欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android6.0 ble 权限问题

程序员文章站 2024-03-17 09:40:34
...

在5.0上系统运行ok,把编译版本改成6.0后报下面这个错

Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission... 

阿西吧!!!这是问题是6.0系统全新的权限机制导致的[可以参考这篇文章] (http://jijiaxin89.com/2015/08/30/Android-s-Runtime-Permission/) 解决方案:
首先在AndroidManifest声明一下权限

<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>

然后在需要权限的地方请求权限


 if (Build.VERSION.SDK_INT >= 23) {
                //判断是否有权限
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    //请求权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                            MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
                    //判断是否需要 向用户解释,为什么要申请该权限
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                            Manifest.permission.READ_CONTACTS)) {
                        Toast.makeText(this, "shouldShowRequestPermissionRationale", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    mBluetoothService.startLongScan();
                }
            }else {
                mBluetoothService.startLongScan();
            }

接收权限请求回调


@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    mBluetoothService.startLongScan();
                } else {
                    // Permission Denied
                    Toast.makeText(this, "ACCESS_COARSE_LOCATION Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
        }
    }

转载于:https://my.oschina.net/oywk/blog/703502