0

I want to know what is the proper method to clear the Android application's data.

I have tried to implement this method below, but it force closed my app, which is not a good thing for user experience.

    private void clearAppData() {
        try {
            // clearing app data
            if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
                ((ActivityManager)getSystemService(ACTIVITY_SERVICE))
                        .clearApplicationUserData();// note: it has a return value!
            } else {
                String packageName = getApplicationContext().getPackageName();
                Runtime runtime = Runtime.getRuntime();
                runtime.exec("pm clear "+packageName);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Already tried to mixing it with uncaughtExceptionmethod for restarting the app after being force closed, but the uncaughtExceptionmethod is not triggered after app closed.

public class MainActivity extends Activity {

    Context context;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                MainActivity.restartApp(context);
            }
        });

        ...

    }

    public static void restartApp(Context context){
        Intent mStartActivity = new Intent(context, MainActivity.class);
        int mPendingIntentId = 123456;
        PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
        System.exit(0);
    }

    ...

}

I alternatively also have tried using the method provided in the links below. but somehow the data was not cleared.

https://stackoverflow.com/a/9073473/15835391

https://stackoverflow.com/a/31988855/15835391

Any help would be greatly appreciated.

Thank you.

0 Answers0