【问题标题】:Start app after boot using broadcast receiver not working in android 10使用广播接收器启动后启动应用程序在android 10中不起作用
【发布时间】:2021-07-07 10:22:57
【问题描述】:

为我的应用打开自动启动选项后,它可以在 android 9 设备上运行,但对于 android 10,没有像自动启动这样的选项

【问题讨论】:

  • 确保您在清单文件 中添加了权限
  • @MuhammadAsad 感谢您的回复,我已经在尝试无法正常工作的无障碍服务,并且我的清单中有 BIND_ACCESSIBILITY_SERVICE 权限。

标签: android broadcastreceiver android-10.0 reboot


【解决方案1】:

在设备重启后再次启动服务或服务被终止时使用唤醒锁。

像这样使用它:

  1. 创建 BroadcastReceiver 用于接收广播以启动服务。

    public class AutoStart extends BroadcastReceiver {
      LocalReceiver localReceiver = new LocalReceiver();
         public void onReceive(Context context, Intent intent) {
             if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
             Intent intent2 = new Intent(context, YourService.class);
             if (Build.VERSION.SDK_INT >= 26)
                 context.startForegroundService(intent2);
             else
                 context.startService(intent2);
            localReceiver.startMainService(context); //It will create a receiver to receive the broadcast & start your service in it's `onReceive()`.
          }
       }
    }
    
  2. 使用ACTION_BOOT_COMPLETEDintent-filter 在清单中注册该接收器。

    <receiver android:name="com.demo.service.service_manager.AutoStart">
        <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>
    
  3. 现在我们已经创建了接收器,它将在设备重新启动时仅接收一次广播。所以我们必须使用wakelock manager在有限的时间内保持注册我们的服务。

  4. 现在,创建广播接收器,用于接收广播以启动服务。

    public class LocalReceiver extends BroadcastReceiver {
        PowerManager.WakeLock wakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).wakeLock(PowerManager.PARTIAL_WAKE_LOCK, ":YourService");
        wakeLock.acquire(60 * 1L); //It will keep the device awake & register the service within 1 minute time duration.
        context.getPackageManager().setComponentEnabledSetting(new ComponentName(context, YourService.class), 1, 1);
    
        playMusic(); //Play your audio here.
    
        wakeLock.release(); //Don't forget to add this line when using the wakelock
    }
    

现在在 LocalReceiver 中创建一个方法来发送广播以启动服务。

public void startMainService(Context context) {
    PendingIntent broadcast = PendingIntent.getBroadcast(context, REQUEST_CODE, new Intent(context, LocalReceiver.class), 0);
}

就是这样!我们已经成功实现了唤醒锁。现在,只要您想播放声音。只需将广播发送到 LocalReceiver,它就会完成您的工作。

另外,不要忘记在 Manifest 中注册此接收器,并在 Manifest 中注册服务的位置添加 android:enabled="true"android:exported="true"

<receiver android:name="com.demo.service.service_manager.LocalReceiver">

注意:我们在onReceive() 中使用了playMusic()。因此,当设备重新启动并注册服务时,它也会播放音频。如果您只想在重启时绑定服务,那么您只需在 onReceive() 中添加 startService() 方法而不是 playMusic()

【讨论】:

    猜你喜欢
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多