part-1 persistent foreGround android service that starts by UI, works at sleep mode too, also starts at phone restart

前端 未结 3 709
心在旅途
心在旅途 2020-12-15 10:05

Status:--- I equally accept Karakuri\'s and Sharad Mhaske\'s answer, but since Sharad Mhaske answer after the

3条回答
  •  遥遥无期
    2020-12-15 10:50

    If you start a service with startService(), it will keep running even when the Activity closes. It will only be stopped when you call stopService(), or if it ever calls stopSelf() (or if the system kills your process to reclaim memory).

    To start the service on boot, make a BroadcastReceiver that just starts the service:

    public class MyReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            Intent service = new Intent(context, MyService.class);
            context.startService(service);
        }
    }
    

    Then add these to your manifest:

    
    
    
        
            
                
            
        
    
    

    Notice that the receiver is not enabled at first. When the user starts your service, use PackageManager to enable the receiver. When the user stops your service, use PackageManager to disable the receiver. In your Activity:

    PackageManager pm = getPackageManager();
    ComponentName receiver = new ComponentName(this, MyReceiver.class);
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,  PackageManager.DONT_KILL_APP);
    

    Use same method with PackageManager.COMPONENT_ENABLED_STATE_DISABLED to disable it.

提交回复
热议问题