Permanently modify Intent that started an Activity

时光毁灭记忆、已成空白 提交于 2019-12-22 04:06:23

问题


I would like send an Intent to start an Activity. I would like to be able to modify that Intent. Then, when the activity is destroyed and recreated, I would like those modifications to still be present when I call getIntent().

Currently, modifying the intent works fine as long as the Activity has not been destroyed. If it has, then when the activity is recreated, it will get the original Intent that started it, and not the copy it received when it was launched the first time that may have modified.


回答1:


Modifying the Intent to remove my extra data works fine as long as the main Activity is still around, but if it's destroyed/recreated, the extra data is back.

That's because you are modifying your local copy of the Intent, not the master copy maintained in an OS process, where the task lists are kept.

If this data is truly instance state of the activity, it should be saved as such, via onSaveInstanceState(), and you'd get that back via onRestoreInstanceState(). The user of your library would need to forward these events on to you.

If you do not wish to consider this to be instance state, but rather process state, store the data in a singleton.

If the data should live beyond the lifetime of a process, write it to disk somewhere.

I could save the data in the host app's broadcast receiver, and then use and delete it in my code

If by "save the data in the host app's broadcast receiver", that is pointless. A manifest-registered receiver lives for a single broadcast, and then is done.




回答2:


This is not the right thing to do it. What you want to do is save data right ? In such a case you don't have to mess with intents, just change the values and then save them, the next time the app runs it will load the values from last time, here is some code:

How to save values:

//Create sharedPref (It's android's way of saving values)
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();

//Save Values here
editor.putInt(getString(R.string.saved_high_score), newHighScore);

//Commit changes
editor.commit();

How to load values:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);

More info here: developer.android.com/training/basics/data-storage/shared-preferences.html




回答3:


Try that

activity.setIntent(activity.getIntent());

Works for me



来源:https://stackoverflow.com/questions/20447643/permanently-modify-intent-that-started-an-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!