问题
I seem to be missing something as I fail to understand why in Android documentation (Android Camera doc. link) it is recommended to release Camera object (as well as MediaRecorder) in onPause() Activity callback? Activity still might be visible by that time and Camera might be running preview so why the Camera object would be released in onPause() rather then onStop() when activity is already hidden? I understand that MediaRecorder object could be stopped in onPause() but Camera itself doesn't make sense to me. What am I missing here? Piece of code from Android documentation is below (its under Releasing the Camera heading):
@Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first
releaseCamera(); // release the camera immediately on pause event
}
private void releaseMediaRecorder(){
if (mMediaRecorder != null) {
mMediaRecorder.reset(); // clear recorder configuration
mMediaRecorder.release(); // release the recorder object
mMediaRecorder = null;
mCamera.lock(); // lock camera for later use
}
}
回答1:
according to application lifecycle
Paused
Another activity is in the foreground and has focus, but this one is
still visible. That is, another activity is visible on top of this
one and that activity is partially transparent or doesn't cover the
entire screen. (...)
I think the documentation follows the rule of the thumb "release resources as soon as possible": onPause
is earlier than onStop
.
camera in the background window needs energy while the user has to to pay attentions to the popup.
Camera in the backgroud is of course more comfortable but for a mobile battery life time is more important.
The popup that intercepted you activity might need the camera and/or might need a lot of memory.
In your scenario when the camera should continue recording in the background the camera-s lifecycle and recording should be controlled by a service
回答2:
Once your activity receives the onPause message it means that the user might be using or going to use some other application .. in this case if he tries to use camera through other application the camera must be in freed or released by your application.
回答3:
Since
onStop
() is not guaranteed to be called, you can't always do in onStop() what is done inonPause().
For Detail Answer
onPause()
is always called. This is guaranteed. If you need to save any state in your activity you need to save it in onPause(). onStop()
may be called after onPause(), or it may not. Depends on the situation.
回答4:
onPause would mean your activity is no longer visible.
onStop would only be called if Android didn't think your process was needed anymore.
来源:https://stackoverflow.com/questions/11839000/why-camera-needs-to-be-released-in-onpause-rather-than-onstop-method-of-acti