Android従来のBluetooth開発(サンプルソースコード付)


前:本文はQiaoJimのオリジナルで、転載は原文のリンクを添付して、協力に感謝します!
http://blog.csdn.net/qiao_jim/article/details/73008695
----------------------------------------------------------------------------------
最近androidの伝統的なBluetoothを勉強して、自分で考えを整理して、それからBluetoothStudioの小さいテストプログラムを書いて、理解したandroidの伝統的なBluetooth開発技術を運用して、書きます
いくつかの心得と構想は、他のandroid愛好者の参考になり、後で振り返るのに便利です.
ブログに間違いがあれば、コメントを歓迎します.ありがとうございます.ブログは最後にソースコードを添付して、ダウンロードして参考にすることができます.
一、全体の考え方と対応に関する方法
1、BluetoothAdapter:BluetoothAdapter.getDefaultAdapter()を取得する.
2、Bluetoothを開く:ユーザーに開く(推奨)または直接bluetooth Adapter.enable()を尋ねる.
3、バインドされたデバイスを検索し、新しいデバイスを発見する:bluetoothAdapter.getBondedDevices();bluetoothAdapter.startDiscovery();
4.1、サービス側、ずっと要求を傍受して、その側が自発的に要求を出す時、その側の傍受を閉じて、役割はクライアントに変わる:
bluetoothDevice.createRfcommSocketToServiceRecord(UUID);
4.2、クライアント、ターゲットデバイスをクリックして、ペアリング接続:
bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, UUID);
5、BluetoothSocket通信による:IOストリーム読み書き
二、開発の詳細
1、権限を宣言し、必要なランタイム権限に注意する
        
        
        
        

Android 6.0以上のデバイスが新しいBluetoothを発見した場合、ランタイム権限を追加する必要があります.そうしないとACTION_を傍受できません.FOUND放送
        if (Build.VERSION.SDK_INT >= 6.0) {
            ActivityCompat.requestPermissions(getActivity(), 
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                             Params.MY_PERMISSION_REQUEST_CONSTANT);
        }

        public void onRequestPermissionsResult(int requestCode, String permissions[],
                                               int[] grantResults) {
           switch (requestCode) {
              case Params.MY_PERMISSION_REQUEST_CONSTANT: {
                  if (grantResults.length > 0 
                          && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                       //         
                   }
                  return;
               }
           }
        }

2、Bluetoothを開き、ダイアログ形式でユーザーに開くことを勧める
       bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

       //      ,    
       if (!bluetoothAdapter.isEnabled()) {
            Intent turnOnBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnOnBtIntent, Params.REQUEST_ENABLE_BT);
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (requestCode) {
                case Params.REQUEST_ENABLE_BT: {
                    //      
                    if (resultCode == RESULT_OK) {
                        //         
                        showBondDevice();
                    }
                    break;
                }
                case Params.REQUEST_ENABLE_VISIBILITY: {
                    //               ,600           (         )
                    if (resultCode == 600) {
                        toast("       ");
                    } else if (resultCode == RESULT_CANCELED) {
                        toast("        ,   ");
                    }
                    break;
                }
            }
        }

3、Bluetooth AdapterでバインドされたBluetoothデバイスを取得する
        private void showBondDevice() {
            deviceList.clear();
            //        ,  Set  
            Set tmp = bluetoothAdapter.getBondedDevices();
            for (BluetoothDevice d : tmp) {
                deviceList.add(d);
            }
            //    
            listAdapter.notifyDataSetChanged();
        }

4、Bluetoothデバイスを発見し、デバイスを発見したら、ACTIONを送信する.FOUNDブロードキャスト、ブロードキャスト受信機の登録、対応するBluetoothデバイス情報の取得
        bluetoothAdapter.startDiscovery();

        intentFilter = new IntentFilter();
        btReceiver = new MyBtReceiver();
        //       ,    ,      3   
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        getActivity().registerReceiver(btReceiver, intentFilter);
        //     
        private class MyBtReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                    toast("     ...");
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    toast("    ");
                } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    //       
                    BluetoothDevice device = 
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                        deviceList.add(device);
                        listAdapter.notifyDataSetChanged();
                    }
                }
            }
        }

5、デバイス接続、サーバー側のオープンスレッドはずっと接続を待っていて、クライアントはあるターゲットデバイスをクリックして、サーバースレッドの傍受を閉じて、そしてスレッドを開いて、接続要求を出す. 
注意:クライアントが接続する前に、必ずcancelDiscovery()
        //      
        if (bluetoothAdapter.isEnabled()) {
            showBondDevice();
            //           
            if (serverThread != null) {
                serverThread.cancel();
            }
            serverThread = new ServerThread(bluetoothAdapter, uiHandler);
            new Thread(serverThread).start();
        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView> parent, View view, 
                                    int position, long id) {
                //        
                if (serverThread != null) {
                    serverThread.cancel();
                    serverThread=null;
                }
                BluetoothDevice device = deviceList.get(position);
                //        ,         
                clientThread = new ClientThread(bluetoothAdapter, device, uiHandler);
                new Thread(clientThread).start();

                //    ui          
                Message message = new Message();
                message.what = Params.MSG_CONNECT_TO_SERVER;
                message.obj = device;
                uiHandler.sendMessage(message);
            }
        });

6、BluetoothSocket接続を確立した後、IOストリームデータ伝送を使用して、サーバーとクライアントの読み書きデータは類似で、一部のコードを貼って参考にする
        public void writeData(String dataSend) {
            if (serverThread != null) {
                serverThread.write(dataSend);
            } else if (clientThread != null) {
                clientThread.write(dataSend);
            }
        }
        //   
        public void write(String data){
            try {
                out.write(data.getBytes("utf-8"));            
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        new Thread(new Runnable() {
                @Override
                public void run() {
                    byte[] buffer = new byte[1024];
                    int len;
                    String content;
                    try {
                        //   
                        while ((len=in.read(buffer)) != -1) {
                            content=new String(buffer, 0, len);
                            Message message = new Message();
                            message.what = Params.MSG_CLIENT_REV_NEW;
                            message.obj = content;
                            //   ui
                            uiHandler.sendMessage(message);
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

7、その他の説明
(1)新しいデバイスバインディング,bluetoothDevice.createBond()
(2)デバイスが発見できる時間を設定する:
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  
enableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 600);  
startActivityForResult(enableIntent, Params.REQUEST_ENABLE_VISIBILITY); 

(3)サーバはリモートデバイスを取得し、bluetoothSocket.getRemoteDevice() 
(4)MACによりブルートゥースデバイス、bluetooth Adapter.getRemoteDevice(String address)を取得する 
(5)Bluetooth、bluetooth Adapter.disable()をオフにします.
三、ソースサンプルのダウンロード
ソースコードgithubアドレスを添付して、助けがあれば★をつけるのを忘れないでね. https://github.com/QiaoJim/BluetoothStudy
読んでくれてありがとう.間違いがあったら、伝言を残してください.博文がいいと思ったら、「いいね」をクリックして支持してください. 
四、効果図
android 传统蓝牙开发 (附示例源码)_第1张图片         android 传统蓝牙开发 (附示例源码)_第2张图片