Prevent activity from being destroyed

14.2k Views Asked by At

I'm sending an intent to the camera from an activity that I call like this:

 Intent testphoto = new Intent(Dashboard.this,CameraHandler.class);
 startActivity(testphoto);

In the CameraHandler class I call the camera:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
startActivityForResult(intent, 0);

But before onActivityResult gets called in the CameraHandler class the activity is destroyed. Is there anyway to prevent this?

FOUND THE ANSWER: I had noHistory="true" in my AndroidManifest and that made the OS destroy the activity before the result.

3

There are 3 best solutions below

8
On

You don't have to worry about the calling Activity being destroyed when you call startActivityForResult(), as it won't change the expected behavior at all (i.e. the child activity will remember to pass the result back to the parent whether the parent is destroyed or not). See this post.

Also note that while it is sometimes necessary to prevent Activitys from being destroyed (i.e. on configuration changes, etc.), in general you want to leave the Activity lifecycle alone and let the system manage background Activitys for you. Once you launch a new Activity, you shouldn't be explicitly preventing previous Activitys from being destroyed.

3
On
7
On

Be sure you don't have the "Don't keep activities" Developer setting on, as it will destroy the activity you are leaving.