Problem with back button in my app [closed]

三世轮回 提交于 2019-12-20 07:48:26

问题


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


回答1:


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" />



回答2:


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




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!