android蓝牙相关

2017-03-20  本文已影响95人  dong_hui

1.android蓝牙的几个基本概念

<uses-permissionandroid:name="[Android](http://lib.csdn.net/base/android).permission.BLUETOOTH" />
允许程序连接到已配对的蓝牙设备。
<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" />
允许程序发现和配对蓝牙设备。
import android.bluetooth.BluetoothAdapter;

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  
 if(!mBluetoothAdapter.isEnabled()){  
//弹出对话框提示用户是后打开  
Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
startActivityForResult(enabler, REQUEST_ENABLE);  
      //不做提示,直接打开,不建议用下面的方法,有的手机会有问题。  
      // mBluetoothAdapter.enable();  
}  

//获取本机蓝牙名称  
String name = mBluetoothAdapter.getName();  
//获取本机蓝牙地址  
String address = mBluetoothAdapter.getAddress();  
Log.d(TAG,"bluetooth name ="+name+" address ="+address);  
//获取已配对蓝牙设备  
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();  
Log.d(TAG, "bonded device size ="+devices.size());  
for(BluetoothDevice bonddevice:devices){  
    Log.d(TAG, "bonded device name ="+bonddevice.getName()+" address"+bonddevice.getAddress());  
}  
IntentFilter filter = new IntentFilter();  
//发现设备  
filter.addAction(BluetoothDevice.ACTION_FOUND);  
//设备连接状态改变  
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);  
//蓝牙设备状态改变  
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);  
registerReceiver(mBluetoothReceiver, filter);  
private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver(){  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            Log.d(TAG,"mBluetoothReceiver action ="+action);  
            if(BluetoothDevice.ACTION_FOUND.equals(action)){//每扫描到一个设备,系统都会发送此广播。  
                //获取蓝牙设备  
                BluetoothDevice scanDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
                if(scanDevice == null || scanDevice.getName() == null) return;  
                Log.d(TAG, "name="+scanDevice.getName()+"address="+scanDevice.getAddress());  
                //蓝牙设备名称  
                String name = scanDevice.getName();  
                if(name != null && name.equals(VnApplication.BLUETOOTH_NAME)){  
                    mBluetoothAdapter.cancelDiscovery();  
                    //取消扫描  
                    mProgressDialog.setTitle(getResources().getString(R.string.progress_connecting));                   //连接到设备。  
                    mBlthChatUtil.connect(scanDevice);  
                }  
            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){  
  
            }  
        }  
          
    };  
BluetoothSocket  mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
mmSocket.connect();

mmOutStream.write(buffer);发送信息。
mmInStream.read(buffer); 收到消息。

Paste_Image.png Paste_Image.png Paste_Image.png Paste_Image.png
上一篇下一篇

猜你喜欢

热点阅读