How do I start my app on startup?

前端 未结 8 1907
失恋的感觉
失恋的感觉 2020-11-22 01:06

I tried using the sample code in this link but it seems outdated and it did not work. So what changes do I have to make and to what files to have my app start automatically

8条回答
  •  孤城傲影
    2020-11-22 01:51

    First, you need the permission in your AndroidManifest.xml:

    
    

    Also, in yourAndroidManifest.xml, define your service and listen for the BOOT_COMPLETED action:

    
        
            
        
    
    
    
        
            
        
    
    

    Then you need to define the receiver that will get the BOOT_COMPLETED action and start your service.

    public class StartMyServiceAtBootReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
                Intent serviceIntent = new Intent(context, MyService.class);
                context.startService(serviceIntent);
            }
        }
    }
    

    And now your service should be running when the phone starts up.

提交回复
热议问题