藍牙開發 基本思路

藍牙開發基本步驟
一、
   配置藍牙權限
   <use-permission name="android.permission.BLUTOOTH"></use-permission>
   <use-permission name="android.permission.BLUTOOTH_ADMIN"></use-permission>

2 、啓動藍牙
  (1)經過藍牙適配器檢查是否支持藍
       //獲取是適配器是否支持藍牙
        bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        if(bluetoothAdapter==null)
        {
           //不支持藍
        }

   (2) BluetoothAdapter.Enable();//不建議使用(會引起程序異常)

  (3)intent 方式啓動
       //打開意圖   REQUEST_ENABLE_BT
       Intent  startbt=new Intent();
       Context.startActivityForResult(startbt,REQUEST_ENABLE_BT);


三、發現藍牙設備
     //發現藍牙設備
        public  void  DiscoverDevice()
        {
             if(bluetoothAdapter.getScanMode()!=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
             {
                  Intent discover=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                 //btcontext 爲上下文對象
                  btcontext.startActivity(discover);
             }

        }
    //查找藍牙設備(以前適配過的藍牙設備)
        //查找以前適配過 的藍牙設備
        public Set<BluetoothDevice> FindExistsDevice(Set<BluetoothDevice> devices) {
            Set<BluetoothDevice> oldDevice = bluetoothAdapter.getBondedDevices();
            //有之前的設備
            if (oldDevice.size() > 0) {
                int index=0;
                for (BluetoothDevice device : oldDevice) {
                      index+=1;
                     if(devices.contains(device))
                     {
                         //除去重複設備
                         oldDevice.remove(device);
                     }

                }
                   devices=oldDevice;
                return  devices;

            }
            else
            {
                Log.i(TAG,"不存在歷史鏈接藍牙");

            }
            return null;
        }
      //搜索藍牙設備
      //先註冊廣播 來監聽
     (1)靜態註冊   <receiver android:name=".receive.Bluetooth_Receive"></receiver>  .receive.Bluetooth_Receive:爲自定義廣播 繼承自BroadcastReceiver
     (2)動態註冊

            //註冊廣播
            public void RegisterBrocastReceive() {
                //實例廣播對象
                bluetooth_receive = new Bluetooth_Receive();
                //過濾器
                IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
                //
                btcontext.registerReceiver(bluetooth_receive,intentFilter);
            }
         //處理廣播

          @Override
              public void onReceive(Context context, Intent intent) {


              }

          //搜索藍牙設備
         public void SearchDevice() {
                 bluetoothAdapter.startDiscovery();
         }


四、鏈接藍牙設備


    public class BluTooth_SocketServer extends Thread {
        private final  static  String TAG=BluTooth_SocketServer.class.getSimpleName();

        private   static  UUID SELF_UUID;
        private   BluetoothAdapter bluetoothAdapter;
        //相似於SocketServer  當作服務器監聽鏈接
        private BluetoothServerSocket serverSocket;
        public  BluTooth_SocketServer(String  uuid,BluetoothAdapter mb,String name)
        {
            SELF_UUID=UUID.fromString(uuid);
            this.bluetoothAdapter=mb;
            try {
            serverSocket=bluetoothAdapter.listenUsingRfcommWithServiceRecord(name,SELF_UUID);

            }
            catch (IOException e)
            {
                Log.i(TAG,"Listen faild",e);
            }

        }

        //在run方法中監聽鏈接
        @Override
        public void run() {
            BluetoothSocket socket=null;
            while (true)
            {
               try {
                   socket=serverSocket.accept(500);
               }
               catch (IOException e)
               {
                   Log.e(TAG,"accept() faild ",e);
                   break;
               }
            }

            if(socket!=null)
            {
                //數據交換
            }
        }
        //取消監聽
        public void  Cancel()
        {
          try {
              serverSocket.close();
          }
          catch (IOException e)
          {
              Log.e(TAG,"Socket Type  close() faild",e);
          }
        }
        //設置UUID
        public  void  SetUUID(String uuid)
        {
            this.SELF_UUID=UUID.fromString(uuid);
        }
    }


五、數據交換:

public class Connect_Thead extends Thread {
    private BluetoothSocket socket;
    private BluetoothDevice device;
    private BluetoothAdapter bluetoothAdapter;

    //初始化
    public Connect_Thead(BluetoothDevice device, boolean secure,BluetoothAdapter blue) {
        this.device = device;
        this.bluetoothAdapter=blue;
        BluetoothSocket tmp = null;
        try {
            tmp = device.createRfcommSocketToServiceRecord(UUID.randomUUID());
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.socket = tmp;

    }

    @Override
    public void run() {
        //取消搜索
        bluetoothAdapter.cancelDiscovery();
        try {
            socket.connect();
        }
        catch (IOException ie)
        {
            Log.d("run","unable to   close",ie);

        }

        //調用鏈接失敗函數
    }
    public void  cancel()
    {
        try {
            socket.close();
        }
        catch (IOException e)
        {
            Log.e("cancel","Socket failed",e);
        }
    }

}


6 消息處理

public class ChangData extends Thread {
    private final static String TAG = ChangData.class.getSimpleName();
    private BluetoothSocket socket;
    private InputStream input;
    private OutputStream output;
    private Handler hclient;

    //接收數據線程
    public ChangData(BluetoothSocket socket, Handler hclients) {
        this.socket = socket;
        this.hclient = hclients;
        try {

            input = socket.getInputStream();
            output = socket.getOutputStream();

        } catch (Exception e) {
            Log.e(TAG, "temp socket not created");

        }

    }

    //在run方法中獲取消息

    @Override
    public void run() {
        byte[] buff = new byte[1024];
        int len = 0;
        while (true) {
            try {

                len = input.read(buff);
                //向UI發送消息
                hclient.sendMessage(hclient.obtainMessage(0, len, -1, buff));

            } catch (IOException ie) {
                //失去鏈接
                conntionlist();
                start();
                ie.printStackTrace();
                break;
            }
        }
    }

    //失去鏈接方法
    public void conntionlist() {
    }

    //發送數據
    public void SenderMessage(byte[] msg) {
        try {
            if (output != null) {
                output.write(msg);
                output.flush();
                hclient.sendMessage(hclient.obtainMessage(1, -1, -1, msg));
            }
        } catch (Exception e) {
            Log.e(TAG, "發送數據異常");
        }
    }

    //取消鏈接
    public void cancel() {
        try {
            socket.close();
        } catch (IOException
                e) {
            Log.e(TAG, "關閉異常");
        }
    }
}
相關文章
相關標籤/搜索