How to automatically restart a service even if user force close it?

后端 未结 10 825
感情败类
感情败类 2020-11-27 11:19

I want a service to run all the time in my application. So I want to restart it even if it is force closed by user. There is definitely a way to do it as apps like facebook

10条回答
  •  日久生厌
    2020-11-27 11:42

    First of all, it is really very bad pattern to run service forcefully against the user's willingness.

    Anyways, you can restart it by using a BroadcastReceiver which handles the broadcast sent from onDestroy() of your service.

    StickyService.java

    public class StickyService extends Service
    {
        private static final String TAG = "StickyService";
    
    
        @Override
        public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub
            return null;
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.e(TAG, "onStartCommand");
            return START_STICKY;
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            sendBroadcast(new Intent("YouWillNeverKillMe"));
        }
    
    }
    

    RestartServiceReceiver.java

    public class RestartServiceReceiver extends BroadcastReceiver
    {
    
        private static final String TAG = "RestartServiceReceiver";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "onReceive");
        context.startService(new Intent(context.getApplicationContext(), StickyService.class));
    
        }
    
    }
    

    Declare the components in manifest file:

        
        
    
        
            
                
                
            
        
    

    Start the StickyService in a Component (i.e. Application, Activity, Fragment):

    startService(new Intent(this, StickyService.class));
    

    OR

    sendBroadcast(new Intent("YouWillNeverKillMe"));
    

提交回复
热议问题