应用程序关闭时应用程序启动新服务
Application starts new service when app is closed
我有一个 android 应用程序,其服务必须跟踪用户的位置,即使应用程序已关闭,仅当用户在应用程序中设置标志时。所以我在用户点击按钮后开始在代码中服务,并在他使用以下代码再次点击它时停止
alarm.changeAlarmStatus();
if(alarm.getAlarmStatus()) {
SharedPreferences.Editor ed = alarmPreferences.edit();
ed.putFloat("MARKER_LATITUDE", (float) theMarker.getPosition().latitude);
ed.putFloat("MARKER_LONGITUDE", (float) theMarker.getPosition().longitude);
ed.commit();
startService(myIntent);
}
else{
stopService(myIntent);
}
它似乎工作正常。服务工作正常,做它应该做的事。但问题是,如果我通过任务管理器关闭应用程序,我在 logcat 中看到该服务再次启动(但仅当服务已经在工作时)并且它会导致 nullPointerException 因为 intent 为 null。您可以在这段代码中看到它发生的原因
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Bundle bundle = intent.getExtras();
alarm = (Alarm) bundle.getSerializable("alarm");
Log.d("service","On Start Command is called ");
serviceIntent = intent;
return START_STICKY;
}
但是我只需要按下按钮就可以启动我的服务,没有其他方式。有谁知道如何解决这个问题?
ReturnSTART_NOT_STICKY in onStartCommand instead of START_STICKY。
如果返回START_STICKY,系统会在服务被杀死后尝试重新创建服务。
如果返回START_NOT_STICKY,系统将不会在服务终止后尝试重新创建服务。
我有一个 android 应用程序,其服务必须跟踪用户的位置,即使应用程序已关闭,仅当用户在应用程序中设置标志时。所以我在用户点击按钮后开始在代码中服务,并在他使用以下代码再次点击它时停止
alarm.changeAlarmStatus();
if(alarm.getAlarmStatus()) {
SharedPreferences.Editor ed = alarmPreferences.edit();
ed.putFloat("MARKER_LATITUDE", (float) theMarker.getPosition().latitude);
ed.putFloat("MARKER_LONGITUDE", (float) theMarker.getPosition().longitude);
ed.commit();
startService(myIntent);
}
else{
stopService(myIntent);
}
它似乎工作正常。服务工作正常,做它应该做的事。但问题是,如果我通过任务管理器关闭应用程序,我在 logcat 中看到该服务再次启动(但仅当服务已经在工作时)并且它会导致 nullPointerException 因为 intent 为 null。您可以在这段代码中看到它发生的原因
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Bundle bundle = intent.getExtras();
alarm = (Alarm) bundle.getSerializable("alarm");
Log.d("service","On Start Command is called ");
serviceIntent = intent;
return START_STICKY;
}
但是我只需要按下按钮就可以启动我的服务,没有其他方式。有谁知道如何解决这个问题?
ReturnSTART_NOT_STICKY in onStartCommand instead of START_STICKY。
如果返回START_STICKY,系统会在服务被杀死后尝试重新创建服务。
如果返回START_NOT_STICKY,系统将不会在服务终止后尝试重新创建服务。