How to ensure PeriodicWorkRequests are called on device reboot on Android N and upwards

后端 未结 1 1036
心在旅途
心在旅途 2021-01-07 04:43

I recently tried to use the WorkManager\'s PeriodicWorkRequests as a surefire way of getting user location updates periodically in the background.

相关标签:
1条回答
  • 2021-01-07 05:47

    Let Say you have defined a RebootWorker class that extends Worker and do some particular job after device get rebooted. 1st Approach :

    public class RebootWorker extends Worker {
    ...............................
    }
    

    In that case defined this worker inside manifest

    <service
        android:name=".RebootWorker"
        android:process=":worker"/> 
    

    This will help to get Workmanger run your worker service after device reboot. Because due to device reboot your app is cleared from task manager.

    2nd Approach : You can also use BroadcastReceiver to listen Boot completed action

    public class MyReceiver extends BroadcastReceiver {
        WorkManager mWorkManager;
        PeriodicWorkRequest rebootRequest;
    
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(MainActivity.TAG, "intent.getAction(): "+intent.getAction());
    
            //Reboot worker
            mWorkManager = WorkManager.getInstance(context);
            rebootRequest = new PeriodicWorkRequest.Builder(RebootWorker.class,
                    MainActivity.REPEAT_INTERVAL, MainActivity.TIME).build();
    
            if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
               //do your work and enqueue it 
                mWorkManager.enqueue(rebootRequest);
    }
    }
    }
    
    0 讨论(0)
提交回复
热议问题