Search code examples
androidsharedpreferencesuninstallationandroid-backup-service

Delete shared preferences after app uninstall without using android:allowBackup="false"


I want to delete sharedpreferences after the app is uninstalled. And I dont want to use the android:allowBackup="false" option as I read that it is not recommended for apps in production. Is there any other way we can delete the shared preferences for an app after uninstalling while still preserving backups(During upgrades)


Solution

  • You can use BroadcastReceiver for it

    Add this to Manifest

    <receiver android:name=".DeleteReceiver">
        <intent-filter>
            <action android:name="android.intent.action.PACKAGE_REMOVED" />
            <data android:scheme="package"/>
        </intent-filter>
    </receiver>
    

    And BroadcastReceiver class

    public class DeleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //remove preferences
            SharedPreferences settings = context.getSharedPreferences("PreferencesName", Context.MODE_PRIVATE);
            settings.edit().clear().commit();
        }
    }
    

    UPDATE: after some research I found that you cannot receive something when your app is deleted.

    The package that is being removed does not receive this Intent.

    The only solution is to use second application to get it. Sorry for disappointing.

    So in your case android:allowBackup=“false” is the only way to delete settings.