中隨機停止工作我正在開發android應用程序,我需要啓動位置服務。所有我需要確保服務應該工作,是否會在任何活動,如果我按下後退按鈕/主頁按鈕,或者即使我按下主頁按鈕掃描應用程序。我的位置服務會在某個時間後停止工作,例如我將時間設置爲1分鐘,但在2-3分鐘後它會進行調用。後臺服務在android onCreate()和onResume()
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(1000 * 60 * 1) // 30 minutes seconds
.setFastestInterval(1000 * 60 * 1) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
我的代碼在下面給出了調用位置服務類和主要類的地方,我正在運行調用該服務。請在上述場景中幫助我,我想在後臺運行該服務:按下後退按鈕,主頁按鈕,按下主頁按鈕以刪除應用程序。
public class GPSLoggerService extends Service {
private LocationManager lm;
private static long minTimeMillis = 2000;
private static long minDistanceMeters = 0;
private static float minAccuracyMeters = 35;
private static boolean showingDebugToast = false;
MyLocationTracker locationTracker;
private static final String tag = "MUrgency GPS Logger";
/** Called when the activity is first created. */
private void startLoggerService() {
if (locationTracker != null)
return;
locationTracker = new MyLocationTracker(this) {
@Override
public void onLocationFound(Location location) {
Constants.sMY_LOCATION = location;
float a = (float) location.getLatitude();
float b = (float) location.getLongitude();
SharedPreferences prefs = getSharedPreferences("locationPref", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("latitudeFloat", a);
editor.putFloat("longitudeFloat", b);
editor.commit();
if (minutes > 5){
shouldSync = true;
}
}
};
}
private void shutdownLoggerService() {
}
}
@Override
public void onCreate() {
super.onCreate();
startLoggerService();
}
@Override
public void onDestroy() {
super.onDestroy();
shutdownLoggerService();
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* Class for clients to access. Because we know this service always runs in
* the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
GPSLoggerService getService() {
return GPSLoggerService.this;
}
}
}
Main類我在哪裏在的onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainlanding);
startService(new Intent(this, GPSLoggerService.class));
}
@Override
protected void onDestroy() {
sActivityMain = null;
super.onDestroy();
stopLocationService();
}
當用戶按下後退按鈕時,你的Activity的'onDestroy()' - 方法將被調用。查看Android生命週期回調https://developer.android.com/training/basics/activity-lifecycle/starting.html#lifecycle-states。你也可以看看http://stackoverflow.com/questions/30771596/gpstracker-class-not-working/30775807#30775807 – momo