【发布时间】:2015-06-11 08:40:55
【问题描述】:
我正在开发需要启动位置服务的 android 应用程序。我只需要确保服务应该工作,无论它是否会在任何活动中,如果我按下后退按钮/主页按钮,或者即使我通过按下主页按钮扫描应用程序。我的定位服务在某个时间后停止工作,比如我设置了 1 分钟的时间,但它会在 2-3 分钟后调用它。
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;
}
}
}
我在 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 生命周期回调developer.android.com/training/basics/activity-lifecycle/…。你也可以看看stackoverflow.com/questions/30771596/…
标签: java android service background-service