2

如何在关闭时打开Android中的gps以检索当前位置。我测试了两种方法

private void turnGPSOn(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

private void turnGPSOff(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

和这个方法

enaABLE GPS:
Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
DISABLE GPS:

Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);

但是当通过这些方法之一打开gps是执行代码恢复位置时,它显示

    Toast.makeText(LbsGeocodingActivity.this,
            "Provider disabled by the user. GPS turned off",
            Toast.LENGTH_LONG).show();
4

2 回答 2

11

您无法为用户启用 GPS,您可以做的是,如果 GPS 已禁用,则提示用户一条消息,要求他启用 GPS 并将他发送到设置以启用它

使用此代码:

Intent gpsOptionsIntent = new Intent(  
    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
startActivity(gpsOptionsIntent);

这是有关如何执行此操作的更详细的代码

http://java-blog.kbsbng.com/2012/08/displaying-dialog-in-android-to-prompt.html

要获取您执行此操作的位置

    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

  /*try to see if the location stored on android is close enough for you,and avoid rerequesting the location*/
    Location location =  locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location == null
            || location.getTime()
                    - Calendar.getInstance().getTimeInMillis() > MAX_LAST_LOCATION_TIME)
    {

        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, TIME_INTERVAL, LOCATION_INTERVAL, yourLocationListener);

    }
    else
    {
        //do your handling if the last known location stored on android is enouh for you
    }

在 yourLocationListener 中,您实现获取位置时要执行的操作

于 2013-04-28T12:42:14.637 回答
0

从代码中启用 GPS 是不合适的。你不能这样。

曾经有一个漏洞可以让没有特殊权限的应用程序打开 GPS。从 2.3 开始,该漏洞不再存在(在大多数 ROM 中)。

于 2013-04-28T12:43:04.290 回答