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

后端 未结 10 835
感情败类
感情败类 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条回答
  •  猫巷女王i
    2020-11-27 12:03

    Whenever a service is killed, its onDestroy method is always called. Its better to use a BroadcastReceiver to start your service when it is killed.

    Here is a sample code illustrating its implementation:-

    @Override
    public void onDestroy() {
    Intent in = new Intent();
    in.setAction("StartkilledService");
    sendBroadcast(in);
    Log.d("debug", "Service Killed");
    }
    

    Then register a receiver in AndroidManifest.xml:-

    
        
            
            
        
    
    

    Finally,create a BroadcastReceiver,and start your service in the onReceive method:-

    @Override
    public void onReceive(Context context, Intent intent) {
    Log.d("debug", "ServeiceDestroy onReceive...");
    Log.d("debug", "action:" + intent.getAction());
    Log.d("debug", "Starting Service");
    ServiceManager.startService();
    }
    

    Hope this helps.

提交回复
热议问题