Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically restart an app in Android 10?

Tags:

java

android

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);
like image 888
User104163 Avatar asked Sep 05 '25 00:09

User104163


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.

like image 51
Arvind Avatar answered Sep 07 '25 19:09

Arvind


Try this:

Intent refresh= new Intent(getActivity(), MainActivity.class);
startActivity(refresh);
like image 22
Francesco Bocci Avatar answered Sep 07 '25 19:09

Francesco Bocci