蓝牙开发 基本思路

蓝牙开发基本步骤
一、
   配置蓝牙权限
   <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, "关闭异常");
        }
    }
}
相关文章
相关标签/搜索