安卓蓝牙知识点随笔

主要实现的需求:
1.动态开启蓝牙,关闭蓝牙
2.使用蓝牙传输数据

1.获取蓝牙管理者【重点】

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void initBlue() {
    BluetoothManager manager= (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    bluetoothAdapter= manager.getAdapter();

}

2.有了蓝牙管理者,之后我们在注册广播,来获取扫描到的蓝牙

理解:扫描是跨App来获取的所以,我们要在这里,定义广播来接收数据源

private void initrecevier() {
    MyRecevier myRecevier=new MyRecevier();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//查询的Action
    intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//查询完的Action
    registerReceiver(myRecevier,intentFilter);//注册,在视图销毁后我们解除注册
}

3.监听广播,接收到的数据

class MyRecevier extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction()== BluetoothDevice.ACTION_FOUND){
           /*序列化对象的分类
           1. Serializable:进程内
           2. Parcelable:进程间
           */ 
           //获得扫描到的设备,Parcelable跨app之间的序列化
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device.getName()!=null){
                list.add(device);
                adapter.notifyDataSetChanged();//通知适配器重新刷新
            }
        }else  if (intent.getAction()== BluetoothAdapter.ACTION_DISCOVERY_FINISHED){
            Toast.makeText(context, "扫描完毕", Toast.LENGTH_SHORT).show();
        }

    }
}

4.点击哪个按钮对蓝牙的对应操作

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.bt_open:
            //打开蓝牙:使用隐士意图
            Intent intent = new Intent();
            intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//设置开启蓝牙
            intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//设备能被扫描
            intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 100);//100秒内能被别人扫描到
            startActivityForResult(intent, 101);//请求码是否有回传的数据
            break;
        case R.id.bt_close:
            bluetoothAdapter.disable();//关闭蓝牙
            break;
        case R.id.bt_scan:
            bluetoothAdapter.startDiscovery();//开始扫描
            break;
    }

}

5.服务端类代码,本机发送,这个指的是接收方

public class ServerThread extends Thread {
    private BluetoothSocket socket;
    private Activity activity;
    public ServerThread(BluetoothSocket socket, Activity activity) {
        this.socket = socket;
        this.activity = activity;
    }
    @Override
    public void run() {
        super.run();

        try {
            InputStream inputStream = socket.getInputStream();
           while (true){
               byte[] bytes=new byte[1024];
               int len = inputStream.read(bytes);
               final String str=new String(bytes,0,len);
               activity.runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       Toast.makeText(activity, "接收到数据"+str, Toast.LENGTH_SHORT).show();
                   }
               });
           }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.开启服务端的线程

private void initServer() throws IOException {
    new Thread(new Runnable() {
        @Override
        public void run() {
            BluetoothServerSocket serverSocket = null;
            try {
            //获取服务BlueToothSocket
                serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
                while(true){
                    BluetoothSocket socket = serverSocket.accept();
                    //每接收到一个客户端的链接就开启一个线程服务
                    new ServerThread(socket,RiKaoActivity.this).start();
                }
            } catch (IOException e) {

            }

        }
    }).start();
}

7.配对和发送消息

//列表的点击
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onclick(int i) {

    //判断是否配对成功
    if(list.get(i).getBondState()==BluetoothDevice.BOND_BONDED){
        Toast.makeText(this, "已经配对成功", Toast.LENGTH_SHORT).show();
    }else{
        list.get(i).createBond();
    }

}
//列表的长安:发送消息
@Override
public void onlong(int i) {
    //判断是否配对成功
    if(list.get(i).getBondState()==BluetoothDevice.BOND_BONDED){
        try {
            //获得客户端Socket
            BluetoothSocket socket=list.get(i).createRfcommSocketToServiceRecord(uuid);
            socket.connect();//连接
            if(socket.isConnected()){
                socket.getOutputStream().write("你好吗".getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }else{
        Toast.makeText(this, "请先配对", Toast.LENGTH_SHORT).show();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章