问题描述
我正在开发一个在前台服务中使用 exoplayer
的音频应用,以允许音频在关闭屏幕的情况下播放。这似乎按预期工作,但我在某处读到了有关添加唤醒锁的内容。
这是前台服务所必需的吗?唤醒锁用于保持 cpu 处于唤醒状态,但前台服务似乎在服务播放时这样做。
我决定在上班途中对其进行测试,它在关闭屏幕的情况下播放音频 +20 分钟没有问题。我认为大约 20 分钟足以让操作系统在没有唤醒锁的情况下关闭某些东西。
解决方法
是的,当您在设备重新启动或服务被终止后再次启动服务时,将使用唤醒锁定。
像这样使用它:
-
创建 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()`. } } }
-
使用
ACTION_BOOT_COMPLETED
意图过滤器在清单中注册该接收器。<receiver android:name="com.demo.service.service_manager.AutoStart"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver>
-
现在我们已经创建了接收器,它只会在设备重启时接收一次广播。所以我们必须使用唤醒锁管理器来保持在有限的时间内注册我们的服务。
-
现在,创建将用于接收广播以启动服务的广播接收器。
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">
注意:我们在 playMusic()
中使用了 onReceive()
。因此,它还会在设备重新启动时播放音频并注册该服务。如果您只想在重启时绑定服务,那么您只需在 startService()
中添加 onReceive()
方法而不是 playMusic()
。