Android 应用程序开关GPS

要在应用程序中操作GPS开关需要权限: 

Java代码   收藏代码
  1. <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />  

但在配置文件中添加此权限之后会报错,无法再eclipse里面正常编译,怎么办? 
1、方法一:将项目放到Android源码中编译; 
2、方法二:网上有人说clean一下,果然有效果; 

正常编译之后安装,添加权限了也报错,无法正常运行。 
研究之后发现还需要System共享权限,就是: 
Java代码   收藏代码
  1. android:sharedUserId="android.uid.system"  


要用这个共享是有要求的: 
1、用系统签名; 
2、安装到System/app目录下; 

这样看来,普通应用程序是没办法在正常方式下操作GPS开关的,这也符合Android设计时的安全考虑。如果需要在定制APP中操作开关,有2个方法: 
1、修改系统,提供给APP操作接口; 
2、按上面流程操作; 

下面贴一下GPS操作的方法: 

Java代码   收藏代码
  1.     public static boolean getGpsState(Context context) {  
  2.         ContentResolver resolver = context.getContentResolver();  
  3.         return Settings.Secure.isLocationProviderEnabled(resolver,LocationManager.GPS_PROVIDER);  
  4.     }  
  5.       
  6.     public static void toggleGps(Context context) {  
  7.         ContentResolver resolver = context.getContentResolver();  
  8.         boolean enabled = getGpsState(context);  
  9.         Settings.Secure.setLocationProviderEnabled(resolver,LocationManager.GPS_PROVIDER, !enabled);  ----开关设置
  10.     }  
  11.   
  12.     public static boolean getGpsState(Context context) {  
  13.         LocationManager locMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);  
  14.         return locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);  
  15.     }  
  16.       
  17.     public static void toggleGps(Context context) {  
  18.         ContentResolver resolver = context.getContentResolver();  
  19.         boolean enabled = getGpsState(context);  
  20. //      Settings.Secure.putInt(resolver, LocationManager.GPS_PROVIDER, enabled?0:1);  
  21.         String value = LocationManager.PROVIDERS_CHANGED_ACTION;  
  22.         if (enabled) {  
  23.             value = "-" + LocationManager.GPS_PROVIDER;  
  24.         } else {  
  25.             value = "+" + LocationManager.GPS_PROVIDER;  
  26.         }  
  27.         Settings.Secure.putString(resolver, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, value);  
  28.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值