user157195
user157195

Reputation:

How to restart Activity in Android

How do I restart an Android Activity? I tried the following, but the Activity simply quits.

public static void restartActivity(Activity act){

        Intent intent=new Intent();
        intent.setClass(act, act.getClass());
        act.startActivity(intent);
        act.finish();

}

Upvotes: 435

Views: 390823

Answers (23)

Akshay
Akshay

Reputation: 103

Kotlin way:

fun Activity.restartActivity() {
    if (Build.VERSION.SDK_INT >= 11) {
        recreate()
    } else {
        finish()
        startActivity(getIntent())
    }
}

Upvotes: 1

Shakthi
Shakthi

Reputation: 15

Simple way is

    public void restartActivity(){
    Intent i = getIntent();
    finish();
    startActivity(i);
}

Upvotes: 0

OhhhThatVarun
OhhhThatVarun

Reputation: 4330

If anybody is looking for Kotlin answer you just need this line.

Fragment

startActivity(Intent.makeRestartActivityTask(activity?.intent?.component))

Activity

startActivity(Intent.makeRestartActivityTask(this.intent?.component))

Upvotes: 14

shkschneider
shkschneider

Reputation: 18253

I wonder why no one mentioned Intent.makeRestartActivityTask() which cleanly makes this exact purpose.

Make an Intent that can be used to re-launch an application's task * in its base state.

startActivity(Intent.makeRestartActivityTask(getActivity().getIntent().getComponent()));

This method sets Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK as default flags.

Upvotes: 28

MicroRJ
MicroRJ

Reputation: 173

This is the way I do it.

        val i = Intent(context!!, MainActivity::class.java)
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        startActivity(i)

Upvotes: -2

Rajesh Peram
Rajesh Peram

Reputation: 1208

The solution for your question is:

public static void restartActivity(Activity act){
    Intent intent=new Intent();
    intent.setClass(act, act.getClass());
    ((Activity)act).startActivity(intent);
    ((Activity)act).finish();
}

You need to cast to activity context to start new activity and as well as to finish the current activity.

Hope this helpful..and works for me.

Upvotes: 4

Thomas Vos
Thomas Vos

Reputation: 12581

I used this code so I still could support older Android versions and use recreate() on newer Android versions.

Code:

public static void restartActivity(Activity activity){
    if (Build.VERSION.SDK_INT >= 11) {
        activity.recreate();
    } else {
        activity.finish();
        activity.startActivity(activity.getIntent());
    }
}

Sample:

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Activity mActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mActivity = MainActivity.this;

        Button button = (Button) findViewById(R.id.restart_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                restartActivity(mActivity);
            }
        });
    }

    public static void restartActivity(Activity activity) {
        if (Build.VERSION.SDK_INT >= 11) {
            activity.recreate();
        } else {
            activity.finish();
            activity.startActivity(activity.getIntent());
        }
    }
}

Upvotes: 39

code
code

Reputation: 2163

This is by far the easiest way to restart the current activity:

finish();
startActivity(getIntent());

Upvotes: 28

user3748515
user3748515

Reputation: 261

This solution worked for me.

First finish the activity and then start it again.

Sample code:

public void restartActivity(){
    Intent mIntent = getIntent();
    finish();
    startActivity(mIntent);
}

Upvotes: 24

Mihir Trivedi
Mihir Trivedi

Reputation: 1505

If you are calling from some fragment so do below code.

Intent intent = getActivity().getIntent();
getActivity().finish();
startActivity(intent);

Upvotes: -1

Ben
Ben

Reputation: 16534

Before SDK 11, a way to do this is like so:

public void reload() {
    Intent intent = getIntent();
    overridePendingTransition(0, 0);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    finish();
    overridePendingTransition(0, 0);
    startActivity(intent);
}

Upvotes: 140

kike0kike
kike0kike

Reputation: 115

Call the method onCreate. For example onCreate(null);

Upvotes: -7

The4thIceman
The4thIceman

Reputation: 3899

In conjunction with strange SurfaceView lifecycle behaviour with the Camera. I have found that recreate() does not behave well with the lifecycle of SurfaceViews. surfaceDestroyed isn't ever called during the recreation cycle. It is called after onResume (strange), at which point my SurfaceView is destroyed.

