android 强制打开gps定位_Android判断GPS是否开启和打开GPS

最近做项目需要用到蓝牙,在6.0测试机上运行时发现6.0以上需要打开定位才能使用蓝牙搜索到设备,于是就有了打开GPS的需求,这里分享一下经验

//请求权限

private void requestPermission() {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//如果 API level 是大于等于 23(Android 6.0) 时

//这里是使用的一个第三方库请求权限,可以自己修改一下

Acp.getInstance(CaptureActivity.this).request(new AcpOptions.Builder()

.setPermissions(Manifest.permission.ACCESS_COARSE_LOCATION)

.build(),

new AcpListener() {

@Override//权限请求成功回调

public void onGranted() {

boolean isOpen = GpsUtil.isOPen(MyApplication.getContext());//判断GPS是否打开

if (!isOpen) {

T.showShort(MyApplication.getContext(), "需要打开位置权限才可以搜索到蓝牙设备");

//跳转到设置页面让用户自己手动开启

Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

startActivityForResult(locationIntent, REQUEST_CODE_LOCATION_SETTINGS);

}

}

@Override//权限请求失败回调

public void onDenied(List permissions) {

T.showShort(MyApplication.getContext(), "需要打开位置权限才可以搜索到蓝牙设备");

finish();

}

});

}

}````

@Override

public void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == REQUEST_CODE_LOCATION_SETTINGS) {

if (GpsUtil.isOPen(MyApplication.getContext())) {

//定位已打开的处理

} else {

//定位依然没有打开的处理

T.showShort(MyApplication.getContext(), "需要打开位置权限才可以搜索到蓝牙设备");

finish();

}

}

}

>Gps工具类

```

public class GpsUtil {

/**

* 判断GPS是否开启,GPS或者AGPS开启一个就认为是开启的

* @param context

* @return true 表示开启

*/

public static final boolean isOPen(final Context context) {

LocationManager locationManager

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

// 通过GPS卫星定位,定位级别可以精确到街(通过24颗卫星定位,在室外和空旷的地方定位准确、速度快)

boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// 通过WLAN或移动网络(3G/2G)确定的位置(也称作AGPS,辅助GPS定位。主要用于在室内或遮盖物(建筑群或茂密的深林等)密集的地方定位)

boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (gps || network) {

return true;

}

return false;

}

/**

* 强制帮用户打开GPS

* @param context

*/

public static final void openGPS(Context context) {

Intent GPSIntent = new Intent();

GPSIntent.setClassName("com.android.settings",

"com.android.settings.widget.SettingsAppWidgetProvider");

GPSIntent.addCategory("android.intent.category.ALTERNATIVE");

GPSIntent.setData(Uri.parse("custom:3"));

try {

PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();

} catch (PendingIntent.CanceledException e) {

e.printStackTrace();

}

}

}```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值