我有一个使用gps
的应用。它工作正常,除非应用程序被强制关闭(由用户或android os)并重新打开。然后,我似乎无法关闭gps
更新。
这是我的代码:
private void registerLocationUpdates() {
Intent intent = new Intent(ParkOGuardActivity.class.getName()
+ ".LOCATION_READY");
pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 0, intent, 0);
// minimum every 1 minutes, 5 kilometers
this.locationManager.requestLocationUpdates(this.provider, 5000,
300000, pendingIntent);
}
private void cancelLocationUpdates() {
if(pendingIntent != null){
Log.d(TAG,pendingIntent!=null ? "pending is not null" : "pending is null");
this.locationManager.removeUpdates(pendingIntent);
}
}
如果我正在调用cancelLocationUpdates()
方法,但是在重新打开应用程序之后(强制关闭之后),pendingIntent
为空,我无法删除更新...
有没有办法做到这一点?
答案 0 :(得分:2)
我找到了解决方案。它是一个丑陋的但它有效:
private void cancelLocationUpdates() {
if(pendingIntent == null) {
registerLocationUpdates();
}
this.locationManager.removeUpdates(pendingIntent);
}
希望它有所帮助。
答案 1 :(得分:0)
在开始活动之前检查GPS是开启还是关闭,如下所示:
LocationManager lm;
boolean gpsOn = false;
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER )) {
launchGPSOptions();
if (!gpsOn) launchGPS();
}
在代码中使用LaunchGPS和LaunchGPS选项,如下所示:
private void launchGPSOptions() {
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) {
final Intent poke = new Intent();
gpsOn = true;
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
private void launchGPS() {
// final ComponentName toLaunch = new
// ComponentName("com.android.settings","com.android.settings.SecuritySettings");
final Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// intent.setComponent(toLaunch);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, 0);
}