最近做一款beacon相关的应用,我知道6.0之后搜索ble设备需要动态申请权限。我在activity申请权限的代码如下
@Override
protected void onResume() {
super.onResume();
Log.e("ScanActivity", "onResume方法");
//判断 当前android版本大于6.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (this.checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.e("onResume","申请权限");
requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}else {
startBeaconService();
}
}else {
startBeaconService();
}
}
//判断网络是否可用
public boolean isGpsEnable(final Context context) {
LocationManager locationManager
= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps || network) {
return true;
}
Toast.makeText(getApplicationContext(), "网络不可用",Toast.LENGTH_SHORT).show();
return false;
}
//回调权限
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (!isGpsEnable(this)){
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent,100);
}else {
ScanActivity.this.finish();
Intent startIntent = new Intent(this, ScanActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startIntent);
startBeaconService();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
break;
}
}
在使用该应用时可以正常搜索到beacon设备,但离开应用或者锁屏一段时间后,有的手机就开始搜索不到设备了,比如小米锁屏一分多钟后无法搜索到设备,点开屏幕再次聚焦到屏幕可以继续搜索。但华为、oppo之类的再次聚焦也不行,我关闭了搜索设备的activity和服务重新点开也不行,,,就是要把应用kill掉之后再打开应用才能再次搜索到设备。。。。
搜索设备的代码一直在跑,但检测不到beacon设备,因为6.0之后ACCESS_COARSE_LOCATION权限才能搜索到设备,而ACCESS_COARSE_LOCATION权限属于比较危险的权限,我猜测申请到这个权限然后是在离开应用一段时间后这个权限被系统收回去了所以无法搜索到设备。
有没有什么办法让这个权限不被系统收回?或者收回后如何再次申请又不会让用户有所感知,就是能到达持续搜索到设备的效果就好。我试过在连续几次搜索到的设备都是空的时候就开启1像素的activity在这里重新申请权限,但这个方法对小米有用,对华为没有用。