我有一个启动服务的活动。现在,我想在监听屏幕关闭/打开的 BroadcastReceiver 中启动/停止服务。我用了:
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.d("Screen:", "In Method: ACTION_SCREEN_OFF");
context.stopService(new Intent(context, ScreenReceiver.class));
}
else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Log.d("Screen:", "In Method: ACTION_USER_PRESENT");
context.startService(new Intent(context, ScreenReceiver.class));
}
}
}
我已添加所需的权限并已在服务中注册/取消注册 BroadcastReceiver。当我运行代码时,我能够在 Logcat 中看到日志消息,但服务似乎没有停止。我应该如何解决?提前致谢。