Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to restart Android App after calling ActivityManager.clearApplicationUserData()

My current Android Application needs to call

 ActivityManager.clearApplicationUserData()

to simulate the user clearing App storage

Which works fine.

A side effect of calling clearApplicationUserData() is that the App is (understandably) closed.

Which gives a poor user experience.

I am having difficulty in restarting my Application once I have called clearApplicationUserData().

I have tried using startActivity, Alarm Manager with Pending Intent, Foreground/Background service.

Nothing works.

Is it impossible to restart an Android App having called clearApplicationUserData()?

like image 403
Hector Avatar asked Dec 20 '19 12:12

Hector


2 Answers

(1st answer: this answer only works on limited situations. it's not a complete answer)

public boolean clearApplicationUserData ()

Description

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

As the reference website stated, we have a returnee before the application is being closed. so, we are going to use this returnee in order to restart the 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 the app will be restarted again.

And also, I think it's a 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.

like image 114
A Farmanbar Avatar answered Nov 15 '22 17:11

A Farmanbar


My suggestion might sound trivial but, have you consider not calling ActivityManager.clearApplicationUserData()?

Here what the docs says about this method:

Permits an application to erase its own data from disk. This is equivalent to the user choosing to clear the app's data from within the device settings UI. It erases all dynamic data associated with the app -- its private data and data in its private area on external storage -- but does not remove the installed application itself, nor any OBB files.

So in order to mimic this behavior you just need to clear you internal and external storage directories. No permissions are needed to access any of those.

like image 41
Ilya Gazman Avatar answered Nov 15 '22 18:11

Ilya Gazman