问题
Well, in my application I'm using default camera and gallery of Android with startActivityforResult as;
Intent i = new Intent("android.intent.action.PICK",
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.setType("image/*");
startActivityForResult(i, this.SELECT_PICTURE);
I am able to catch onActivityResult as well. However, if memory is low and I start this activity, I experienced that system is killing my parent activity, and even if the activity returns with a value, I lost all my local variables (and onCreate() is called again). Only onResume() should be called again.
I tried several times, I'm pretty sure that it is related with memory issue. If there is enough memory process is performed successfully. How can I prevent this behaviour?
Since Android doesn't kill application in foreground, can I still use this feature? I think my problem is almost similar with this one .
Solution
In addition to solution provided by Yahel, usage of following methods can work.
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
}
回答1:
You need a good read of the must-read-before-you code article : http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
You activitie can and will be killed by Android if memory is low. But it will be notified and there is a very well defined way of dealing with this.
This is the reason of existence of the Bundle savedInstanceState
in all your activities oncreate : public void onCreate(Bundle savedInstanceState)
During the onpause of your app, you should save all you need to recreate the state your app is in and during the oncreate of your app you should check if you are coming back with a full savedInstanceState and restore your app from there.
Good luck.
回答2:
Have you considered using some type of persistent storage? Save the data you need saved in persistent storage (shared preferences, db, file system, etc.) before you call the new intent, with some sort of reconstruction flag. Then if the activity calls onCreate and the flag is up, you can restore the previous activity state. Make sure to clear the reconstruction flag when its not needed, which should be in onResume.
Edit:
onSaveInstanceState seems to be the way for data local to the activity.
来源:https://stackoverflow.com/questions/8988946/android-is-killing-my-application-whenever-startactivityforresult-is-called