android的学习:蓝牙(BluetoothDevice)

如果对您帮助,麻烦您点个赞哦~谢谢。

一、代入

推荐资源
https://www.cnblogs.com/hanshuliang/p/4215467.html
https://www.cnblogs.com/hanshuliang/p/4215465.html

使用步骤

  • 设置蓝牙设备
  • 寻找能力范围内可能或匹配的设备
  • 连接设备
  • 设备之间的数据传输

二、 相关实践方法

(1)、当蓝牙状态发生变化,要修改注册信息

//(在Oncreat()里执行初始化操作)
IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND); //寻找蓝牙
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//蓝牙设备状态改变
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); //蓝牙搜索结束
         //搜索蓝牙,需要进行广播(mReceive)接收,搜索到一个设备,就要接收一个广播
        registerReceiver(mReceive, filter);
   private BroadcastReceiver mReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //寻找远程蓝牙,如果搜索到的设备跟上面过滤器中的动作一致
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //成功搜索到远程设备,实例化对象
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //判断远程蓝牙状态是否被绑定
                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    Log.i(TAG, "搜索到已经配对的设备,device name" + device.getName() + "device address " + device.getAddress());

                }else {
                    Log.i(TAG,"搜索到没有配对的设备");
                    //直接指定一个地址
                    if (device.getAddress().equals("00:20:00:76:45:39")){
                        bluetoothDevice=device;
                        Log.i(TAG,"指定配对连接的device");

                    }
                }
                //如果蓝牙装填反生了改变,那么就需要重新发送一个新的广播
            }else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
                //更新蓝牙设备的绑定状态
                BluetoothDevice device =  intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //如果绑定状态==正在绑定状态
                if (device.getBondState()==BluetoothDevice.BOND_BONDED){
                    Log.i(TAG,"正在配对 device name "+device.getName()+"device address"+device.getAddress()+"device uuid"+device.getUuids());
                    //如果绑定状态==已经完成绑定状态
                }else if (device.getBondState()==BluetoothDevice.BOND_BONDED){
                    Log.i(TAG,"完成配对 device name "+device.getName()+"device address"+device.getAddress()+"device uuid"+device.getUuids());
                    //如果绑定状态==没有绑定状态
                }else if (device.getBondState()==BluetoothDevice.BOND_NONE){
                    Log.i(TAG,"取消配对 device name");
                    //蓝牙搜索结束
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    Log.i(TAG,"设备搜索结束!");

                }
            }
        }
    };
}

(2)、添加蓝牙权限

 	<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>

(3)、获取本地蓝牙

BluetoothAdapter mBluetoothAdapter  = BluetoothAdapter.getDefaultAdapter();

(4)、打开蓝牙

private void enableBluetooth() {
        if (mBluetoothAdapter == null) {
            Log.i(TAG, "设备不支持蓝牙功能");
            return;
        }
        //如果蓝牙没有打开,我们就要将蓝牙打开
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            //请求能够打开蓝牙
            //要先在全局声明变量:private static final int REQUEST_ENABLE = 0x01;
            startActivityForResult(enableIntent, REQUEST_ENABLE);

        } else {
            Log.i(TAG, "蓝牙已经打开");
        }
    }

(5)、关闭蓝牙

    private void claseBluetooth() {
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
            Log.i(TAG, "关闭蓝牙");
        }
    }

(6)、允许蓝牙搜索

    private void disCovereEnable() {
    //如果扫描模式不等于既可以自己扫描也可以被别人扫描
        if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            //设置本机蓝牙在300毫秒内允许扫描和被扫描
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
            Log.i(TAG, "已设置蓝牙为搜索状态");
        } else {
            Log.i(TAG, "蓝牙模式是:" + mBluetoothAdapter.getScanMode());
        }
    }

(7)、搜索设备

 mBluetoothAdapter.startDiscovery();
 Log.i(TAG, "开始进行搜索");

