Android service not restarting in lollipop

前端 未结 7 1334
借酒劲吻你
借酒劲吻你 2020-12-11 01:13

In my application, I use location based service in background. So I need to restart my service when it gets destroyed.

But I got this message in logcat

7条回答
  •  -上瘾入骨i
    2020-12-11 02:14

    You can restart it by using a BroadcasteReceiver which handles the broadcast sent from onDestroy() of your service.

    How to do this:

    StickyService.java

    public class StickyService extends Service
    {
    
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY;
        }
    
    
        @Override
        public void onTaskRemoved(Intent rootIntent) {
             super.onTaskRemoved(rootIntent);
             sendBroadcast(new Intent("IWillStartAuto"));
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            sendBroadcast(new Intent("IWillStartAuto"));
        }
    
    }
    

    RestartServiceReceiver.java

    public class RestartServiceReceiver extends BroadcastReceiver
    {
    
        @Override
        public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context.getApplicationContext(), StickyService.class));
    
        }
    
    }
    

    Declare the components in manifest file:

        
        
    
        
            
                
                
            
        
    

    Hope this will help you.

提交回复
热议问题