问题
I'm trying to detect if an Android device has rebooted since the last time a preference value is set. Ideally, I'd like to do it without the android.permission.RECEIVE_BOOT_COMPLETED
permission.
One way I'm thinking about doing this is storing another preference value that contains some sort of session ID. When I update the preference value in question, I'd update the session value as well. When I check the value in the preference for the session value, if it equals the current session value then there has not been a reboot. If the current session value is different than what's saved, then there's been a reboot. Unfortunately, I've been digging through the docs for quite some time now trying to find a session value, and I can't find anything.
I'd like help with one of two things. If you can provide where I could find a value of something similar to a session ID or a boot ID, then I'll use my algorithm. Alternatively, I'd be open to another algorithm to solve the problem. Thank you so much!
回答1:
Yes you can do that using Application class and the Non-Static broadcast Receiver ACTION_SHUTDOWN. The Application class got started in two cases
- Android Device Boot
- Your Application Starts after it was "Force-Close" it.
When ACTION_SHUTDOWN received use your application Shared-preferences or database to save a boolean shutdown = true when application class starts check this boolean. If it is true then the device is booting , else the user forced your app to stop.
To get more info you can read the following post that I wrote and try the code example in which, I added
- Application Class
- Boot Broadcast Receiver (To Show the difference and that both starts)
- Shutdown broadcast receiver that is register in the Application calss
来源:https://stackoverflow.com/questions/27562179/determine-if-phone-has-been-rebooted