开发者

How to delete a folder when user selects uninstall my application in android

开发者 https://www.devze.com 2023-02-27 10:05 出处:网络
I would like to know about how to delete a folder once user select uninstall button for my application.

I would like to know about how to delete a folder once user select uninstall button for my application. I want it by 开发者_C百科programmatically is there any chance to do it... If so let me know possible solution for it. thanks in advance.


If you created any folders on a device's external storage... there is no way for you to call code when the user uninstalls your app. Certain things are removed automatically (databases, anything written to Internal Storage), but not folders on external storage.

EDIT - As pointed out by Stephan, if you are targeting API Level 8 or higher, you can use Context.getExternalFilesDir() for your external files and those will be removed on uninstall.


Here is an idea. If you are concerned about the fact that the files that are not deleted during an uninstall will be messing up the user onboarding process when he later re-installs your app as in this question then you could simply ensure that all data is deleted at the moment your app is reinstalled (or simply installed for that matter). It's a "if Mohammed does not go to the mountain, the mountain will go to Mohammed" kind of hack. Obviously you would have to set a flag in shared preferences so the process of deleting the content of ExternalStorageDir is only performed once before the users very FIRST interaction with your app here is some sample code:

SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstInteraction = sharedPreferences.getBoolean("isFirstUsage", true);
if(isFirstInteraction){
    trimCache(this);
    SharedPreferences.Editor editor=sharedPreferences.edit();
    editor.putBoolean("isFirstUsage",false);
    editor.apply();
}
//delete files from external files dir
public static void trimStorage(Context context) {
    try {
        File dir = context.getExternalFilesDir();
        if (dir != null && dir.isDirectory()) {
            deleteDir(dir);

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

    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                Log.d("deletion","failed at "+children[i]);
                return false;
            }
        }
    }

    // The directory is now empty so delete it
    return dir.delete();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号