安卓藍牙知識點隨筆

主要實現的需求:
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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章