在这里,我附上了我的代码,我创建了一个服务,在我的应用程序处于后台和被杀死状态时运行这两种情况 . 它不是在Android marshmallow设备上运行,但它可以在其他设备上运行 . 当我检查其他设备时,当应用程序处于终止状态时,将执行日志,仅执行版本6,而不执行 .
public class SensorService extends Service {
public int counter=0;
public SensorService(Context applicationContext) {
super();
Log.e("HERE", "here I am!");
}
public SensorService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
再次来破坏我会打电话给服务,它会去广播接收,然后启动服务功能就会打电话 .
@Override
public void onDestroy() {
super.onDestroy();
Log.e("EXIT", "ondestroy!");
Intent broadcastIntent = new Intent("sales.com.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
stoptimertask();
}
private Timer timer;
private TimerTask timerTask;
long oldTime=0;
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 1000, 1000); //
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
Log.e("in timer", "in timer ++++ "+ (counter++));
}
};
}
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
下面代码为广播接收器代码:app工作,当我点击后退按钮,如果应用程序被杀死状态,它不工作,其他设备服务运行 .
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
// context.startService(new Intent(context, SensorService.class));
Intent i = new Intent(context, SensorService.class);
context.startService(i);
}
}