1. 程式人生 > >從查詢藍芽裝置到能夠相互通訊要經過幾個基本步驟(本機做為伺服器)

從查詢藍芽裝置到能夠相互通訊要經過幾個基本步驟(本機做為伺服器)

從查詢藍芽裝置到能夠相互通訊要經過幾個基本步驟(本機做為伺服器):

1.設定許可權
在manifest中配置

<uses-permission android:name=“android.permission.BLUETOOTH”/+>
<uses-permission android:name=“android.permission.BLUETOOTH_ADMIN”/+>

2.啟動藍芽
首先要檢視本機是否支援藍芽,獲取BluetoothAdapter藍芽介面卡物件

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null){
//表明此手機不支援藍芽
return;
}
if(!mBluetoothAdapter.isEnabled()){ //藍芽未開啟,則開啟藍芽
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
//…
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_ENABLE_BT){
if(requestCode == RESULT_OK){
//藍芽已經開啟
}
}
}

3。發現藍芽裝置
這裡可以細分為幾個方面
(1)使本機藍芽處於可見(即處於易被搜尋到狀態),便於其他裝置發現本機藍芽

//使本機藍芽在300秒內可被搜尋

private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}

(2)查詢已經配對的藍芽裝置,即以前已經配對過的裝置

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    if (pairedDevices.size() > 0) {
        findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
        for (BluetoothDevice device : pairedDevices) {
            //device.getName() +" "+ device.getAddress());
        }
    } else {
        mPairedDevicesArrayAdapter.add("沒有找到已匹對的裝置");
    }

(3)通過mBluetoothAdapter.startDiscovery();搜尋裝置,要獲得此搜尋的結果需要註冊
一個BroadcastReceiver來獲取。先註冊再獲取資訊,然後處理

//註冊,當一個裝置被發現時呼叫onReceive
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);

//當搜尋結束後呼叫onReceive
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
//…
private BroadcastReceiver mReceiver = 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) {
mNewDevicesArrayAdapter.add(device.getName() + “\n” + device.getAddress()); //儲存裝置地址與名字
}
}else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { //搜尋結束
if (mNewDevicesArrayAdapter.getCount() == 0) {
mNewDevicesArrayAdapter.add(“沒有搜尋到裝置”);
}
}
}
};

4.建立連線
查詢到裝置 後,則需要建立本機與其他裝置之間的連線。
一般用本機搜尋其他藍芽裝置時,本機可以作為一個服務端,接收其他裝置的連線。
啟動一個伺服器端的執行緒,死迴圈等待客戶端的連線,這與ServerSocket極為相似。
這個執行緒在準備連線之前啟動

複製程式碼
//UUID可以看做一個埠號
private static final UUID MY_UUID =
UUID.fromString(“fa87c0d0-afac-11de-8a39-0800200c9a66”);
//像一個伺服器一樣時刻監聽是否有連線建立
private class AcceptThread extends Thread{
private BluetoothServerSocket serverSocket;

    public AcceptThread(boolean secure){
        BluetoothServerSocket temp = null;
        try {
            temp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
                        NAME_INSECURE, MY_UUID);
        } catch (IOException e) {
              Log.e("app", "listen() failed", e);
        }
        serverSocket = temp;
    }
    
    public void run(){
        BluetoothSocket socket=null;
        while(true){
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                 Log.e("app", "accept() failed", e);
                 break;
            }
        }
        if(socket!=null){
            //此時可以新建一個數據交換執行緒,把此socket傳進去
        }
    }
    
    //取消監聽
    public void cancel(){    
        try {
            serverSocket.close();
        } catch (IOException e) {
            Log.e("app", "Socket Type" + socketType + "close() of server failed", e);
        }
    }

}

5.交換資料

搜尋到裝置後可以獲取裝置的地址,通過此地址獲取一個BluetoothDeviced物件,可以看做客戶端,通過此物件device.createRfcommSocketToServiceRecord(MY_UUID);同一個UUID可與伺服器建立連接獲取另一個socket物件,由此服務端與客戶端各有一個socket物件,此時
他們可以互相交換資料了。
創立客戶端socket可建立執行緒

//另一個裝置去連線本機,相當於客戶端
private class ConnectThread extends Thread{
    private BluetoothSocket socket;
    private BluetoothDevice device;
    public ConnectThread(BluetoothDevice device,boolean secure){
        this.device = device;
        BluetoothSocket tmp = null;
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
        } catch (IOException e) {
             Log.e("app", "create() failed", e);
        }
    }
    
    public void run(){
        mBluetoothAdapter.cancelDiscovery();    //取消裝置查詢
        try {
            socket.connect();
        } catch (IOException e) {
            try {
                socket.close();
            } catch (IOException e1) {
                 Log.e("app", "unable to close() "+
                            " socket during connection failure", e1);
            }
            connetionFailed();    //連線失敗
            return;
        }
        //此時可以新建一個數據交換執行緒,把此socket傳進去
    }
    
      public void cancel() {
          try {
              socket.close();
          } catch (IOException e) {
              Log.e("app", "close() of connect  socket failed", e);
          }
      }
}

6.建立資料通訊執行緒,進行讀取資料

//建立連線後,進行資料通訊的執行緒
private class ConnectedThread extends Thread{
private BluetoothSocket socket;
private InputStream inStream;
private OutputStream outStream;

    public ConnectedThread(BluetoothSocket socket){
        
        this.socket = socket;
        try {
            //獲得輸入輸出流
            inStream = socket.getInputStream();
            outStream = socket.getOutputStream();
        } catch (IOException e) {
            Log.e("app", "temp sockets not created", e);
        }
    }
    
    public void run(){
        byte[] buff = new byte[1024];
        int len=0;
        //讀資料需不斷監聽,寫不需要
        while(true){
            try {
                len = inStream.read(buff);
                //把讀取到的資料傳送給UI進行顯示
                Message msg = handler.obtainMessage(BluetoothChat.MESSAGE_READ,
                        len, -1, buff);
                msg.sendToTarget();
            } catch (IOException e) {
                Log.e("app", "disconnected", e);
                connectionLost();    //失去連線
                start();    //重新啟動伺服器
                break;
            }
        }
    }
    
    
    public void write(byte[] buffer) {
        try {
            outStream.write(buffer);

            // Share the sent message back to the UI Activity
            handler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            Log.e("app", "Exception during write", e);
        }
    }

    public void cancel() {
        try {
            socket.close();
        } catch (IOException e) {
            Log.e("app", "close() of connect socket failed", e);
        }
    }
}