1. 首先需要在AndroidManifest.xml中导入以下权限: <uses-permission android:name = "android.permission.BLUETOOTH" /> <uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN"/>



2. 把你手机的蓝牙设置设置为可用状态,这里有两步:
A. 获得BluetoothAdapter,如果返回值为null,说明设备不支持蓝牙
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}

B. 打开蓝牙设备驱动,BluetoothAdapter.ACTION_REQUEST_ENABLE 打开一个对话框进行选择
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult
(enableBtIntent, REQUEST_ENABLE_BT);
}



3. 寻找蓝牙设备

A. 首先获取已配对的远端设备,并把设备的名字以及地址添加到adapter
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter
.add(device.getName() + "\n" + device.getAddress());
}
}
B. 然后通过BluetoothAdapter.startDiscovery启动蓝牙设备的搜索备,注意:这是一个异步方法,调用的时候立刻就会返回。为了获得搜寻的结果,必须在用户自己的Activity中注册一个BroadcastReceiver
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter
.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver
(mReceiver, filter); // Don't forget to unregister during onDestroy
C. 使你的设备能够被其他设备搜索到
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent
.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity
(discoverableIntent);


4. 连接设备
A. 作为连接方的服务器
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;

public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp
= mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) { }
mmServerSocket
= tmp;
}

public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket
= mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
manageConnectedSocket
(socket);
mmServerSocket
.close();
break;
}
}
}

/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket
.close();
} catch (IOException e) { }
}
}
B. 作为连接方的客户端
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;

public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice
= device;

// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp
= device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket
= tmp;
}

public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter
.cancelDiscovery();

try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket
.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket
.close();
} catch (IOException closeException) { }
return;
}

// Do work to manage the connection (in a separate thread)
manageConnectedSocket
(mmSocket);
}

/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket
.close();
} catch (IOException e) { }
}
}
5. 设备连接时候的数据传输
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket) {
mmSocket
= socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;

// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn
= socket.getInputStream();
tmpOut
= socket.getOutputStream();
} catch (IOException e) { }

mmInStream
= tmpIn;
mmOutStream
= tmpOut;
}

public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()

// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes
= mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler
.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}

/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream
.write(bytes);
} catch (IOException e) { }
}

/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket
.close();
} catch (IOException e) { }
}
}

更多相关文章

  1. adb通过wifi连接android设备的方法
  2. 通过JavaScript或PHP检测Android设备
  3. Android设备唯一标识符(适配Android Q)
  4. Android获取存储设备挂载路径
  5. Android有两种方法检测USB设备插入
  6. 【Android开发学习01】与Android实体设备的连接
  7. android蓝牙BLE(三) —— 广播
  8. android基础知识17:Android设备常见问题与测试要领

随机推荐

  1. Android自带的时间空间和日期控件
  2. android 添加视频、图片、录音上传(一)
  3. Android(安卓)6.0后 apk权限默认开启
  4. Ubuntu 14.04 64位机上配置Android Studi
  5. Android studio更新
  6. android弹出选择对话框-仿某团购网androi
  7. android studio打包 so文件
  8. App开发日报 2015-05-19 Android依赖注入
  9. android 通知栏背景颜色跟随app导航栏背
  10. android关于获取摄像头帧数据转成图片