I'd like to restart an activitiy with the onResume() method. I thought i can use an Intent to achieve that, but that ends in an endless loop.
@Override
protected void onResume() {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(intent);
finish();
super.onResume();
}
Is there another way to restart an activity?
This example demonstrates how do I restart an Activity in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.
I can use this intent to refresh the activity currently: Intent refresh = new Intent(this, Favorites. class); startActivity(refresh); this. finish();
Scenario 1: Start an Activity, Press the Home Button and Open the App again. When we open an Activity, at that time the Activity's onCreate(), onStart() and onResume() is get called sequentially. After that, the Activity is visible and interactive to the user.
onResume() is one of the methods called throughout the activity lifecycle. onResume() is the counterpart to onPause() which is called anytime an activity is hidden from view, e.g. if you start a new activity that hides it. onResume() is called when the activity that was hidden comes back to view on the screen.
I would question why you want to do this... but here is the first thing that popped into my mind:
@Override
protected void onCreate(Bundle savedInstanceState) {
...
Log.v("Example", "onCreate");
getIntent().setAction("Already created");
}
@Override
protected void onResume() {
Log.v("Example", "onResume");
String action = getIntent().getAction();
// Prevent endless loop by adding a unique action, don't restart if action is present
if(action == null || !action.equals("Already created")) {
Log.v("Example", "Force restart");
Intent intent = new Intent(this, Example.class);
startActivity(intent);
finish();
}
// Remove the unique action so the next time onResume is called it will restart
else
getIntent().setAction(null);
super.onResume();
}
You should make "Already created"
unique so that no other Intent might accidentally has this action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With