如何在Android 10中以编程方式重新启动应用?

huangapple go评论68阅读模式
英文:

How to programmatically restart an app in Android 10?

问题

我想要一种在用户进行应用内购买以移除广告横幅后重新启动应用的方法,以便调用onCreate()方法。

问题是,我不希望终止任何服务,我只希望应用以更改后的限制重新启动。

我在Stack Overflow上找到了以下代码:

Intent mStartActivity = new Intent(getApplicationContext(), MainActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(getApplicationContext(), mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
英文:

I want a way to restart an app after the user has made any in-app purchase that removes ad banners, so that the onCreate() methods gets called again.

The problem is, I don’t want any services to be killed, I just want the app to restart with changed restrictions

I found this code on Stack Overflow:

Intent mStartActivity = new Intent(getApplicationContext(), MainActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(getApplicationContext(), mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

答案1

得分: 6

Update: 要重新启动您的应用程序,请在设置以下标志的同时使您的根活动的意图:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

这将确保启动您的根活动的新实例(第一个标志),同时弹出堆栈上的所有先前活动(第二个标志)


在同一活动内部时,使用recreate()

如果您的应用程序未在运行,则在打开时已经刷新了。

英文:

Update: To restart your application, Make your Root Activity's Intent, while setting these flags

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

This will ensure a fresh instance of your root activity is launched (the first flag), while all previous activities are popped off the stack (the second flag)

<hr>

<strike>Use recreate() when inside the same activity.</strike>

If your app is not running, it's already refreshed on opening anyways.

答案2

得分: 3

尝试这样做:

意图 刷新 = new 意图(获取活动(), 主活动.class);
开始活动(刷新);
英文:

Try this:

Intent refresh= new Intent(getActivity(), MainActivity.class);
startActivity(refresh);

huangapple
  • 本文由 发表于 2020年10月7日 20:58:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64244495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定