(8)、匹配蓝牙

    private void paireDevice() {
    //如果正在搜索,先取消搜索状态
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        try {
	        //用javad反射机制,Method.invoke();
	        //获取匹配设备的类创建createRfcommSocket定义了一个对象
            Method method = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
            try {
	            //实例化对象,传入一个对象
                method.invoke(bluetoothDevice, 1);
                Log.i(TAG, "匹配成功");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                Log.i(TAG, "匹配失败");
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                Log.i(TAG, "匹配失败");
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            Log.i(TAG, "匹配失败");
        }
    }

(9)、已经匹配好的蓝牙

 private void pairedConnect() {
 		//设置列表
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
        //遍历循环列表,打印服务器名称和蓝牙地址
            for (BluetoothDevice device : pairedDevices) {
                Log.i(TAG, "device name" + device.getName() + "device address" + device.getAddress());
            }
        } else {
            Log.i(TAG, "没有找到匹配的蓝牙");
        }
    }

(10)、取消蓝牙配对

 private void unPairDevice() {
        Method method = null;
        //配对之前把扫描关闭
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        try {
            //移除设备把类文件设置为空值
            method = bluetoothDevice.getClass().getMethod("removeBond", (Class[]) null);
            method.invoke(bluetoothDevice,(Objects[])null);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        try {
            method.invoke(bluetoothDevice, (Objects[]) null);
            Log.i(TAG, "取消蓝牙配对");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

(11)、开启客户端的线程,用来监听和接收服务器的请求

private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
 private class AcceptThread extends Thread{
        public AcceptThread() {
            BluetoothServerSocket temp = null;
            try {
                temp=mBluetoothAdapter.listenUsingRfcommWithServiceRecord("BLUE_TEST",MY_UUID);

            } catch (IOException e) {
                e.printStackTrace();
            }
            serverSocket=temp;
            Log.i(TAG,"服务器端已经创建成功");
        }

        @Override
        public void run() {
            while (true){
                try {
                    BluetoothSocket socket = serverSocket.accept();//阻塞
                    if (socket!=null){
                        serverClentSocket=socket;
                        Log.d(TAG,"服务器端连接成功");

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG,"连接失败!");
                }
            }
        }
        private void cancel(){
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                    serverSocket=null;
                    Log.i(TAG,"服务器端取消连接");
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

(12)、开启服务器端的线程,用来监听和接收客户端的请求

private class AcceptThread extends Thread{
        public AcceptThread() {
            BluetoothServerSocket temp = null;
            try {
                temp=mBluetoothAdapter.listenUsingRfcommWithServiceRecord("BLUE_TEST",MY_UUID);

            } catch (IOException e) {
                e.printStackTrace();
            }
            serverSocket=temp;
            Log.i(TAG,"服务器端已经创建成功");
        }

        @Override
        public void run() {
            while (true){
                try {
                    BluetoothSocket socket = serverSocket.accept();//阻塞
                    if (socket!=null){
                        serverClentSocket=socket;
                        Log.d(TAG,"服务器端连接成功");

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG,"连接失败!");
                }
            }
        }
        private void cancel(){
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                    serverSocket=null;
                    Log.i(TAG,"服务器端取消连接");
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

(13)、打开服务

private void serverOpen(){
        acceptThread = new AcceptThread();
        acceptThread.start();
    }

(14)、关闭服务

private void serverUnconnect(){
        acceptThread.cancel();
    }

(15)、客户端蓝牙连接

private void clientConnectDevices(){
        clientThread=new ClientThread();
        clientThread.start();
    }

(16)、客户端断开蓝牙连接

 private void clientUnConnectDevices(){
        clientThread.cancel();
    }

(17)、发送数据线程

public void sendData(byte[] bytStr,BluetoothSocket socket){
        try {
            OutputStream os = socket.getOutputStream();
            os.write(bytStr);
            Log.i(TAG,"发送的数据是:"+new String(bytStr));

        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG,"发送数据错位");
        }

    }

(18)、接收数据线程

private class ReadReceiveThread extends Thread{
        private BluetoothSocket socket;

        public ReadReceiveThread(BluetoothSocket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
            Log.i(TAG,"连接成功"+socket.isConnected()+"socket"+socket);
            try {

                InputStream is = socket.getInputStream();
                bytes=is.read(buffer);
                while (true){
                    if (bytes>0){
                        byte[] buf_data=new byte[bytes];
                        for (int i = 0 ; i < bytes; i++){
                            buf_data[i]=buffer[i];
                        }
                        String str = new String(buf_data);
                        Log.i(TAG,"接收到的数据"+str);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG,"接收数据错误");
            }finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

(19)、客户端接收数据

public void clentReadRev(){
        ReadReceiveThread clientReadThread = new ReadReceiveThread(bluetoothSocket);
        clientReadThread.start();
    }

(20)、客户端发送数据

public void clientSendData(){
        sendData("客户端发送数据".getBytes(),bluetoothSocket);
    }

(21)、服务器端接收数据

public void serverReadRev(){
        ReadReceiveThread sercerReadThread = new ReadReceiveThread(serverClentSocket);
        sercerReadThread.start();
    }

(22)、服务器端发送数据

public void serverSendData(){
        sendData("服务器端发送数据".getBytes(),serverClentSocket);
    }

实例源码

布局代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="horizontal">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_weight="1">
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_op_id"
                    android:textSize="30dp"
                    android:text="打开蓝牙"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_close_id"
                    android:textSize="30dp"
                    android:text="关闭蓝牙"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_discovered_id"
                    android:textSize="30dp"
                    android:text="允许搜索"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_search_id"
                    android:textSize="30dp"
                    android:text="开始搜索"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_paired_id"
                    android:textSize="30dp"
                    android:text="已经配对"
                    />
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_Pair_id"
                    android:text="蓝牙配对"
                    android:textSize="30dp"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_unPair_id"
                    android:text="取消配对"
                    android:textSize="30dp"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_server_id"
                    android:textSize="30dp"
                    android:text="开启服务"
                    />
            </LinearLayout>
            <LinearLayout
                android:orientation="vertical"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_serverUnconnect_id"
                    android:textSize="30dp"
                    android:text="服务断开"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_connect_id"
                    android:textSize="30dp"
                    android:text="蓝牙连接"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_unConnect_id"
                    android:textSize="30dp"
                    android:text="取消连接"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_clientRev_id"
                    android:textSize="30dp"
                    android:text="客户端收"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_clientSend_id"
                    android:textSize="30dp"
                    android:text="客户端发"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_ServerRev_id"
                    android:textSize="30dp"
                    android:text="服务端收"
                    />
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:id="@+id/bt_ServerSend_id"
                    android:textSize="30dp"
                    android:text="服务端发"
                    />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>


</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG = "xieyun";
    private Button btn_Open, btn_Close, btn_Discover, btn_Search, btn_Paired, btn_Pair, btn_UnPair, btn_Server, btn_ServerUnconnect, btn_Connect, btn_UnConnect, btn_ClientRev, btn_ClientSend, btn_ServerRev, btn_ServerSend;
    //请求能够打开蓝牙
    private static final int REQUEST_ENABLE = 0x01;
    //请求权限
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 0x02;
    private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
    //本地蓝牙
    private BluetoothAdapter mBluetoothAdapter;
    //蓝牙配对客户端的socket
    private BluetoothSocket bluetoothSocket;
    //远程蓝牙
    private BluetoothDevice bluetoothDevice;
    //服务器端的socket
    private BluetoothServerSocket serverSocket;
    //服务器接收的客户端socket
    private BluetoothSocket serverClentSocket;

    private AcceptThread acceptThread; //服务端线程
    private ClientThread clientThread; //客户端线程

    private OutputStream outputStream; //输出流
    private InputStream inputStream; //输入流
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();//初始化事件

        checkBLEFeatrue();//检测蓝牙
//        checkPermissions();//检测权限
    }

    private void initView() {
        //先要获取默认的蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


        //当蓝牙状态发生变化时,要修改注册信息
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND); //寻找蓝牙
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); //蓝牙搜索结束
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//蓝牙设备状态改变
        registerReceiver(mReceive, filter);

        //绑定控件
        btn_Open = findViewById(R.id.bt_op_id);
        btn_Close = findViewById(R.id.bt_close_id);
        btn_Discover = findViewById(R.id.bt_discovered_id);
        btn_Search = findViewById(R.id.bt_search_id);
        btn_Pair = findViewById(R.id.bt_Pair_id);
        btn_Paired = findViewById(R.id.bt_paired_id);
        btn_UnPair = findViewById(R.id.bt_unPair_id);
        btn_Server = findViewById(R.id.bt_server_id);
        btn_ServerUnconnect = findViewById(R.id.bt_serverUnconnect_id);
        btn_Connect = findViewById(R.id.bt_connect_id);
        btn_UnConnect = findViewById(R.id.bt_unConnect_id);
        btn_ClientRev = findViewById(R.id.bt_clientRev_id);
        btn_ClientSend = findViewById(R.id.bt_clientSend_id);
        btn_ServerRev = findViewById(R.id.bt_ServerRev_id);
        btn_ServerSend = findViewById(R.id.bt_ServerSend_id);

        btn_Open.setOnClickListener(this);
        btn_Close.setOnClickListener(this);
        btn_Discover.setOnClickListener(this);
        btn_Search.setOnClickListener(this);
        btn_Pair.setOnClickListener(this);
        btn_Paired.setOnClickListener(this);
        btn_UnPair.setOnClickListener(this);
        btn_Server.setOnClickListener(this);
        btn_ServerUnconnect.setOnClickListener(this);
        btn_Connect.setOnClickListener(this);
        btn_UnConnect.setOnClickListener(this);
        btn_ClientRev.setOnClickListener(this);
        btn_ClientSend.setOnClickListener(this);
        btn_ServerRev.setOnClickListener(this);
        btn_ServerSend.setOnClickListener(this);
    }
    private void checkBLEFeatrue() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Log.i(TAG, "设备不支持BLE");
            return;
        } else {
            Log.i(TAG, "设备支持蓝牙");
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_op_id:
                enableBluetooth();//打开蓝牙
                break;
            case R.id.bt_close_id:
                claseBluetooh();//关闭蓝牙
                break;
            case R.id.bt_discovered_id:
                disCovereEnable();//允许被搜索
                break;
            case R.id.bt_paired_id:
                pairedConnect();//已经配对的设备

                break;
            case R.id.bt_Pair_id: //蓝牙配对
                paireDevice();
                break;
            case R.id.bt_search_id:
                mBluetoothAdapter.startDiscovery();//搜索设备
                Log.i(TAG,"开始进行搜索");
                break;
            case R.id.bt_unPair_id:
                unPairDevice();  //取消蓝牙配对
                break;
            case R.id.bt_server_id:
                serverOpen(); //打开服务器
                break;
            case R.id.bt_serverUnconnect_id:
                serverUnconnect(); //服务器断开连接
                break;
            case R.id.bt_connect_id:
                clientConnectDevices();//客户端蓝牙连接
                break;
            case R.id.bt_unConnect_id:
                clientUnConnectDevices(); //客户端取消蓝牙连接
                break;
            case R.id.bt_clientRev_id:
                clentReadRev();//客户端接收数据
                break;
            case R.id.bt_clientSend_id:
                clientSendData(); //客户端发送数据
                break;
            case R.id.bt_ServerRev_id:
                serverReadRev();  //服务器接收数据
                break;
            case R.id.bt_ServerSend_id:
                serverSendData(); //服务器发生数据
                break;
            default:
                break;
        }

    }

    //打开蓝牙
    private void enableBluetooth() {
        if (mBluetoothAdapter == null) {
            Log.i(TAG, "设备不支持蓝牙功能");
            return;
        }
        //如果蓝牙没有打开,我们就要将蓝牙打开
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE);

        } else {
            Log.i(TAG, "蓝牙已经打开");
        }
    }
    //关闭蓝牙
    private void claseBluetooh() {
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
            Log.i(TAG, "关闭蓝牙");
        }
    }
    private void disCovereEnable() {

        if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
            Log.i(TAG, "已设置蓝牙为搜索状态");
        } else {
            Log.i(TAG, "蓝牙模式是:" + mBluetoothAdapter.getScanMode());
        }
    }

    //匹配蓝牙
    private void paireDevice() {
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        try {
            Method method = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
            try {
                method.invoke(bluetoothDevice, 1);
                Log.i(TAG, "匹配成功");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                Log.i(TAG, "匹配失败");
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                Log.i(TAG, "匹配失败");
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            Log.i(TAG, "匹配失败");
        }
    }

    //已经匹配好的蓝牙
    private void pairedConnect() {
        //设置列表
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            //遍历列表,打印蓝牙名字跟蓝牙地址
            for (BluetoothDevice device : pairedDevices) {
                Log.i(TAG, "device name" + device.getName() + "device address" + device.getAddress());
            }
        } else {
            Log.i(TAG, "没有找到匹配的蓝牙");
        }
    }

    //取消蓝牙匹配
    private void unPairDevice() {
        Method method = null;
        //配对之前把扫描关闭
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        try {
            //移除设备把类文件设置为空值
            method = bluetoothDevice.getClass().getMethod("removeBond", (Class[]) null);
            method.invoke(bluetoothDevice,(Objects[])null);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        try {
            method.invoke(bluetoothDevice, (Objects[]) null);
            Log.i(TAG, "取消蓝牙配对");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    //打开服务
    private void serverOpen(){
        acceptThread = new AcceptThread();
        acceptThread.start();
    }
    //服务器断开连接
    private void serverUnconnect(){
        acceptThread.cancel();
    }
    //客户端蓝牙连接
    private void clientConnectDevices(){
        clientThread=new ClientThread();
        clientThread.start();
    }
    //客户端断开蓝牙连接
    private void clientUnConnectDevices(){
        clientThread.cancel();
    }

    //开启服务器端的线程,用来监听和接收客户端的请求
    private class AcceptThread extends Thread{
        public AcceptThread() {
            BluetoothServerSocket temp = null;
            try {
                temp=mBluetoothAdapter.listenUsingRfcommWithServiceRecord("BLUE_TEST",MY_UUID);

            } catch (IOException e) {
                e.printStackTrace();
            }
            serverSocket=temp;
            Log.i(TAG,"服务器端已经创建成功");
        }

        @Override
        public void run() {
            while (true){
                try {
                    BluetoothSocket socket = serverSocket.accept();//阻塞
                    if (socket!=null){
                        serverClentSocket=socket;
                        Log.d(TAG,"服务器端连接成功");

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG,"连接失败!");
                }
            }
        }
        private void cancel(){
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                    serverSocket=null;
                    Log.i(TAG,"服务器端取消连接");
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }
    //开启客户端的线程,用来监听和接收服务器的请求
    private class ClientThread extends Thread{
        public ClientThread(){
            BluetoothSocket temp = null;
            if (mBluetoothAdapter.isDiscovering()){
                mBluetoothAdapter.cancelDiscovery();
            }
            try {
                bluetoothDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                e.printStackTrace();
            }
            bluetoothSocket=temp;

        }

        @Override
        public void run() {
            try {
                bluetoothSocket.connect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        private void cancel(){
            if (bluetoothSocket!=null&&bluetoothSocket.isConnected()){
                try {
                    bluetoothSocket.close();
                    bluetoothSocket=null;
                    Log.i(TAG,"取消设备连接");
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }
    //客户端接收数据
    public void clentReadRev(){
        ReadReceiveThread clientReadThread = new ReadReceiveThread(bluetoothSocket);
        clientReadThread.start();
    }
    //客户端发送数据
    public void clientSendData(){
        sendData("客户端发送数据".getBytes(),bluetoothSocket);
    }
    //服务器端接受数据
    public void serverReadRev(){
        ReadReceiveThread sercerReadThread = new ReadReceiveThread(serverClentSocket);
        sercerReadThread.start();
    }
    //服务端发送数据
    public void serverSendData(){
        sendData("服务器端发送数据".getBytes(),serverClentSocket);
    }

    //发送数据
    public void sendData(byte[] bytStr,BluetoothSocket socket){
        try {
            OutputStream os = socket.getOutputStream();
            os.write(bytStr);
            Log.i(TAG,"发送的数据是:"+new String(bytStr));

        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG,"发送数据错位");
        }

    }

    //接收数据线程
    private class ReadReceiveThread extends Thread{
        private BluetoothSocket socket;

        public ReadReceiveThread(BluetoothSocket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
            Log.i(TAG,"连接成功"+socket.isConnected()+"socket"+socket);
            try {

                InputStream is = socket.getInputStream();
                bytes=is.read(buffer);
                while (true){
                    if (bytes>0){
                        byte[] buf_data=new byte[bytes];
                        for (int i = 0 ; i < bytes; i++){
                            buf_data[i]=buffer[i];
                        }
                        String str = new String(buf_data);
                        Log.i(TAG,"接收到的数据"+str);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG,"接收数据错误");
            }finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //搜索蓝牙,需要进行广播接收,搜索到一个设备,就要接收一个广播
    private BroadcastReceiver mReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //寻找远程蓝牙,如果搜索到的设备跟上面过滤器中的动作一致
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //成功搜索到远程设备,实例化对象
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //判断远程蓝牙状态是否被绑定
                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    Log.i(TAG, "搜索到已经配对的设备,device name" + device.getName() + "device address " + device.getAddress());

                }else {
                    Log.i(TAG,"搜索到没有配对的设备");
                    //直接指定一个地址
                    if (device.getAddress().equals("00:20:00:76:45:39")){
                        bluetoothDevice=device;
                        Log.i(TAG,"指定配对连接的device");

                    }
                }
                //如果蓝牙装填反生了改变,那么就需要重新发送一个新的广播
            }else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
                //更新蓝牙设备的绑定状态
                BluetoothDevice device =  intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //如果绑定状态==正在绑定状态
                if (device.getBondState()==BluetoothDevice.BOND_BONDED){
                    Log.i(TAG,"正在配对 device name "+device.getName()+"device address"+device.getAddress()+"device uuid"+device.getUuids());
                    //如果绑定状态==已经完成绑定状态
                }else if (device.getBondState()==BluetoothDevice.BOND_BONDED){
                    Log.i(TAG,"完成配对 device name "+device.getName()+"device address"+device.getAddress()+"device uuid"+device.getUuids());
                    //如果绑定状态==没有绑定状态
                }else if (device.getBondState()==BluetoothDevice.BOND_NONE){
                    Log.i(TAG,"取消配对 device name");
                    //蓝牙搜索结束
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    Log.i(TAG,"设备搜索结束!");

                }
            }
        }
    };
}
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中,因为 BluetoothDevice 类并没有实现 Serializable 接口,所以不能直接将 BluetoothDevice 对象保存到 SharedPreferences 中。不过,我们可以将 BluetoothDevice 对象中的 MAC 地址和名称保存到 SharedPreferences 中。 以下是一个示例代码,用来将 BluetoothDevice 对象的 MAC 地址和名称保存到 SharedPreferences 中: ```java // 将 BluetoothDevice 对象保存到 SharedPreferences 中 private void saveBluetoothDevice(BluetoothDevice device) { // 获取 SharedPreferences 对象 SharedPreferences sharedPreferences = getSharedPreferences("BluetoothDeviceInfo", Context.MODE_PRIVATE); // 获取 MAC 地址和名称 String address = device.getAddress(); String name = device.getName(); // 获取 SharedPreferences 编辑器对象 SharedPreferences.Editor editor = sharedPreferences.edit(); // 保存 MAC 地址和名称 editor.putString("address", address); editor.putString("name", name); // 提交更改 editor.apply(); } ``` 在代码中,我们首先通过 getSharedPreferences() 方法获取到一个 SharedPreferences 对象,并通过 edit() 方法获取到它的编辑器对象。然后,我们通过 BluetoothDevice 对象的 getAddress() 和 getName() 方法获取到 MAC 地址和名称,并将它们保存到 SharedPreferences 中。最后,我们通过 apply() 方法提交更改。 在需要读取保存的 BluetoothDevice 信息时,可以通过以下代码读取: ```java // 从 SharedPreferences 中读取 BluetoothDevice 信息 private BluetoothDevice readBluetoothDevice() { // 获取 SharedPreferences 对象 SharedPreferences sharedPreferences = getSharedPreferences("BluetoothDeviceInfo", Context.MODE_PRIVATE); // 读取保存的 MAC 地址和名称 String address = sharedPreferences.getString("address", null); String name = sharedPreferences.getString("name", null); // 如果 MAC 地址或名称为空,则返回 null if (address == null || name == null) { return null; } // 使用 MAC 地址创建 BluetoothDevice 对象 BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); return bluetoothAdapter.getRemoteDevice(address); } ``` 在代码中,我们首先通过 getSharedPreferences() 方法获取到之前保存的 SharedPreferences 对象,并通过 getString() 方法读取保存的 MAC 地址和名称。然后,我们使用 BluetoothAdapter 的 getRemoteDevice() 方法根据 MAC 地址创建 BluetoothDevice 对象。需要注意的是,如果之前没有保存过数据,则 getString() 方法会返回 null。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值