Trying to start a service on boot on Android

后端 未结 16 1493
慢半拍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:20

    The other answers look good, but I thought I'd wrap everything up into one complete answer.

    You need the following in your AndroidManifest.xml file:

    1. In your element:

      
      
    2. In your element (be sure to use a fully-qualified [or relative] class name for your BroadcastReceiver):

        
            
                
            
      
      

      (you don't need the android:enabled, exported, etc., attributes: the Android defaults are correct)

      In MyBroadcastReceiver.java:

      package com.example;
      
      public class MyBroadcastReceiver extends BroadcastReceiver {
          @Override
          public void onReceive(Context context, Intent intent) {
              Intent startServiceIntent = new Intent(context, MyService.class);
              context.startService(startServiceIntent);
          }
      }
      

    From the original question:

    • it's not clear if the element was in the element
    • it's not clear if the correct fully-qualified (or relative) class name for the BroadcastReceiver was specified
    • there was a typo in the

提交回复
热议问题