How to programmatically restart an app in Android 10?

Viewed 6238

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);
2 Answers

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)


Use recreate() when inside the same activity.

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

Try this:

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