简体   繁体   中英

App hangs on Camera.release()

I have an application that calls a custom activity within it for the purpose of recording audio and video. It uses the MediaRecorder and the Camera classes. My issue is that when the user hits the back button or cancel while the video is recording, the activity always hangs on Camera.release(), but if the stop button is pressed first, there's no problem. Here's my code:

Stop button code:

mRecorder.stop();   // Stop recording
mRecorder.reset();  // Reset recorder
camera.stopPreview();

onDestroy():

mRecorder.reset();  // Release media recorder
mRecorder.release();
if (camera != null) {
    camera.stopPreview();
    camera.setPreviewCallback(null);
    camera.release();
}
mRecorder = null;
camera = null;

I tried adding mRecorder.stop() to onDestroy() as well but that didn't solve it. I checked here but none of the answers worked. I'm really stumped with this one.

Code such as this should be put in onPause() and not onDestroy() to be sure it gets called when needed.

According to the docs

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

You aren't saving data here but the same principle applies. So stopping the recording in onPause() will guarantee the code runs when the user presses the Back button.

Overriding onBackPressed() would work too but that wouldn't account for if the Activity went into the background for other reasons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM