我有一个启动服务的活动。现在,我想在监听屏幕关闭/打开的广播接收器中启动/停止服务。我使用了以下代码:
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中看到日志信息,但服务似乎无法停止。我该如何解决?提前感谢您。
startService
,而不是ScreenReceiver
(BroadcastReceiver名称),并确保已将服务添加到AndroidManifest文件中。 - ρяσѕρєя K