Activity recreated when returning from camera app

activity-lifecycle, android, android-camera-intent, android-lifecycle

Solution

Apparently configuration of application changes! Add logs in onDestroy and improve log in onCreate to show what is the value of Bundle savedInstanceState. if savedInstanceState is not null then configuration change enforced recreation of Activity. Adding logs in onSaveInstanceState(Bundle) could help to.

You can handle yourself configuration changes by setting Activity property android:configChanges in manifest.

Problem

This issue is only occurring on two older Samsung Galaxy models, but is nevertheless very reproducable. I have a simple app that displays a photo that is taken through the device's camera app. It has one button to start that app, and processes the result in an AsyncTask to downsample it into an ImageView. The trouble arises from the flow of the activity when returning from the camera app: for some reason, the activity is created, processes result in an AsyncTask in the `onActivityResult()`, is destroyed, only to immediately be recreated. Once the AsyncTask completes, it hold a reference to the incorrect/old activity. Placing some debug statements into the various lifecycle callbacks reveals this odd behavior: ``` 06-02 16:01:53.509: I/myapp(4437): onCreate com.myapp.PhotoActivity_@488cbef8 06-02 16:01:53.509: I/myapp(4437): onResume com.myapp.PhotoActivity_@488cbef8 06-02 16:01:58.298: I/myapp(4437): onPause com.myapp.PhotoActivity_@488cbef8 06-02 16:01:59.470: I/myapp(4437): onStop com.myapp.PhotoActivity_@488cbef8 [a photo is taken in the camera app] 06-02 16:02:10.196: I/myapp(4437): onCreate com.myapp.PhotoActivity_@4874f8b8 06-02 16:02:10.251: I/myapp(4437): onActivityResult com.myapp.PhotoActivity_@4874f8b8 06-02 16:02:10.259: I/myapp(4437): onResume com.myapp.PhotoActivity_@4874f8b8 06-02 16:02:10.712: I/myapp(4437): onPause com.myapp.PhotoActivity_@4874f8b8 06-02 16:02:10.720: I/myapp(4437): onStop com.myapp.PhotoActivity_@4874f8b8 06-02 16:02:10.923: I/myapp(4437): onCreate com.myapp.PhotoActivity_@48817118 06-02 16:02:10.931: I/myapp(4437): onResume com.myapp.PhotoActivity_@48817118 06-02 16:02:12.564: I/myapp(4437): onBitmapLoaded com.myapp.PhotoActivity_@4874f8b8 ``` The instance of the activity on which `onActivityResult()` is called (note the hash codes above) no longer matches the final instance that is being displayed. When my bitmap loading through `onBitmapLoaded()` completes, it therefore also holds the incorrect instance. Why is this happening, and how can I prevent the activity from being (needlessly) recreated?

Original source