androidcordovapowermanager

Android - clear application data and reboot device


I am programming an Android-application with cordova. This app gets only installed on dedicated Android 5.1.1-devices. Among others I have the functionality to clear all the apps data. I have implemented this functionality in a cordova-plugin:

// My Cordova Plugin java
if (action.equals("factory_reset")) {
  try {
    Log.i(TAG, "Factory Reset");
    ((ActivityManager)cordova.getActivity().getApplicationContext().getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData();
    rebootDevice();
  } catch (Exception ex) {
    Log.w(TAG, "Error while doing a Factory Reset", ex);
  }
}

I want to reboot the device, after the deletion of all app-data is finished. Here is my reboot-function:

private void rebootDevice(){
  Context mContext = cordova.getActivity().getApplicationContext();
  PowerManager pManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
  pManager.reboot(null);
}

The reboot function itself is working. However I have the problem, that it doesn't reach this function when I call ((ActivityManager)cordova.getActivity().getApplicationContext().getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData(); because the app immediately get's force closed.

How can I solve this? How can I clear the application-data AND reboot the device?


Solution

  • I went for this solution:

    My Plugincode:

    public boolean execute(final String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
      if (action.equals("factory_reset")) {
        clearApplicationData();
        rebootDevice();
      }
    }
    

    The private-functions, that are called:

    private void clearApplicationData() {
      File cache = cordova.getActivity().getApplicationContext().getCacheDir();
      File appDir = new File(cache.getParent());
      Log.d(TAG, "AppDir = " + appDir);
      if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
          if (!s.equals("lib")) {
            Log.d(TAG, "Delete " + s);
            deleteDir(new File(appDir, s));
          }
        }
      }
    }
    
    private void rebootDevice(){
      Context mContext = cordova.getActivity().getApplicationContext();
      PowerManager pManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
      pManager.reboot(null);
    }