【发布时间】:2018-04-10 05:53:55
【问题描述】:
我想在屏幕解锁时运行我的服务,并在屏幕锁定时停止它。我查看了these answers 并实现了它们。 但是,当我锁定屏幕时,服务会按要求停止,但当我解锁屏幕时,它不会再次启动。
运行该服务的代码如下:
public class PhonePositionService extends Service {
@Override
public void onCreate() {
//ADDED CODE
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new BootCompletedIntentReceiver();
registerReceiver(mReceiver, filter);
{...}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int icon = R.drawable.ic_stat_bright;
startForeground(NOTIFICATION_ID, getCompatNotification(icon));
if (backgroundThread != null) {
backgroundThread.start();
}
return START_STICKY;
}
}
在其他文件中,我的广播接收器代码如下:
public class BootCompletedIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(Intent.ACTION_SCREEN_ON.equals(action)) {
// start the service
Intent pushIntent = new Intent(context, PhonePositionService.class);
context.startService(pushIntent);
} else if(Intent.ACTION_SCREEN_OFF.equals(action)) {
// stop the service
Intent pushIntent = new Intent(context, PhonePositionService.class);
context.stopService(pushIntent);
}
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent pushIntent = new Intent(context, PhonePositionService.class);
context.startService(pushIntent);
}
}
}
那为什么当我解锁手机时服务没有重新启动?
【问题讨论】:
-
您可以通过关注answer添加更多回调来检索用户操作