强制应用程序重新启动第一个活动

Sep*_*phy 68 android

由于未知原因,我无法正确地离开应用程序,因此当我再次按下主页按钮和应用程序图标时,我会恢复应用程序中的位置.我想强制应用程序在第一个Activity上重新启动.

我想这与onDestroy()或者onPause()有关,但我不知道该怎么做.

小智 148

以下是使用PackageManager以通用方式重新启动应用程序的示例:

Intent i = getBaseContext().getPackageManager()
             .getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
Run Code Online (Sandbox Code Playgroud)

  • 不工作,只是在启动活动中恢复,应用程序类没有重置 (7认同)
  • 它对我有所帮助.谢谢.我喜欢这样,"try {Intent i; i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName()); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i);} catch(NameNotFoundException) e){e.printStackTrace();} (3认同)
  • 使用标志作为`Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK`,这很好用,也可以清除活动堆栈。 (2认同)

AAv*_*rin 28

标记为"回答"的解决方案有效,但有一个对我来说至关重要的缺点.使用FLAG_ACTIVITY_CLEAR_TOP,您的目标活动将在您的旧活动堆栈收到onDestroy之前调用onCreate.虽然我已经在onDestroy中清除了一些必要的东西,但我不得不工作.

这是对我有用的解决方案:

public static void restart(Context context, int delay) {
    if (delay == 0) {
        delay = 1;
    }
    Log.e("", "restarting app");
    Intent restartIntent = context.getPackageManager()
            .getLaunchIntentForPackage(context.getPackageName() );
    PendingIntent intent = PendingIntent.getActivity(
            context, 0,
            restartIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP);
    AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    manager.set(AlarmManager.RTC, System.currentTimeMillis() + delay, intent);
    System.exit(2);
}
Run Code Online (Sandbox Code Playgroud)

我们的想法是通过AlarmManager触发PendingIntent,稍后会调用它,给旧活动堆栈一些时间来清理.

  • 同意之前的评论。我使用 PendingIntent.FLAG_CANCEL_CURRENT 而不是 Intent.FLAG_ACTIVITY_CLEAR_TOP 来删除警告 (3认同)

jqp*_*liq 15

如果你想总是从根目录开始,你想在你的root活动上设置android:clearTaskOnLaunch为true

  • 那么为什么这个答案被标记为被接受的答案呢? (20认同)
  • 或者以编程方式向 Intent 添加标志 `Intent.FLAG_ACTIVITY_CLEAR_TASK`。 (2认同)

Ris*_*tam 9

android:clearTaskOnLaunch="true"
android:launchMode="singleTask"
Run Code Online (Sandbox Code Playgroud)

在启动类(第一个活动)的清单文件中使用此属性.


归档时间:

查看次数:

91429 次

最近记录:

7 年,4 月 前