I want to clear shared preference values when my mobile is switched off?
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" />
Asfar as i know the only possibility is to use OnDestroy()
but your program should be running when the device is shutdown.
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" />
来源:https://stackoverflow.com/questions/7498418/problem-with-back-button-in-my-app