Coming back from Camera Intent crashes Activity

2019-02-28 08:55发布

问题:

I have an Activity that launches a Camera Intent like this (nothing special):

    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    File photo = new File(Environment.getExternalStorageDirectory(),  filename);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    Uri imageUri = Uri.fromFile(photo);
    startActivityForResult(intent, CAMERA_REQUEST);

Than I get the result in onActivityResult() and set the bitmap to an ImageView. Again, nothing special.

The problem is that the Camera app is always in landscape. So if the user keeps the device in the horizontal orientation when they hit OK to send it back to my Activity, and my Activity was previously in portrait, then it crashes my activity because it has to rebuild it. If you tilt the device to portrait orientation before you tap OK in the camera, then it does not crash. How do I get around this?

回答1:

You need to override the onSaveInstanceState method to persist the settings of your activity before fit rotates. Then, in the onCreate method, you can check to see if the Bundle argument is null. If not, then you are recreating your activity and should load the saved settings from it.



回答2:

The quick and dirty route would be to handle the orientation change yourself. If your application doesn't have a different layout for landscape and portrait, then this is a good route to take. Here's how.

Add android:configChanges="orientation" to your Activity in the AndroidManifest.

The other thing you can do is make sure your onSaveInstanceState is persisting the camera data and any other data you may be using so that when the application reloads itself, you can reload that data in onRestoreInstanceState. If you share your LogCat errors, you'd probably see a NullPointerException which is because the data is being lost on the rotate. I'd put my money its the camera data.



回答3:

If you don't really need landscape support for your application, you can also block the activity to portrait mode and you don't have to manage the orientation changes.. you can do that in manifest by setting the android:screenOrientation="portrait" attribute to your activity.

If you want to have support for landscape too, then I'm afraid that you have to take a look at Brigham's answer .