-3

I want to clear shared preference values when my mobile is switched off?

CharithJ
  • 46,289
  • 20
  • 116
  • 131
  • Please improve your question, put some efforts else its going to be closed. – Mudassir Sep 21 '11 at 10:52
  • Re-asking the same question is considered abuse of the system; please don't do it. If you can clarify your question by [editing it](http://stackoverflow.com/posts/7498418/edit), then please do so. Once your question has been improved (see this section in the [faq#howtoask] to learn how), flag for moderator attention. Select "other" and ask for a mod to reopen your question. –  Sep 21 '11 at 12:20

3 Answers3

2

How can you clear SharedPreference when the device is switched off.

You can clear it when the device starts thru BraodcastReceiver.

public class PhoneStateReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(final Context context, Intent intent) {

        if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
            //Clear your `SharedPreference` here.
        }
    }
}

In your manifest add this:

<receiver android:name=".receiver.PhoneStateReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>  

Add permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Vineet Shukla
  • 23,865
  • 10
  • 55
  • 63
0

Asfar as i know the only possibility is to use OnDestroy() but your program should be running when the device is shutdown.

Roel Veldhuizen
  • 4,613
  • 8
  • 44
  • 78
0

Same question as: Android: Android: How to make a specific SharedPreference reset itself after the system reboots?

I don't know of a different way. This implementation is quite simple. Just handle the BOOT_COMPLETED broadcast action and clear preferences by calling .clear() on the SharedPreference.Editor (answer is here).

A simple Boot receiver might look like this:

public class OnBootReceiver extends BroadcastReceiver{

                @Override
                public void onReceive(Context context, Intent intent) {
                      //clear preferences here         
                }

}

Declare it also in your AndroidManifest.xml as:

           <receiver android:name=".OnBootReceiver">
                    <intent-filter>
                            <action android:name="android.intent.action.BOOT_COMPLETED" />
                    </intent-filter>
            </receiver>

You will also need a permission for this:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Community
  • 1
  • 1
Daniel Novak
  • 2,746
  • 3
  • 28
  • 37