Digipng Digipng - 5 months ago 15
Android Question

How to run application of the first with click on the button in android?

I'm writing a android game. I want to click on button, all application runs of the first.

This is my code:

newgame.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent myIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(myIntent);
}
});


This works but when user onBackPressed, opens previous page instead of application is closed. How can i do that run my app again of the first?

Answer

You can recreate the Activity like this:

public void restartActivity() {
    finish();
    startActivity(getIntent());
}

And call the above method from the onClick event:

newgame.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            restartActivity();
        }
    });