Is there any way to have one and only one instance

2019-01-22 06:21发布

I'm finding that in my application, the user can get quite 'nested' in the various activities that are opened while the user is using the application.

For example:

  1. Main Menu
  2. Object List
  3. Object Details
  4. Object Edit
  5. Object Details
  6. Object Child Details
  7. Object Child Edit
  8. Object Child Details

Now, when the user presses back, it has to go through 'Object Child Details' twice (same object, when it is edited it returns to the detailed page), and the same thing happens for the 'Parent Object Details'.

Is there a way to reuse activities, if they are already open in the stack, and reorder them to the front? The only way I have seen is on activities with the launcher attribute. I believe I saw singleTask and singleTop.

If am supposed to be using these two attributes, singleTask and singleTop, how am I supposed to use them? When I tried to include them in the application, it made no difference. Do I also need to set a flag while launching the intent using startActivity?

7条回答
三岁会撩人
2楼-- · 2019-01-22 06:53

Yes you can demand only one instance of these activities be created, but it is generally not recommended. If you simply are concerned about history, take a look at Intent.FLAG_ACTIVITY_CLEAR_TOP.

查看更多
迷人小祖宗
3楼-- · 2019-01-22 06:55

This is your flag! http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_REORDER_TO_FRONT

intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)

Note the 'addFlags'. Also note that, onCreate will not be called on this Activity when a new Intent is delivered to it. It will be delivered via the onNewIntent().

This does not ensure that there is a single instance of the Activity running. To ensure that, check this out: http://developer.android.com/guide/topics/manifest/activity-element.html#lmode

查看更多
聊天终结者
4楼-- · 2019-01-22 07:01

in Manifest Activity property you can give this parameter android:launchMode="singleInstance"

Read in more detail here http://developer.android.com/guide/topics/manifest/activity-element.html

查看更多
对你真心纯属浪费
5楼-- · 2019-01-22 07:05

Add intent Flags as

Intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP); StartActivity(srcActivity.java, DesiredActivity.class);

Then at onPause() DesiredActivity

Add finish(), This did the work for me.

查看更多
看我几分像从前
6楼-- · 2019-01-22 07:07

This worked for me.

Intent intent = new Intent(this, MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

If an instance of this Activity already exists, then it will be moved to the front. If an instance does NOT exist, a new instance will be created.

查看更多
劫难
7楼-- · 2019-01-22 07:07
Intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_NO_HISTORY);

It works for me :)

查看更多
登录 后发表回答