Home > Mobile >  How to restart app and clear all data with Button
How to restart app and clear all data with Button

Time:10-09

If you go to the program information on the phone, you will see delete all data. The question is how to do it in Java in MainActivity and reboot it. Is it even possible to do that? I need this to sign out. In my project (MainActivity) there is a login via Google and Email & Password. When I call the signOut () function, I don't log out of my accounts. And to make life easier, I decided to clean and restart.

Button btnClearAndRestart = findViewById(R.id.btn);
btnClearAndRestart.setOnClickListener(new View.OnClickListener(){
    //Delete all app data and restart app
});

CodePudding user response:

public boolean clearApplicationUserData ()

Return: true if the application successfully requested that the application's data be erased; false otherwise.

We have a returnee before application is being closed. so, we are going to use this returnee in order to restart app.

if(ActivityManager.clearApplicationUserData)
{
     doRestart = true;
}

when Activity onDestroy() and onStop() are called restart app.

@Override
   protected void onDestroy() {
       super.onDestroy();
       if(doRestart){
           Intent intent = new Intent(this, Activity.class);
           this.startActivity(intent);
       }
   }

@Override
protected void onStop() {
    super.onStop();
    if(doRestart){
        Intent intent = new Intent(this, Activity.class);
        this.startActivity(intent);
    }
}

We put restart action in both onDestroy() and onStop() in order to make sure app will be restarted again.

And also , i think it's good idea to force stop activity before OS stops it.

if(ActivityManager.clearApplicationUserData)
{
     doRestart = true;
     finish(); <= i mean this 
}

it's because , it makes sure that onDestroy() and onStop() will be invoked.

  • Related