nsL
nsL

Reputation: 3792

Android Detect clear data for refreshing widget

Is there any way to know in "real-time", via broadcast I guess, when a user has cleared data of the app?

I have a widget showing some user details, which are stored in the Preferences, but when the user clear the app data, I am not able to know it until the next refresh/update (the onUpdate() call) which is every 30min.

During that time, the widget is showing useless values. So I need to trigger somehow any broadcast to capture it from a receiver and update the widget when that happens.

Is that possible?

Upvotes: 4

Views: 3714

Answers (3)

Rajas47Ashtikar
Rajas47Ashtikar

Reputation: 583

You can also have a look at this solution, you will not exactly get a callback but you will get a fighting chance to update your widget before clearing the data

android:manageSpaceActivity=".path.to.MyActivity"

This will replace the button "Clear Data" from the settings to "Manage Space". Now you can redirect the user to a custom activity that is controlled by you.

The launch of the activity will act as callback for you. Manipulate your data in your activity and use the following code

private void clearPreferences() {
    try {
        // clearing app data
        Runtime runtime = Runtime.getRuntime();
        runtime.exec("pm clear YOUR_APP_PACKAGE_GOES HERE");

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

to clear the app data.

Upvotes: 1

Junior Buckeridge
Junior Buckeridge

Reputation: 2085

You can use a service that implements a http://developer.android.com/reference/java/util/prefs/PreferenceChangeListener.html to monitor when your preferences change.

Even if the service is killed by the system, if you use START_STICKY it will be brought to live, and you'll be able to determine if your keys are available or has been deleted. I've used this approach in a couple of apps and it works like a charm.

If you want to make even more efficient, you can add a receiver for screen on/off, so you can start your service only when the screen starts and terminate your service when the screen gets on.

Hope it helps.

Upvotes: 3

Chris Arriola
Chris Arriola

Reputation: 1784

Looks like there is no way to get an event for that. The app's process should be terminated after clearing data. https://stackoverflow.com/a/10701338/450243

Upvotes: 3

Related Questions