我有一个通过蓝牙与我的应用连接的传感器。我创建了一个前台服务,即使用户关闭应用程序后,该应用程序仍可以保持应用程序处于活动状态并与传感器连接。要停止前景服务,用户需要重新启动应用程序并停止前景服务。
以上所有操作均已完美完成,并且对NOW正常运行。
我的问题是-
有一个播放和暂停按钮可以启动和停止服务。一旦启动,图标会更改,但是在完全关闭应用程序(不停止前台服务)之后重新启动应用程序,应用程序不会更改。当然,它不会改变,因为我不知道如何检查服务是否仍在前台运行。
是的,我已经阅读了前面所有的答案,并且大多数答案已被弃用或不再起作用。
尝试使用该实用工具检查服务是否正在运行:
public static boolean isServiceRunning(Context context, Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
用动作名称android.intent.action.BOOT_COMPLETED在清单中定义一个接收者。
<!-- Start the Service if applicable on boot -->
<receiver android:name=".ServiceStarter">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
请确保还包括完整的启动许可。
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
定义服务以捕获接收动作
public class ServiceStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//check if start button has clicked
if(isServiceRun){
//start foreground service
Intent i = new Intent("ForegroundService");
i.setClass(context, MyForeGroundService.class);
context.startService(i);
}
}
}