2014-09-11 62 views
0

我想在android中以编程方式打开和关闭gps。想要在android中以编程方式更改gps或位置服务设置?

我尝试使用

boolean provider = Settings.Secure.putInt(this.getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED, 1); 

,但它需要一个许可"WRITE_SECURE_SETTINGS",当我用此权限它给我,只有系统的应用程序可以使用该权限写入系统设置错误。

请告诉我如何以编程方式更改设置。

我可以通过编程方式更改位置服务吗?

回答

0

请使用这个类:

public class GpsConnectionManager { 

     @SuppressWarnings("deprecation") 
     public void turnGPSOn(Context context) { 
       Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); 
       intent.putExtra("enabled", true); 
       context.sendBroadcast(intent); 

       String provider = Settings.Secure.getString(context.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")); 
         context.sendBroadcast(poke); 

       } 
     } 


     public void turnGPSOff(Context context) { 
       Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); 
       intent.putExtra("enabled", false); 
       context.sendBroadcast(intent); 
       // String provider = 
       // Settings.Secure.getString(this.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")); 
       // this.sendBroadcast(poke); 
       // } 
     } 
} 

,并使用这些权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.ACCESS_GPS" /> 
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

和奇巧它不会工作

+0

您的类参考示例这可以作为参考传递 – 2014-09-11 10:01:08

0

此前Android版本4.4。您无法以编程方式打开或关闭gps。您的遗嘱将从Kitkat版本中启动此异常java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE

您无法以编程方式访问GPS。

0

你根本无法从Android 1.5开始。但您可以将用户重定向到位置设置:

Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
相关问题