user2609847
user2609847

Reputation: 185

restart/refresh whole app on click of a button

My main activity is

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyGame(this));
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

where whole content is with in Mygame class,and I want whole app to restart on click of button which is in MyGame class, how can I do so, I came across this and tried it but nothing worked

OnClickListener retryClicklistener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

//          Intent i = getContext().getPackageManager()
//                   .getLaunchIntentForPackage(getContext().getPackageName() );
//                   
//                   i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
//              //   startActivity( MyGameLongClick);
//          Intent startActivity = new Intent();
//          startActivity.setClass(this,OTHER_ACTIVITY.class);
//          startActivity(startActivity); 


        }};

Upvotes: 2

Views: 6656

Answers (3)

ozbek
ozbek

Reputation: 21183

If that's the main activity, you can use the following method to restart the application:

private void restartSelf() {
    AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + 1000, // one second
            PendingIntent.getActivity(this, 0, getIntent(), PendingIntent.FLAG_ONE_SHOT
                    | PendingIntent.FLAG_CANCEL_CURRENT));
    finish();
}

And call restartSelf() from onClick():

@Override
public void onClick(View v) {
    restartSelf();
}

This will restart your app after one second of button press. Hope this helps.

Upvotes: 2

Shabbir Dhangot
Shabbir Dhangot

Reputation: 9121

I don't think You can do like this. You cant restart activity not whole application.

because Life-cycle of android app is stack. and activity on activity you can not close all the activity at a time. Read this and this.

Upvotes: 0

DjP
DjP

Reputation: 4587

may be recreate() can help you out..

Upvotes: 3

Related Questions