【发布时间】:2017-07-16 16:41:21
【问题描述】:
我正在开发一个应用程序,它只有一个服务在后台运行。我希望此服务仅在用户使用他的手机时运行,即当手机解锁时,服务记录传感器数据,当屏幕锁定时服务停止,但问题是我的服务即使在屏幕已关闭。
我有以下代码,我看不出问题出在哪里!
public class ScreenReceiver extends BroadcastReceiver {
private boolean wasScreenOn = true;
@Override
public void onReceive(Context context, Intent intent) {
System.out.println(intent.getAction());
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
wasScreenOn = true;
}else{
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
wasScreenOn = true;
}else{
if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
System.out.println(intent.getAction());
wasScreenOn = false;
}
}
}
Intent intent1 = new Intent(context, MyService.class);
intent1.putExtra("statut", wasScreenOn);
context.startService(intent1);
}
}
清单中的代码
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT"/>
</intent-filter>
</receiver>
<service
android:name=".MyService"
android:enabled="true" />
在我的服务中,我打电话给接收者
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean screenOn = intent.getBooleanExtra("statut", true);
System.out.println("statut********************************************************"+screenOn);
if(!screenOn){
System.out.println("END********************************************************");
try {
unregisterReceiver(mReceiver);
}catch(IllegalArgumentException e){}
SM.unregisterListener(this, Accelerometre);
SM.unregisterListener(this, Gyroscope);
SM.unregisterListener(this, Gravity);
stopSelf();
}
return START_STICKY;
}
谢谢!
【问题讨论】: