蓝牙通信需要一个客户端和一个服务端
蓝牙操作需要在manifest.xml文件里添加蓝牙权限
<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permissionandroid:name="android.permission.BLUETOOTH" />
客户端蓝牙操作:
获取本地蓝牙适配器
BluetoothAdapter
mAdapter= BluetoothAdapter.getDefaultAdapter();
2、打开蓝牙
if(!mAdapter.isEnabled()){
//弹出对话框提示用户是后打开
Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler, REQUEST_ENABLE);
//不做提示,强行打开
// mAdapter.enable();
}
3、搜索设备
mAdapter.startDiscovery()
需要定义一个广播接收器,用来接收蓝牙搜索的结果代码如下
BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//找到设备
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
Log.v(TAG, "find device:" + device.getName()
+ device.getAddress());
}
}
//搜索完成
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
setTitle("搜索完成");
if (mNewDevicesAdapter.getCount() == 0) {
Log.v(TAG,"find over");
}
}
//执行更新列表的代码
}
};
BroadcastReceiver,具体代码如下
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
(这段代码,一般写在onCreate()里..)
4、建立蓝牙连接
客户端
BluetoothSocket clienSocket=dcvice. createRfcommSocketToServiceRecord(UUID);
clienSocket.connect();
服务端
BluetoothServerSocket serverSocket = mAdapter. listenUsingRfcommWithServiceRecord(serverSocketName,UUID);
serverSocket.accept();
5、数据通信
inputStream
= socket.getInputStream();//获取输入流
outputStream = socket.getOutputStream();//获取输出流
outputStream.write("需要发送的数据");
inputStream.read("需要接收的数据");
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u010184245/article/details/47420959