bluetooth蓝牙小试牛刀

来源:互联网 发布:java招生 编辑:程序博客网 时间:2024/06/05 15:10

首先一个问题
android6.0之后,BluetoothDevice.ACTION_FOUND监听不到
需要两个权限

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

这是因为在6.0之后如果需要利用本机查找周围的wifi和蓝牙设备
开发步骤
一、获取BluetoothAdapter实例

BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

二、注册蓝牙监听

  IntentFilter filter = new IntentFilter();        filter.addAction(BluetoothDevice.ACTION_FOUND);        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);        registerReceiver(blueReceiver, filter); public class BlueReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            String action = intent.getAction();            // 获得已经搜索到的蓝牙设备            Log.e("tag",action+"==========");            if (action.equals(BluetoothDevice.ACTION_FOUND)) {                BluetoothDevice device = intent                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);                // 搜索到的不是已经绑定的蓝牙设备                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {                    // 显示在TextView上                 Log.e("tag",device.getName() + ":"                            + device.getAddress()+"\n");                }                // 搜索完成            } else if (action                    .equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {                setProgressBarIndeterminateVisibility(false);            }        }

三、开启蓝牙搜索
//判断蓝牙是否开启
if( !bluetoothAdapter.isEnabled()){
bluetoothAdapter.enable();
bluetoothAdapter.startDiscovery();
}

四、开启蓝牙的两种方式
1、 bluetoothAdapter.enable();
//比较人性化,会弹窗
2 Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(mIntent, 1);

五 创建蓝牙连接
首先遇到的问题说一下
read failed, socket might closed or timeout, read ret: -1导致连接失败
//address蓝牙地址

BluetoothDevice device=bluetoothAdapter.getRemoteDevice(address);BluetoothSocket  clientSocket = device.createInsecureRfcommSocketToServiceRecord(UUID                                .fromString("00001101-0000-1000-8000-00805F9B34FB")); try {                                    clientSocket.connect(); //获得输出流(客户端指向服务端输出文本)   os = clientSocket.getOutputStream();      Log.e("tag", "start connect"); if (os != null) { //往服务端写信息 os.write("蓝牙信息来了".getBytes("utf-8"));    }       } catch (IOException e) {  try {  //解决来连接蓝牙超时失败的  clientSocket =(BluetoothSocket)device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);                                        clientSocket.connect();     } catch (Exception e1) {e1.printStackTrace();   } }
0 0
原创粉丝点击