The original way of recreating an activity works fine.

Intent intent = getIntent();
finish();
startActivity(intent);

I can't figure out exactly why this is, but it is just an observation that can hopefully guide others in the future because it fixed my problems i was having with SurfaceViews

Upvotes: 4

Amsheer
Amsheer

Reputation: 7141

public void onRestart() {
    super.onRestart();
    Intent intent=new Intent();
    intent.setClass(act, act.getClass());
    finish();
    act.startActivity(intent);
}

try to use this ..

Upvotes: 3

Justin Morris
Justin Morris

Reputation: 7329

Just to combine Ralf and Ben's answers (including changes made in comments):

if (Build.VERSION.SDK_INT >= 11) {
    recreate();
} else {
    Intent intent = getIntent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    finish();
    overridePendingTransition(0, 0);

    startActivity(intent);
    overridePendingTransition(0, 0);
}

Upvotes: 117

EboMike
EboMike

Reputation: 77762

I did my theme switcher like this:

Intent intent = getIntent();
finish();
startActivity(intent);

Basically, I'm calling finish() first, and I'm using the exact same intent this activity was started with. That seems to do the trick?

UPDATE: As pointed out by Ralf below, Activity.recreate() is the way to go in API 11 and beyond. This is preferable if you're in an API11+ environment. You can still check the current version and call the code snippet above if you're in API 10 or below. (Please don't forget to upvote Ralf's answer!)

Upvotes: 684

Codeversed
Codeversed

Reputation: 9473

Well this is not listed but a combo of some that is already posted:

if (Build.VERSION.SDK_INT >= 11) {
    recreate();   
} else {
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

Upvotes: 15

Achal Dave
Achal Dave

Reputation: 4419

There is one hacky way that should work on any activity, including the main one.

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

When orientation changes, Android generally will recreate your activity (unless you override it). This method is useful for 180 degree rotations, when Android doesn't recreate your activity.

Upvotes: 4

Chris.Jenkins
Chris.Jenkins

Reputation: 13139

Even though this has been answered multiple times.

If restarting an activity from a fragment, I would do it like so:

new Handler().post(new Runnable() {

         @Override
         public void run()
         {
            Intent intent = getActivity().getIntent();
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
            getActivity().overridePendingTransition(0, 0);
            getActivity().finish();

            getActivity().overridePendingTransition(0, 0);
            startActivity(intent);
        }
    });

So you might be thinking this is a little overkill? But the Handler posting allows you to call this in a lifecycle method. I've used this in onRestart/onResume methods when checking if the state has changed between the user coming back to the app. (installed something).

Without the Handler if you call it in an odd place it will just kill the activity and not restart it.

Feel free to ask any questions.

Cheers, Chris

Upvotes: 16

Ralf
Ralf

Reputation: 14840

Since API level 11 (Honeycomb), you can call the recreate() method of the activity (thanks to this answer).

The recreate() method acts just like a configuration change, so your onSaveInstanceState() and onRestoreInstanceState() methods are also called, if applicable.

Upvotes: 404

Nikhil Dinesh
Nikhil Dinesh

Reputation: 3409

Call this method

private void restartFirstActivity()
 {
 Intent i = getApplicationContext().getPackageManager()
 .getLaunchIntentForPackage(getApplicationContext().getPackageName() );

 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
 startActivity(i);
 }

Thanks,

Upvotes: 21

Sandy
Sandy

Reputation: 2692

Actually the following code is valid for API levels 5 and up, so if your target API is lower than this, you'll end up with something very similar to EboMike's code.

intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
overridePendingTransition(0, 0);

Upvotes: 3

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 16367

If you remove the last line, you'll create new act Activity, but your old instance will still be alive.

Do you need to restart the Activity like when the orientation is changed (i.e. your state is saved and passed to onCreate(Bundle))?

If you don't, one possible workaround would be to use one extra, dummy Activity, which would be started from the first Activity, and which job is to start new instance of it. Or just delay the call to act.finish(), after the new one is started.

If you need to save most of the state, you are getting in pretty deep waters, because it's non-trivial to pass all the properties of your state, especially without leaking your old Context/Activity, by passing it to the new instance.

Please, specify what are you trying to do.

Upvotes: 1

Related Questions