Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart Activity with onResume method

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?

like image 294
user1627867 Avatar asked Aug 27 '12 17:08

user1627867


People also ask

How do you 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.

How do you refresh an activity on a resume?

I can use this intent to refresh the activity currently: Intent refresh = new Intent(this, Favorites. class); startActivity(refresh); this. finish();

When onResume () method is called?

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.

What is onResume method?

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.


1 Answers

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.

like image 153
Sam Avatar answered Nov 10 '22 01:11

Sam