有人可以請解釋我爲什麼我的服務不停止?如何在設備被鎖定時立即停止服務並永久停止。 我的活動:如何立即停止服務立即
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, MyService.class));
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
BroadcastReceiver mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
}
我的收款人:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(Intent.ACTION_SCREEN_ON.equals(action)) {
Log.i("isScreen ","on");
} else
if(Intent.ACTION_SCREEN_OFF.equals(action)) {
Log.i("isScreen ","off");
context.stopService(new Intent(context, MyService.class));
}
}
}
我的服務:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i("Service ","starts");
}
}
當您解鎖設備時,檢查接收器中的條件 –
除非您管理該服務,否則該服務將繼續在後臺運行。 http://stackoverflow.com/a/34530513/3956566 –
@ ajay-pandya你的意思是像「如果設備被解鎖,然後開始/停止服務」? –