Trying to start a service on boot on Android

后端 未结 16 1507
慢半拍i
慢半拍i 2020-11-21 06:41

I\'ve been trying to start a service when a device boots up on android, but I cannot get it to work. I\'ve looked at a number of links online but none of the code works. Am

16条回答
  •  遥遥无期
    2020-11-21 07:08

    This is what I did

    1. I made the Receiver class

    public class BootReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //whatever you want to do on boot
           Intent serviceIntent = new Intent(context, YourService.class);
           context.startService(serviceIntent);
        }
    }
    

    2.in the manifest

    
        
        
            
                
                    
                
            
        ...
    

    3.and after ALL you NEED to "set" the receiver in your MainActivity, it may be inside the onCreate

    ...
     final ComponentName onBootReceiver = new ComponentName(getApplication().getPackageName(), BootReceiver.class.getName());
            if(getPackageManager().getComponentEnabledSetting(onBootReceiver) != PackageManager.COMPONENT_ENABLED_STATE_ENABLED)
            getPackageManager().setComponentEnabledSetting(onBootReceiver,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
    ...
    

    the final steap I have learned from ApiDemos

提交回复
热议问题