android6.0蓝牙权限问题以及4.0无法扫描到Ble设备问题

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/m0_37796683/article/details/82380758

在Android 6.0,原来的蓝牙功能,发现扫描蓝牙设备时,无法获取到蓝牙设备;因为在6.0后,蓝牙这块增加一个动态权限;需要在程序中动态申请。

 1.在AndroidManifest里面加上了权限

      1)   在6.0版本前,使用蓝牙功能,只需要配置下面的权限即可:

    <!-- 蓝牙相关 -->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    

     2)   在6.0及后续版本,使用蓝牙扫描,添加如下的权限,且该权限还需要在使用时动态申请:

    <!-- Android6.0及以上版本 蓝牙扫描才需要-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

2.动态获取权限 

可参考:https://blog.csdn.net/m0_37796683/article/details/83310209

       2.1)声明你要申请的权限

 private String[] permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION};

       2.2)判断是否有权限

 List<String> denyPermissions = new ArrayList<>();
       for (String value : permission) {
            if (ContextCompat.checkSelfPermission(this, value) !=PackageManager.PERMISSION_GRANTED) {//判断权限是否已授权
                  //没有权限 就添加
                  denyPermissions.add(value);
          }
      }

      2.3)请求权限

      if (denyPermissions != null && !denyPermissions.isEmpty()) {
          //申请权限授权
          ActivityCompat.requestPermissions(this, denyPermissions.toArray(new String[denyPermissions.size()]), 100);
      } else {
         //已全部授权
         //do something
    }

    2.4)权限申请结果回调

   @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //申请权限成功
                //do something
            } else {
                //权限被拒绝

            }
        }
    }

3.开启位置权限

       安卓从6.0开始,连接BLE设备不仅需要位置权限,还需要打开位置服务,需要把系统位置(Location)打开。

如果没有允许位置权限,需要到设置(应用管理)指定的App手动打开权限。

出于对用户体验性的考虑,可加入检测GPS开关是否打开,以及未打开时提示用户并打开相关页面的操作

 // gps是否可用  
       public static final 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;  
           }  
           return false;  
       }  
    //跳转到gps设置页
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
    activity.startActivityForResult(intent,requestCode);  

 

注意:部分机型打开GPS开关才可以搜索到蓝牙设备,如oppo手机。

 

另:目前安卓系统7.1.1版本连接蓝牙尚有问题,基本上连接不上

至此,本文结束!

展开阅读全文

华为荣耀6 在android6.0版本 调用蓝牙无法扫描设备

07-06

代码如下(基本跟github的一样 但是已经无法扫描到设备)rn这里没有调动ListView的adpaterrn只是简单的进行扫描rnrn将扫描结果放到Textviewrn[code=java]rn//权限rn rn rn rn[/code]rnrn[code=java]rnpublic class MainActivity extends Activity rnrn private static final int OPENBLUETOOTH = 1001;rn private BluetoothAdapter blueToothAdapter;rn private Handler mHandler = new Handler();rn private boolean mScanning;rnrn private BlueAdapter adapt;rnrn private TextView tv;rn private ListView lv;rnrn @Overridern protected void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn setContentView(R.layout.activity_main);rnrn tv = (TextView) findViewById(R.id.tv1);rn lv = (ListView) findViewById(R.id.listview);rn Button c1 = (Button) findViewById(R.id.click1);rn Button c2 = (Button) findViewById(R.id.click2);rnrn adapt = new BlueAdapter();rn lv.setAdapter(adapt);rnrn BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);rn blueToothAdapter = bluetoothManager.getAdapter();rnrn c1.setOnClickListener(new OnClickListener() rnrn @Overridern public void onClick(View v) rn // TODO Auto-generated method stubrn Check();rn rn );rnrn c2.setOnClickListener(new OnClickListener() rnrn @Overridern public void onClick(View v) rn // blueToothAdapter = BluetoothAdapter.getDefaultAdapter();rn if (blueToothAdapter == null || !blueToothAdapter.isEnabled()) rn Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);rn startActivityForResult(enableBtIntent, OPENBLUETOOTH);rn else rn scanLeDevice(true);rn // getDeviceInfo();rn rn rn );rnrn rnrn @Overridern protected void onActivityResult(int requestCode, int resultCode, Intent data) rn if (requestCode == OPENBLUETOOTH && resultCode == RESULT_OK) rn Toast.makeText(this, "开启成功", Toast.LENGTH_SHORT).show();rn scanLeDevice(true);rn // getDeviceInfo();rn rn rnrnrn private void Check() rn if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) rn Toast.makeText(this, "不支持BLE", Toast.LENGTH_SHORT).show();rn finish();rn else rn Toast.makeText(this, "支持BLE", Toast.LENGTH_SHORT).show();rn rn rnrn /**rn * 扫描rn * rn * @param enablern */rn private void scanLeDevice(final boolean enable) rn if (enable) rn // Stops scanning after a pre-defined scan period.rn mHandler.postDelayed(new Runnable() rn @Overridern public void run() rn mScanning = false;rn Toast.makeText(getApplicationContext(), "暂停扫描", Toast.LENGTH_SHORT).show();rn blueToothAdapter.stopLeScan(testBlueCallBack);rn rn , 60000);rn mScanning = true;rn blueToothAdapter.startLeScan(testBlueCallBack);rn Toast.makeText(getApplicationContext(), "开始扫描", Toast.LENGTH_SHORT).show();rn else rn Toast.makeText(getApplicationContext(), "暂停扫描", Toast.LENGTH_SHORT).show();rn mScanning = false;rn blueToothAdapter.stopLeScan(testBlueCallBack);rn rn rnrn /**rn * 获取已经配对的列表rn */rn private void getDeviceInfo() rn Set devices = blueToothAdapter.getBondedDevices();rnrn if (devices.size() == 0) rn return;rn rn Map list = new HashMap();rn int i = 0;rn for (Iterator iterator = devices.iterator(); iterator.hasNext();) rn BluetoothDevice device = (BluetoothDevice) iterator.next();rnrn device.getUuids();rn list.put("key" + i, device.getAddress() + "&" + device.getName());rn i++;rnrn Log.d("mytag", device.getAddress() + "----" + device.getName());rn rn adapt.setList(list);rn adapt.notifyDataSetChanged();rnrn rnrn /**rn * 是通过startLeScan(BlueToothAdapter.LeScanCallback)函数调用之后 , 会初始化一个device对象 ;rn * 当一个LE设备被发现的时候 , 这个对象device作为参数传递进来rn */rn private BluetoothAdapter.LeScanCallback testBlueCallBack = new LeScanCallback() rn /**rn * device : 识别的远程设备 rssi : RSSI的值作为对远程蓝牙设备的报告; 0代表没有蓝牙设备; scanRecode:rn * 远程设备提供的配对号(公告)rn */rn @Overridern public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) rnrn // Toast.makeText(getApplicationContext(), device.getName(),rn // Toast.LENGTH_SHORT).show();rnrn final BluetoothDevice dev = device;rnrn final String record = String.valueOf(scanRecord);rn runOnUiThread(new Runnable() rn @Overridern public void run() rn//只是将扫描到的终端的名字跟地址写到Textviewrn tv.setText("蓝牙地址:" + dev.getName() + "-----蓝牙配对号:" + record);rn rn );rnrn rn ;rnrn private BluetoothGattCallback bgc = new BluetoothGattCallback() rnrn @Overridern public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) rnrn rnrn ;rnrn[/code] 论坛

没有更多推荐了,返回首页