Android, how to determine if a reboot occurred?

前端 未结 4 1690
慢半拍i
慢半拍i 2021-01-14 09:33

How would I programmatically determine when an android device has rebooted (whether on its own, or user initiated) ?

相关标签:
4条回答
  • 2021-01-14 10:02

    If you happen to want to know if the device has been rebooted in-app, then you can use this code.

    fun hasDeviceBeenRebooted(app: Application): Boolean {
        val REBOOT_PREFS = "reboot prefs"
        val REBOOT_KEY = "reboot key"
        val sharedPrefs = app.getSharedPreferences(REBOOT_PREFS, 
    
        val expectedTimeSinceReboot = sharedPrefs.getLong(REBOOT_KEY, 0)
        val actualTimeSinceReboot = System.currentTimeMillis() - SystemClock.elapsedRealtime() // Timestamp of rebooted time
    
        sharedPrefs.edit().putLong(REBOOT_KEY, actualTimeSinceReboot).apply()
    
        return actualTimeSinceReboot !in expectedTimeSinceReboot.minus(2000)..expectedTimeSinceReboot.plus(2000) // 2 Second error range.
    }
    
    0 讨论(0)
  • 2021-01-14 10:11

    Use a BroadcastReceiver and listen to the broadcast Intent ACTION_BOOT_COMPLETED.

    0 讨论(0)
  • 2021-01-14 10:13

    This snippet starts an Application automatically after the android-os booted up.

    in AndroidManifest.xml (application-part):

    // You must hold the RECEIVE_BOOT_COMPLETED permission in order to receive this broadcast. 
    <receiver android:enabled="true" android:name=".BootUpReceiver"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    
            <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
    </receiver>
    [..]
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    [..]
    

    In Java Class

     public class BootUpReceiver extends BroadcastReceiver{
    
                @Override
                public void onReceive(Context context, Intent intent) {
                        Intent i = new Intent(context, MyActivity.class);  
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(i);  
                }
    
    }
    
    0 讨论(0)
  • 2021-01-14 10:25

    Set up a BroadcastReceiver and register it in your manifest to respond to the android.intent.action.BOOT_COMPLETED system even. When the phone starts up the code in your broadcastreceiver's onReceive method will run. Make sure it either spawns a separate thread or takes less than 10 seconds, the OS will destroy your broadcastreceiver thread after 10 seconds.

    0 讨论(0)
提交回复
热议问题