0

NOTE: This resembles a duplicate but none of the others solved my problem

@Hitesh Tarbundiya's answer in Step 2 solved my problem

I am using the natario1 CameraView library for android to record video.

I am working with a Fragment.

I have written code to

  1. Stop the video recording

  2. Save the recorded video

  3. Update the media gallery with the newly created video file

But what I can't figure out now is where to call those methods when the user presses the back button or home button on their phone before the fragment is destroyed.

I have tried calling the methods from the onPause() onStop() onDestroyView() and onDestroy() but have not succeeded.

Would appreciate some advice, thanks.

FlashspeedIfe
  • 368
  • 1
  • 6
  • 15
  • try onBackPressed() – Hitesh Tarbundiya Mar 15 '19 at 04:21
  • @HiteshTarbundiya I don't have access to that method in a `Fragment` class – FlashspeedIfe Mar 15 '19 at 04:30
  • https://stackoverflow.com/questions/5448653/how-to-implement-onbackpressed-in-fragments – ADM Mar 15 '19 at 04:34
  • @ADM I tried to implement the solution in the stackoverflow answer you linked to. While I'am able to trigger code to run when the back button is pressed I think the issue now is that the `cameraView.close()` method is running in another thread so even when I call it in the implemented `onBackPressed()` in the `Fragment` it doesn't work. the `.close()` method returns `void` a good return value (say a Boolean) would have been great. – FlashspeedIfe Mar 15 '19 at 06:10

1 Answers1

2

try this, may solved your issue.

@Override
public void onBackPressed() {
  if (mMediaRecorder != null) {
   //Wtire your code for stop video, on back press
    mMediaRecorder.stop();
    mMediaRecorder.reset();
   }else{
    super.onBackPressed();
   }         
}

If you are in fragment then follow this step.

Step 1:create one interface file

public interface IOnBackPressed {
/**
 * If you return true the back press will not be taken into account, otherwise the activity will act naturally
 * @return true if your processing has priority if not false
 */
boolean onBackPressed();
}

Step 2: in your Activity class implement this,

public class MyActivity extends Activity {
@Override public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
   if (!(fragment instanceof IOnBackPressed) || !((IOnBackPressed) fragment).onBackPressed()) {
      super.onBackPressed();
   }
 } 
}

Step 3: Now in your fragment class implemnt interface write like this,

public class MyFragment extends Fragment implements IOnBackPressed{
@Override
public boolean onBackPressed() {
   if (myCondition) {
        if (mMediaRecorder != null) {
         //Wtire your code for stop video, on back press
         mMediaRecorder.stop();
         mMediaRecorder.reset();
        }
      return true; 
    } else {
        return false;
    }
 }
}