Trying to start a service on boot on Android

后端 未结 16 1502
慢半拍i
慢半拍i 2020-11-21 06:41

I\'ve been trying to start a service when a device boots up on android, but I cannot get it to work. I\'ve looked at a number of links online but none of the code works. Am

16条回答
  •  灰色年华
    2020-11-21 07:03

    As @Damian commented, all the answers in this thread are doing it wrong. Doing it manually like this runs the risk of your Service being stopped in the middle from the device going to sleep. You need to obtain a wake lock first. Luckily, the Support library gives us a class to do this:

    public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // This is the Intent to deliver to our service.
            Intent service = new Intent(context, SimpleWakefulService.class);
    
            // Start the service, keeping the device awake while it is launching.
            Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
            startWakefulService(context, service);
        }
    }
    

    then, in your Service, make sure to release the wake lock:

        @Override
        protected void onHandleIntent(Intent intent) {
            // At this point SimpleWakefulReceiver is still holding a wake lock
            // for us.  We can do whatever we need to here and then tell it that
            // it can release the wakelock.
    
    ...
            Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
            SimpleWakefulReceiver.completeWakefulIntent(intent);
        }
    

    Don't forget to add the WAKE_LOCK permssion to your mainfest:

    
    
    

提交回复
热议问题