最近需要弄一个蓝牙方面的功能,第一个想法是先把其余的蓝牙设备获取到再说,看了下网上的demo感觉真的是so easy啊,于是就马上开干了。一通操作过后,居然不显示。。。。。。好吧!继续搜寻帮助,结果就是自己太二了,6.0以后的一些权限是需要动态申请的。且6.0之后的蓝牙也有所变化,好了,看代码吧。

1.首先是需要的权限

<uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <!--6.0之后需要定位权限-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

接下来是Activity以及layout的代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.gzw.bluetoothtest.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="19dp"
        android:text="搜索蓝牙" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button"
        android:layout_marginBottom="14dp"
        android:layout_marginLeft="45dp"
        android:layout_marginStart="45dp"
        android:layout_toEndOf="@+id/button"
        android:layout_toRightOf="@+id/button"
        android:text="初始状态" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/button"
        android:layout_marginLeft="12dp"
        android:layout_marginStart="12dp"
        android:layout_marginTop="53dp"
        android:text="已配对蓝牙设备如下:" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:layout_below="@+id/textView"
        android:layout_marginTop="107dp"
        android:text="未配对蓝牙设备如下:" />

</RelativeLayout>
package com.example.gzw.bluetoothtest;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter bluetoothAdapter;
    private TextView text1,text2,text3;
    private Button button;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text1 = findViewById(R.id.textView);
        text2 = findViewById(R.id.textView2);
        text3 = findViewById(R.id.textView3);
        button = findViewById(R.id.button);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null){
            Toast.makeText(this,"设备不支持蓝牙",Toast.LENGTH_SHORT).show();
        }
        if (!bluetoothAdapter.isEnabled()){
            bluetoothAdapter.enable();
        }
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver,filter);
        IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver,filter1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermission();
                text2.setText("正在搜索...");
            }
        });
    }

    /**
     * 动态处理权限
     */
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkAccessFinePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (checkAccessFinePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        1);
                Log.d(TAG, "没有权限,请求权限");
                return;
            } else {
                /**
                 * 如果已经同意了该权限则开始搜索设备
                 */
                bluetoothAdapter.startDiscovery();

            }
            Log.d(TAG, "已有定位权限");
        }
    }

    /**
     * 申请权限回调方法 处理用户是否授权
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    /**
                     * 用户同意授权开始搜索设备
                     */
                    bluetoothAdapter.startDiscovery();

                } else {
                    //用户拒绝授权 则给用户提示没有权限功能无法使用,
                    Log.d(TAG, "没有定位权限,请先开启!");
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    /**
     * 创建广播接收器
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(BluetoothDevice.ACTION_FOUND)){
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (device.getBondState() == BluetoothDevice.BOND_BONDED){
                        //显示已经配对的设备
                        text1.append("\n" + device.getName() + "==>" + device.getAddress() + "\n");
                    }else if (device.getBondState() != BluetoothDevice.BOND_BONDED){
                        text3.append("\n" + device.getName() + "==>" + device.getAddress() + "\n");
                    }
                }else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
                    text2.setText("搜索完成");
                }
        }
    };
}

最后来个效果图

Android 蓝牙搜索 android蓝牙搜索显示_Android 蓝牙搜索

测试的时候需要先将蓝牙打开,这一块这可以自己稍微再修改下就好。