蓝牙一对多连接

代码太多,我直接用了一个可以运行的包,核心代码就是有两个同样的uuid

mUuid.add(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
mUuid.add(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));


/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.hao.activity.server;


import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import com.hao.activity.IConnection;
import com.hao.activity.IConnectionCallback;
import com.hao.activity.StartDiscoverableModeActivity;
import com.hao.activity.util.FetchData;


/**
 * Service for simplifying the process of establishing Bluetooth connections and
 * sending data in a way that is geared towards multi-player games.
 */


public class ConnectionService extends Service {
public static final String TAG = "net.clc.bt.ConnectionService";


private ArrayList<UUID> mUuid;


private ConnectionService mSelf;


private String mApp; // Assume only one app can use this at a time; may


// change this later
FetchData fd = new FetchData();
private IConnectionCallback mCallback;


private ArrayList<String> mBtDeviceAddresses;


private HashMap<String, BluetoothSocket> mBtSockets;


private HashMap<String, Thread> mBtStreamWatcherThreads;


private BluetoothAdapter mBtAdapter;

public ConnectionService() {
mSelf = this;
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
mApp = "";
mBtSockets = new HashMap<String, BluetoothSocket>();
mBtDeviceAddresses = new ArrayList<String>();
mBtStreamWatcherThreads = new HashMap<String, Thread>();
mUuid = new ArrayList<UUID>();


mUuid.add(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
mUuid.add(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
/*
* mUuid.add(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
* mUuid.add(UUID.fromString("503c7430-bc23-11de-8a39-0800200c9a66"));
* mUuid.add(UUID.fromString("503c7431-bc23-11de-8a39-0800200c9a66"));
* mUuid.add(UUID.fromString("503c7432-bc23-11de-8a39-0800200c9a66"));
* mUuid.add(UUID.fromString("503c7433-bc23-11de-8a39-0800200c9a66"));
* mUuid.add(UUID.fromString("503c7434-bc23-11de-8a39-0800200c9a66"));
* mUuid.add(UUID.fromString("503c7435-bc23-11de-8a39-0800200c9a66"));
*/
}


@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}


private class BtStreamWatcher implements Runnable {
private String address;


public BtStreamWatcher(String deviceAddress) {
address = deviceAddress;
}


public void run() {


BluetoothSocket bSock = mBtSockets.get(address);
try {
InputStream instream = bSock.getInputStream();


String message = "";
BufferedReader bufferedReader;
while (true) {
message = "";
if (instream.available() > 0) {
bufferedReader = new BufferedReader(
new InputStreamReader(instream));
if ((message = bufferedReader.readLine()) != null) {
Thread.sleep(0);
mCallback.messageReceived(address, message);
}
}
}
} catch (IOException e) {
Log
.i(
TAG,
"IOException in BtStreamWatcher - probably caused by normal disconnection",
e);
} catch (RemoteException e) {
Log
.e(
TAG,
"RemoteException in BtStreamWatcher while reading data",
e);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Getting out of the while loop means the connection is dead.
try {
mBtDeviceAddresses.remove(address);
mBtSockets.remove(address);
mBtStreamWatcherThreads.remove(address);
mCallback.connectionLost(address);
} catch (RemoteException e) {
Log
.e(
TAG,
"RemoteException in BtStreamWatcher while disconnecting",
e);
}
}
}


private class ConnectionWaiter implements Runnable {
private String srcApp;


private int maxConnections;


public ConnectionWaiter(String theApp, int connections) {
srcApp = theApp;
maxConnections = connections;
}


public void run() {
try {
for (int i = 0; i < Connection.MAX_SUPPORTED
&& maxConnections > 0; i++) {
BluetoothServerSocket myServerSocket = mBtAdapter
.listenUsingRfcommWithServiceRecord(srcApp, mUuid
.get(i));
BluetoothSocket myBSock = myServerSocket.accept();
myServerSocket.close(); // Close the socket now that the
// connection has been made.


String address = myBSock.getRemoteDevice().getAddress();


mBtSockets.put(address, myBSock);
mBtDeviceAddresses.add(address);
Thread mBtStreamWatcherThread = new Thread(
new BtStreamWatcher(address));
mBtStreamWatcherThread.start();
mBtStreamWatcherThreads
.put(address, mBtStreamWatcherThread);
maxConnections = maxConnections - 1;
if (mCallback != null) {
mCallback.incomingConnection(address);
}
}
if (mCallback != null) {
mCallback.maxConnectionsReached();
}
} catch (IOException e) {
Log.i(TAG, "IOException in ConnectionService:ConnectionWaiter",
e);
} catch (RemoteException e) {
Log
.e(
TAG,
"RemoteException in ConnectionService:ConnectionWaiter",
e);
}
}
}


private BluetoothSocket getConnectedSocket(BluetoothDevice myBtServer,
UUID uuidToTry) {
BluetoothSocket myBSock;
try {
myBSock = myBtServer.createRfcommSocketToServiceRecord(uuidToTry);
myBSock.connect();
return myBSock;
} catch (IOException e) {
Log.i(TAG, "IOException in getConnectedSocket", e);
}
return null;
}


private final IConnection.Stub mBinder = new IConnection.Stub() {
public int startServer(String srcApp, int maxConnections)
throws RemoteException {
if (mApp.length() > 0) {
return Connection.FAILURE;
}
mApp = srcApp;
(new Thread(new ConnectionWaiter(srcApp, maxConnections))).start();
Intent i = new Intent();
i.setClass(mSelf, StartDiscoverableModeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
return Connection.SUCCESS;
}


public int connect(String srcApp, String device) throws RemoteException {
if (mApp.length() > 0) {
return Connection.FAILURE;
}
mApp = srcApp;
BluetoothDevice myBtServer = mBtAdapter.getRemoteDevice(device);
BluetoothSocket myBSock = null;


for (int i = 0; i < Connection.MAX_SUPPORTED && myBSock == null; i++) {
for (int j = 0; j < 3 && myBSock == null; j++) {
myBSock = getConnectedSocket(myBtServer, mUuid.get(i));
if (myBSock == null) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Log.e(TAG, "InterruptedException in connect", e);
}
}
}
}
if (myBSock == null) {
return Connection.FAILURE;
}


mBtSockets.put(device, myBSock);
mBtDeviceAddresses.add(device);
Thread mBtStreamWatcherThread = new Thread(new BtStreamWatcher(
device));
mBtStreamWatcherThread.start();
mBtStreamWatcherThreads.put(device, mBtStreamWatcherThread);
return Connection.SUCCESS;
}


public int broadcastMessage(String srcApp, String message)
throws RemoteException {
if (!mApp.equals(srcApp)) {
return Connection.FAILURE;
}
for (int i = 0; i < mBtDeviceAddresses.size(); i++) {
sendMessage(srcApp, mBtDeviceAddresses.get(i), message);
}
return Connection.SUCCESS;
}


public String getConnections(String srcApp) throws RemoteException {
if (!mApp.equals(srcApp)) {
return "";
}
String connections = "";
for (int i = 0; i < mBtDeviceAddresses.size(); i++) {
connections = connections + mBtDeviceAddresses.get(i) + ",";
}
return connections;
}


public int getVersion() throws RemoteException {
try {
PackageManager pm = mSelf.getPackageManager();
PackageInfo pInfo = pm
.getPackageInfo(mSelf.getPackageName(), 0);
return pInfo.versionCode;
} catch (NameNotFoundException e) {
Log.e(TAG, "NameNotFoundException in getVersion", e);
}
return 0;
}


public int registerCallback(String srcApp, IConnectionCallback cb)
throws RemoteException {
if (!mApp.equals(srcApp)) {
return Connection.FAILURE;
}
mCallback = cb;
return Connection.SUCCESS;
}


public int sendMessage(String srcApp, String destination, String message)
throws RemoteException {
if (!mApp.equals(srcApp)) {
return Connection.FAILURE;
}
try {
BluetoothSocket myBsock = mBtSockets.get(destination);
if (myBsock != null) {
OutputStream outStream = myBsock.getOutputStream();
byte[] stringAsBytes = (message + " ").getBytes();
stringAsBytes[stringAsBytes.length - 1] = 0; // Add a stop
// marker
outStream.write(stringAsBytes);
return Connection.SUCCESS;
}
} catch (IOException e) {
Log.i(TAG, "IOException in sendMessage - Dest:" + destination
+ ", Msg:" + message, e);
}
return Connection.FAILURE;
}


public void shutdown(String srcApp) throws RemoteException {
try {
for (int i = 0; i < mBtDeviceAddresses.size(); i++) {
BluetoothSocket myBsock = mBtSockets.get(mBtDeviceAddresses
.get(i));
myBsock.close();
}
mBtSockets = new HashMap<String, BluetoothSocket>();
mBtStreamWatcherThreads = new HashMap<String, Thread>();
mBtDeviceAddresses = new ArrayList<String>();
mApp = "";
} catch (IOException e) {
Log.i(TAG, "IOException in shutdown", e);
}
}


public int unregisterCallback(String srcApp) throws RemoteException {
if (!mApp.equals(srcApp)) {
return Connection.FAILURE;
}
mCallback = null;
return Connection.SUCCESS;
}


public String getAddress() throws RemoteException {
return mBtAdapter.getAddress();
}


public String getName() throws RemoteException {
return mBtAdapter.getName();
}
};


}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的 Android 蓝牙一对多连接示例: 1. MainActivity.java ``` public class MainActivity extends AppCompatActivity { private BluetoothAdapter mBluetoothAdapter; private ArrayList<BluetoothSocket> mSockets = new ArrayList<>(); private ArrayList<BluetoothDevice> mDevices = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 获取蓝牙适配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 扫描蓝牙设备 scanDevices(); } // 扫描蓝牙设备 private void scanDevices() { mBluetoothAdapter.startDiscovery(); IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); } // 广播接收器,用于获取扫描到的蓝牙设备 private final 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 (!mDevices.contains(device)) { mDevices.add(device); connectDevice(device); } } } }; // 连接蓝牙设备 private void connectDevice(BluetoothDevice device) { new Thread(() -> { try { BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.randomUUID()); socket.connect(); mSockets.add(socket); } catch (IOException e) { e.printStackTrace(); } }).start(); } // 发送消息给所有连接的设备 private void sendMessages(String message) { for (BluetoothSocket socket : mSockets) { try { OutputStream outputStream = socket.getOutputStream(); outputStream.write(message.getBytes()); } catch (IOException e) { e.printStackTrace(); } } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); for (BluetoothSocket socket : mSockets) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` 2. activity_main.xml ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/btn_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送消息"/> </LinearLayout> ``` 在上面的示例中,我们使用 `BluetoothAdapter` 获取蓝牙适配器,并调用 `startDiscovery()` 方法开始扫描蓝牙设备。然后,我们使用 `BroadcastReceiver` 监听 `ACTION_FOUND` 广播,获取扫描到的蓝牙设备,并使用 `connectDevice()` 方法连接设备。 连接设备时,我们使用 `UUID.randomUUID()` 方法生成一个 UUID,并以此创建一个 `BluetoothSocket`。然后,我们调用 `connect()` 方法连接设备,并将连接的 `BluetoothSocket` 添加到 `mSockets` 列表中。 最后,我们使用 `sendMessages()` 方法发送消息给所有连接的设备。在 `onDestroy()` 方法中,我们注销 `BroadcastReceiver` 并关闭所有连接的 `BluetoothSocket`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值