蓝牙






添加权限:

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

<uses-permission android:name="android.permission.BLUETOOTH"/>

  • 客户端


开启蓝牙:

/**

 * 打开蓝牙设备

 */

void openBT(){

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (mBluetoothAdapter!= null){

        if (!mBluetoothAdapter.isEnabled()){

            mBluetoothAdapter.enable();

            Log.d("qfopenBT","打开蓝牙成功");

        }

    }

}


搜索蓝牙:

/**

 * 搜索蓝牙设备

 * @param view

 */

@OnClick(R.id.btSearch)

public void startSearch(View view){

    if(mBluetoothAdapter!= null &&mBluetoothAdapter.isEnabled()){

        if (!mBluetoothAdapter.isDiscovering()){

            mBluetoothAdapter.startDiscovery();

        }

    }


}

开启搜索是异步操作,发现设备后会发送广播,所以要定义广播接收者

在接收到广播后,获取广播里的蓝牙数据

private class BTBroadCastRevextends BroadcastReceiver{


    @Override

    public void onReceive(Context context,Intent intent) {

        String strAction = intent.getAction();

        if (strAction.equals(BluetoothDevice.ACTION_FOUND)){

            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);


                mArrDevice.add(device);

                mAdapter.notifyDataSetChanged();

            



        }

        else if(strAction.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){

            Log.d("qfonReceive","搜索完成");

        }


    }

}



//注册广播接收者

myReceive = newBTBroadCastRev();

IntentFilter ifFind = new IntentFilter(BluetoothDevice.ACTION_FOUND);

this.registerReceiver(myReceive,ifFind);


IntentFilter ifFinishFind = newIntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

this.registerReceiver(myReceive,ifFinishFind);

连接蓝牙,并开启发送数据线程:



/**

 * 点击item,连接对应的蓝牙设备

 */

protected void connectBT() {

    mLvDevice.setOnItemClickListener(newAdapterView.OnItemClickListener() {

        @Override

        public void onItemClick(AdapterView<?> parent,View view, int position, longid) {

            MyClientTask task = newMyClientTask();

            task.execute(mArrDevice.get(position));


        }

    });

}

class MyClientTask extends AsyncTask<BluetoothDevice,Void,Void>{



    @Override

    protected VoiddoInBackground(BluetoothDevice... devices) {


        BluetoothDevice device = devices[0];

        try {

            //使用安全连接,服务端也要一样使用安全连接,UUID也要跟服务器的监听UUID一致

            BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);

            socket.connect();

            Log.d("qfdoInBackground_client","连接成功,开始发送数据");


            byte[] btMsg =new String("Hello").getBytes();

            socket.getOutputStream().write(btMsg,0,btMsg.length);


        } catch(Exception e) {

            e.printStackTrace();

        }


        return null;

    }

}

uuid可以通过uuidgen生成,生成结果类似以下结构:

5D3D5E52-338A-47B8-9F10-27ADF89E204E

  • 服务端

开启蓝牙,跟客户端一样


启动服务线程



new RevTask().execute();


class RevTask extendsAsyncTask<Void,Void,String>{


    @Override

    protected void onPostExecute(String s) {

        super.onPostExecute(s);


        tvMsg.setText(s);

    }


    @Override

    protected StringdoInBackground(Void... params) {



        try {

            Log.d("qfdoInBackground","开始监听");

            //要跟客户端uuid一致

            BluetoothServerSocket sevSocket =mBluetoothAdapter.listenUsingRfcommWithServiceRecord("blue_service",MY_UUID_SECURE);

            BluetoothSocket socket = sevSocket.accept();

            if(socket != null){

                Log.d("qfdoInBackground","连接成功");

                InputStream stream = socket.getInputStream();

                byte[] btRead =new byte[1024];

                int iLength = stream.read(btRead);

                Log.d("qfdoInBackground","读取数据成功"+iLength);

                String strMsg =new String(btRead,"utf-8");

                Log.d("qfdoInBackground",strMsg);

               return strMsg;


            }

            else{

                Log.d("qfdoInBackground","失败");

            }

        } catch (IOException e) {

            e.printStackTrace();

            Log.d("qfdoInBackground","异常");

        }




        return null;

    }

}


上述代码没有实现配对,对应经典蓝牙通信,最好先进行配对再连接,已经配对的蓝牙设备可以直接通过adapter获取到


//得到所有已经配对的蓝牙适配器对象
Set<BluetoothDevice> devices = adapter.getBondedDevices();
               

没有配对的蓝牙设备,可以在扫描设备的广播通知中判断:

if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                  ......
                }
点击设备连接时,判断是否已经配对,如果已经配对,直接连接,如果没有配对,先配对:

  1. if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {  
  2.                     //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);  
  3.                     Method createBondMethod = BluetoothDevice.class  
  4.                             .getMethod("createBond");  
  5.                     Log.d("BlueToothTestActivity""开始配对");  
  6.                     returnValue = (Boolean) createBondMethod.invoke(btDev);  
  7.                       
  8.                 }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){  
  9.                     connect(btDev);  
  10.                 }  

配对结果也会通过广播传递结果信息:

  1. // 注册Receiver来获取蓝牙设备相关的结果  
  2.         IntentFilter intent = new IntentFilter();  
  3.         intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果  
  4.         intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);  
  5.         intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);  
  6.         intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);  
  7.         registerReceiver(searchDevices, intent); 

  1. if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){  
  2.                 device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  3.                 switch (device.getBondState()) {  
  4.                 case BluetoothDevice.BOND_BONDING:  
  5.                     Log.d("BlueToothTestActivity""正在配对......");  
  6.                     break;  
  7.                 case BluetoothDevice.BOND_BONDED:  
  8.                     Log.d("BlueToothTestActivity""完成配对");  
  9.                     connect(device);//连接设备  
  10.                     break;  
  11.                 case BluetoothDevice.BOND_NONE:  
  12.                     Log.d("BlueToothTestActivity""取消配对");  
  13.                 default:  
  14.                     break;  
  15.                 }  





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值