How to use IntentCompat.makeRestartActivityTask()?

2019-02-12 16:08发布

I'm trying to implement a button that will result in my app going back to the first activity and acting as if it was (almost) restarted all over. This code

Intent newIntent =
        new Intent(currentActivity.getApplicationContext(), StartActivity.class);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK + Intent.FLAG_ACTIVITY_CLEAR_TASK);
currentActivity.startActivity(newIntent);

seems to be working OK for a newer tablet that is running Android 4.1, but it doesn't work on an older device that is running Android 2.3.4.

I've found a couple of threads about this:

Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK not working Android

Clear all activities in a task?

Reading the fine print leads me to believe I should be using the IntentCompat class in android-support-v4.jar, http://developer.android.com/reference/android/support/v4/content/IntentCompat.html

Unfortunately, the documentation does not contain any examples, and I'm very unsure of how I should be using IntentCompat. The only example I've found is this: Not start MainActivity with android 2.3

which leads me to believe I should be doing something like this:

    Intent newIntent = IntentCompat.makeRestartActivityTask(cn);

But this is giving me a compiler error, saying "makeRestartActivityTask" is an undefined symbol.

I'm guessing this implies I haven't added android-support-v4.jar correctly to my build environment (IntelliJ IDEA 12 community edition), but I've tried doing that in several different ways, and it still doesn't work.

So I have two questions:

  1. Does my attempted usage of IntentCompat look correct?

  2. How do I get the compiler to stop saying that "makeRestartActivityTask" is an undefined symbol?

3条回答
相关推荐>>
2楼-- · 2019-02-12 16:31

This is how I'm using IntentCompat

    Intent intentToBeNewRoot = new Intent(this, MainActivity.class);
    ComponentName cn = intentToBeNewRoot.getComponent();

    Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);

    startActivity(mainIntent);

This effectively replaces my no-longer-wanted task root with MainActivity. It works in Gingerbeard and ICS. I haven't seen the "is an undefined symbol" message.

查看更多
Emotional °昔
3楼-- · 2019-02-12 16:32

IntentCompat is deprecated which is may be deleted, but Intent class this static method

Intent mainIntent = Intent.makeRestartActivityTask(cn);

So just use the above statement.

查看更多
仙女界的扛把子
4楼-- · 2019-02-12 16:42

Update

Google has removed the method IntentCompat.makeRestartActivityTask() in current support library versions. Instead, you can just use the plain Android API:

ComponentName cn = intent.getComponent();
Intent.makeRestartActivityTask(cn);

I hope this can save someone time searching for alternatives ;)

查看更多
登录 后发表回答