Permanently modify Intent that started an Activity

2019-04-22 14:43发布

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.

3条回答
叼着烟拽天下
2楼-- · 2019-04-22 15:10

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楼-- · 2019-04-22 15:13

Try that

activity.setIntent(activity.getIntent());

Works for me

查看更多
乱世女痞
4楼-- · 2019-04-22 15:30

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.

查看更多
登录 后发表回答