'How to clean the resources in case android app crashed or manually killed?

In android app, I've been saving data in an external directory during the application run. After performing some operations I've been deleting the data so this case has no issue, but I want data to be deleted in case either app get crashed or manually killed by the user. What would be the more appropriate & standardized way to handle this case?



Solution 1:[1]

For force kill I am not sure but in case of crash you can delete the data as follows:

create a class used to handle unCaughtException

 public class MyExceptionHandler implements
            java.lang.Thread.UncaughtExceptionHandler {
        private final Context myContext;
        private final Class<?> myActivityClass;

        public MyExceptionHandler(Context context, Class<?> c) {

            myContext = context;
            myActivityClass = c;
        }

        public void uncaughtException(Thread thread, Throwable exception) {

            //delete your data
        }
    }

and in every Activity create an Object of this class and set it as the DefaultUncaughtExceptionHandler

Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
            YourCurrentActivity.class));

Solution 2:[2]

For killing of the app from recent bar: onDestryoy() method is called.

public void onDestroy(){ 
  super.onDestroy(); 
  // delete you data here
}

and for ANR(Application Not Responding) or crash you should use:

 public class MyExceptionHandler implements
        java.lang.Thread.UncaughtExceptionHandler {
    private final Context myContext;
    private final Class<?> myActivityClass;

    public MyExceptionHandler(Context context, Class<?> c) {

        myContext = context;
        myActivityClass = c;
    }

    public void uncaughtException(Thread thread, Throwable exception) {

        //delete your data
    }
}

and in every Activity create an Object of this class and set it as the DefaultUncaughtExceptionHandler

Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
            YourCurrentActivity.class));

Solution 3:[3]

Place the delete code in below method:

public void onDestroy() { super.onDestroy(); }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Firu
Solution 2 Shubham Agrawal
Solution 3 Armel