Android -Starting Service at Boot Time

后端 未结 9 1759
一个人的身影
一个人的身影 2020-11-22 16:12

I need to start a service at boot time. I searched a lot. They are talking about Broadcastreceiver. As I am new to android development, I didn\'t get a clear picture about s

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 16:20

    Most the solutions posted here are missing an important piece: doing it without a wake lock runs the risk of your Service getting killed before it is finished processing. Saw this solution in another thread, answering here as well.

    Since WakefulBroadcastReceiver is deprecated in api 26 it is recommended for API Levels below 26

    You need to obtain a wake lock . 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 permission and register your receiver in the manifest:

    
    
    
    ...
    
    
        
            
        
    
    

提交回复
热议问题