0

我有一个使用gps. 除非应用程序被强制关闭(由用户或 android 操作系统)并重新打开,否则它工作正常。然后我似乎无法关闭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是空的,我不能删除更新......有什么办法吗?

4

2 回答 2

2

我找到了解决方案。它是一个丑陋的,但它的工作原理:

private void cancelLocationUpdates() {
    if(pendingIntent == null) {
        registerLocationUpdates();
    }
    this.locationManager.removeUpdates(pendingIntent);
}

希望能帮助到你。

于 2012-05-30T10:05:27.447 回答
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);
}
于 2012-05-30T10:11:14.667 回答