简体   繁体   中英

How delete files and folders when the App is uninstalled?

In our App, we have created folders and store some images in internal storage through our app. I want to delete these folders and images when user uninstalls the app.

Here is my code, with the way I am storing currently:

public void cropImage(Uri sourceUri, String fileName) 
{
    File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
            + File.separator
            + getString(R.string.app_name) + File.separator + getString(R.string.app_name_images) + File.separator);
    if (!myDir.exists()) {
        myDir.mkdirs();
    }
    File outputFile = new File(myDir, fileName);

    UCrop.of(sourceUri, Uri.fromFile(outputFile)).start(this);
}

Well, that doesn't seem to be achievable as we dont get any callback information regarding uninstall.

what i have tried in my career :

BroadCast Receiver : wont work as once app is uninstalled it doesn't exist anymore on OS therefore wont be able to get broadcast.

Therefore theirs no way to remove folders created on device's external storage.

What you can do :

  • Use getExternalCacheDir(), then the folders created are auto deleted when app is uninstalled.

  • If your app target is API Level 8 or higher, you can use Context#getExternalFilesDir() for your external files and those will be removed on uninstall.

If you put the files in random places over the file system, they won't be removed, and you might leave junk files behind.

If you store it nicely in the folders that belong to your app, they will be removed automatically.

The good news is that starting from some Android version (Kitkat - 4.4), you don't need storage permission if all your files will be in the folders of the app (link here ) :

Starting in Build.VERSION_CODES.KITKAT, no permissions are required to read or write to the returned path; it's always accessible to the calling app. This only applies to paths generated for package name of the calling application. To access paths belonging to other packages, Manifest.permission.WRITE_EXTERNAL_STORAGE and/or Manifest.permission.READ_EXTERNAL_STORAGE are required.

So, my suggestion: put your own temporary/private files in the app's folders, and files the user actually needs (images/audio/video/documents/...) in other folders

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM