Background execution not allowed receiving intent BOOT_COMPLETED

后端 未结 2 1595
小蘑菇
小蘑菇 2020-12-17 14:42

I\'ve read about Android Oreo background execution limitations, and it clearly states that BOOT_COMPLETED broadcast is unaffected, but I can\'t get it to work o

2条回答
  •  独厮守ぢ
    2020-12-17 15:12

    The solution was a combination of two attempts I had already made.

    First, I had to start a foreground service (even a dummy service would be good) with sticky notification:

    public class StartDetectionAtBoot extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Intent intent1 = new Intent(context.getApplicationContext(), DummyService.class);
                context.startForegroundService(intent1);
            }
    
            Intent intent0 = new Intent( context, ActivityRecognitionService.class );
            PendingIntent pendingIntent = PendingIntent.getService(context, 111, intent0, PendingIntent.FLAG_UPDATE_CURRENT);
            ActivityRecognitionClient activityRecognitionClient = ActivityRecognition.getClient(context);
            activityRecognitionClient.requestActivityUpdates(5000, pendingIntent);
        }
    }
    

    Of course inside the service you start there must be an onCreate method which creates a notification and calls startForeground.

    Secondly, I had did a cache invalidation in Android Studio and I also wiped emulator instance. This part of the solution was necessary for me since the first part still didn't work.

提交回复
热议问题