我有一项启动服务的活动。现在,我想在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中看到Log消息,但服务似乎没有停止。我该如何解决?提前谢谢。
答案 0 :(得分:4)
您正在尝试重新启动BroadcastReceiver。
请改为使用服务类。
context.startService(new Intent(context, ScreenReceiver.class));
应该是
context.startService(new Intent(context, YourService.class));
并在您的清单文件中:
<service android:name=".YourService"></service>