本人刚接触蓝牙开发不久,对蓝牙客户的开发有一点积累。
今天就在这做一个分享,希望对有需要的人有一点帮助。
如果你对蓝牙开发一无所知,可以看一下Mars的视频,里面有两集是关于蓝牙的,都是基础内容。
here we go.
首先,要在Manifest中加入蓝牙操作的权限,如下
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
然后 就是activity部分。
第一步 开启蓝牙功能,蓝牙不开启其他的都无法操作。代码如下
//判断蓝牙是否开启
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
//开启蓝牙的指令
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
第二部就是搜索蓝牙,(当然这一步也可以改为自动连接,查看是否有连接过的的蓝牙MAC地址,如果有就自动连接)。
mBtAdapter.startDiscovery();//开启蓝牙搜索
第三部就是配对了,配对要在service中完成。
//获得可用的远程蓝牙设备
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 得到之后判断一下此设备是否已配对,如果已配对则跳过
//否则将此设备的名字及mac地址添加到列表
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
{
mNewDevicesArrayAdapter.add(device.getName() + "\n"
+ device.getAddress());
}
//当选择一个要配对的设备,首先要取消蓝牙搜索
mBtAdapter.cancelDiscovery();
// 获得设备地址,这是近17字的
//视图
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
//创建结果意图和包括地址
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
//结果,完成这项活动
setResult(Activity.RESULT_OK, intent);
在接下来就是创建socket连接,获取输入输出流,这些已经不是蓝牙内容了,就不具体写了。
具体内容参见如下代码:
public void onStart() {
super.onStart();
if (D)
Log.e(TAG, "++MainActity--------------------> ON START ++");
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the session
} else {
if (mBluetoothReceiver == null)
setupService();
}
}
@Override
public synchronized void onResume() {
super.onResume();
if (D)
Log.e(TAG, "MainActivity---------->" + "ON RESUME +");
mBluetoothReceiver = new BluetoothReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.lxx");
MainActivity.this.registerReceiver(mBluetoothReceiver, filter);
if (D)
Log.e(TAG, "MainActivity---------->" + "ON RESUME + register Receiver success");
}
private void setupService() {
Log.d(TAG, "setupService()");
// Broadcast receiver
// Initialize the BluetoothService to perform bluetooth connections
mBluetoothService=new BluetoothService();
System.out.println("sp--------getting------>"+"address");
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
mReceiveData = new String[] { "" };
sp = MainActivity.this.getSharedPreferences("Device", MODE_PRIVATE);
// Get the device MAC address
String address = sp.getString("Address", "");
// Toast.makeText(this, mAddress,Toast.LENGTH_LONG).show();
if (address.equals(""))
startConectPairedDevice();
else {
Intent it = new Intent(MainActivity.this, BluetoothService.class);
it.putExtra("address", address);
startService(it);
Service 中的部分:
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
String address=intent.getStringExtra("address");
Log.d(TAG, "++--------server the 2 setp------------------->onStartCommand ++ "+address);
BluetoothDevice device=mAdapter.getRemoteDevice(address);
BluetoothService.this.connect(device,true);
return super.onStartCommand(intent, flags, startId);
}
public synchronized void connect(BluetoothDevice device, boolean secure) {
if (D)
Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device, secure);
mConnectThread.start();
setState(STATE_CONNECTING);
System.out.println("now connectthread is connecting........");
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private String mSocketType;
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
connected=false;
mSocketType = secure ? "Secure" : "Insecure";
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
if (secure) {
tmp = device
.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
tmp = device
.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "----------- " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
System.out.println("got socket----------------------------from connectthread");
}
public void run() {
setName("ConnectThread" + mSocketType);
System.out.println("--------------- socket conneting-----------------" + "?" + connected);
mAdapter.cancelDiscovery();
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
connected=true;
System.out.println(" --------------- socket connected-----------------");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
System.out.println(" --------------- socket exception-----------------");
} catch (IOException e2) {
Log.e(TAG, "unable to close() ---------------" + mSocketType
+ " socket during connection failure", e2);
}
}
if (!connected){
connectionFailed();
System.out.println("connectionFailed,,, then back to connectthread-------");
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect----------> " + mSocketType
+ " socket failed", e);
}
}
}
不太会分享,不知道童鞋们看懂了多少,呵呵。另附qq群号,欢迎加群聊,互相学习,提高。
蓝牙开发交流群号:297587224,暂时只限蓝牙开发的朋友。