Starting background service when Android turns on

后端 未结 2 655
难免孤独
难免孤独 2020-12-30 11:18

I need to have ALWAYS a background service that will synchronize my Android application and a server. I know how to launch it through my application, but when the Android tu

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 11:42

    use for starting your service when the device turns on.

    In AndroidManifest.xml:

        
                   
                       
                   
             
    

    Add permission in your AndroidManifest.xml as:

    
    
    

    In code part BootBroadcastReceiver:

    public class BootBroadcastReceiver extends BroadcastReceiver {     
        static final String ACTION = "android.intent.action.BOOT_COMPLETED";   
        @Override   
        public void onReceive(Context context, Intent intent) {   
            // BOOT_COMPLETED” start Service    
            if (intent.getAction().equals(ACTION)) {   
                //Service    
                Intent serviceIntent = new Intent(context, StartOnBootService.class);       
                context.startService(serviceIntent);   
            }   
        }    
    }   
    

    EDIT: if you are talking about device screen on/off then you need to register and for starting your service when user is present or screen is on.

提交回复
热议问题