问题
I have created a custom camera preview view CameraView
which extends SurfaceView
, and it also implements SurfaceHolder.Callback
interface. The view operates with the camera. When you open the view it shows a camera preview. On the same screen there is also overlay with two buttons - 'Take picture', 'Choose from gallery'. The activity that holds the CameraView
releases and reopens the camera in onPause()
and onResume()
methods.
If I click the 'Choose from gallery' button, the following intent is created:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, LOAD_PICTURE);
If there is only one activity that can respond to this intent then it's fine. The activity gets automatically opened, the camera is released. I can also hit back when on the gallery and I will get back into the CameraView
activity, and camera preview is restored.
The interesting part starts if there are multiple activities that can handle this intent, and the intent chooser dialog pops up. When intent chooser dialog spawns, onPause()
gets called in parent activity and camera gets released, the screen becomes black. If I dont choose intent from the dialog, but instead click back button on the phone onResume()
is called, but camera preview is never coming back. To get the camera preview to show again, I need to go back to previous activity and go back inside the preview activity.
The following problem happens because, when the dialog is raised only onPause()
gets called, but if I actually switch to different activity surfaceDestroyed()
get called also. The same is true for onResume()
when the dialog is canceled with back button, surfaceChanged()
and surfaceCreated()
never gets called.
My question is how to get camera preview to reappear if the intent chooser dialog is canceled. Is there a way how to trigger SurfaceHolder.Callback
methods explicitly?
I know that there are hidden hideSurface()
and showSurface()
in SurfaceView
, but I don't want to go this route.
回答1:
It is right, you have open your camera in the onStart method and release it in the onStop method of your activity. The methods onResume and onPause are part of the visible lifecycle of the android activity. OnStop is called when another activity occupies the whole visible space. OnPause is even called when another activity comes to the foreground even if it does not occupy the whole visible space such as the intent chooser dialog does when it pops up. So I guess moving your camera creation and release into the correct lifecycle methods should do the trick. You can find further information about the activity lifecycle here, but I'm sure you are familiar with that:
http://developer.android.com/reference/android/app/Activity.html
来源:https://stackoverflow.com/questions/8023534/reopening-camera-after-intent-chooser-is-canceled