Trying to start a service on boot on Android

后端 未结 16 1520
慢半拍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 06:59

    How to start service on device boot(autorun app, etc.)

    For first: since version Android 3.1+ you don't receive BOOT_COMPLETE if user never started your app at least once or user "force closed" application. This was done to prevent malware automatically register service. This security hole was closed in newer versions of Android.

    Solution:

    Create app with activity. When user run it once app can receive BOOT_COMPLETE broadcast message.

    For second: BOOT_COMPLETE is sent before external storage is mounted. If app is installed to external storage it won't receive BOOT_COMPLETE broadcast message.

    In this case there is two solution:

    1. Install your app to internal storage
    2. Install another small app in internal storage. This app receives BOOT_COMPLETE and run second app on external storage.

    If your app already installed in internal storage then code below can help you understand how to start service on device boot.


    In Manifest.xml

    Permission:

    
    

    Register your BOOT_COMPLETED receiver:

    
        
            
        
    
    

    Register your service:

    
    

    In receiver OnBoot.java:

    public class OnBoot extends BroadcastReceiver
    {
    
        @Override
        public void onReceive(Context context, Intent intent) 
        {
            // Create Intent
            Intent serviceIntent = new Intent(context, YourCoolService.class);
            // Start service
            context.startService(serviceIntent);
    
        }
    
     }
    

    For HTC you maybe need also add in Manifest this code if device don't catch RECEIVE_BOOT_COMPLETED:

    
    

    Receiver now look like this:

    
        
            
            
        
    
    

    How to test BOOT_COMPLETED without restart emulator or real device? It's easy. Try this:

    adb -s device-or-emulator-id shell am broadcast -a android.intent.action.BOOT_COMPLETED
    

    How to get device id? Get list of connected devices with id's:

    adb devices
    

    adb in ADT by default you can find in:

    adt-installation-dir/sdk/platform-tools
    

    Enjoy! )

提交回复
热议问题