以编程方式重启Android应用 [英] Restarting Android app programmatically

查看:89
本文介绍了以编程方式重启Android应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是该问题的后续问题:

This is a follow up question to this question:

强制应用程序在首次活动时重新启动

我正在尝试从这样的片段重新启动我的应用程序:

I am trying to restart my application from a fragment like that:

    Toast.makeText(getActivity(), "Restarting app", Toast.LENGTH_SHORT).show();
    Intent i = getActivity().getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getActivity().getBaseContext().getPackageName() );
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
    getActivity().finish();

该代码不执行任何操作.由于某些原因,finish()是唯一起作用的东西.如果删除finish(),则什么也不会发生.为什么会这样?

The code does nothing. The finish() is the only thing working for some reason. If I remove the finish(), nothing happens. Why is that?

推荐答案

如果您只是考虑切换到开始的Activity,请参考

If you just consider to switch to your starting Activity, refer to Ricardo's answer. But this approach won't reset static context of your app and won't rebuild the Application class, so the app won't be really restarted.

如果您想完全重启您的应用程序,我可以建议使用PendingIntent更为彻底的方式.

If you want to completely restart your app, I can advise more radical way, using PendingIntent.

private void restartApp() {
    Intent intent = new Intent(getApplicationContext(), YourStarterActivity.class);
    int mPendingIntentId = MAGICAL_NUMBER;
    PendingIntent mPendingIntent = PendingIntent.getActivity(getApplicationContext(), mPendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
    System.exit(0);
}

PS .在我的项目中试用过您的代码-在有finish()和没有finish()的情况下都能很好地工作.因此,也许您还没有写有关Activity或Fragment的特定内容.

P.S. Tried your code in my project - works well with and without finish(). So maybe you have something specific about your Activity or Fragment, you haven't written.

这篇关于以编程方式重启Android应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