gpt4 book ai didi

android - 通过服务使用存储的 MAC 地址连接到蓝牙设备

转载 作者:行者123 更新时间:2023-12-05 07:49:49 26 4
gpt4 key购买 nike

我是 Android 新手,我想了解蓝牙连接的工作原理。为此,我使用了 wiced sense 应用程序来了解工作原理。

在这里,我想根据 MA​​C 地址连接到特定设备。我已经设法通过共享首选项存储和检索 MAC 地址。现在我想在没有用户交互的情况下连接到与 MAC 地址匹配的设备。

要存储 MAC 地址,我执行以下操作:

 public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;

if (convertView == null || convertView.findViewById(R.id.device_name) == null) {
convertView = mInflater.inflate(R.layout.devicepicker_listitem, null);
holder = new ViewHolder();
String DeviceName;

holder.device_name = (TextView) convertView.findViewById(R.id.device_name);
// DeviceName= String.valueOf((TextView) convertView.findViewById(R.id.device_name));
holder.device_addr = (TextView) convertView.findViewById(R.id.device_addr);
holder.device_rssi = (ProgressBar) convertView.findViewById(R.id.device_rssi);

convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

DeviceRecord rec = mDevices.get(position);
holder.device_rssi.setProgress(normaliseRssi(rec.rssi));
editor = PreferenceManager.getDefaultSharedPreferences(mContext);
String deviceName = rec.device.getName();
if (deviceName != null && deviceName.length() > 0) {
holder.device_name.setText(rec.device.getName());
holder.device_addr.setText(rec.device.getAddress());
//Log.i(TAG, "Service onStartCommand");
if(deviceName.equals("eVulate")&& !editor.contains("MAC_ID")) {
storeMacAddr(String.valueOf(rec.device.getAddress()));
}
} else {
holder.device_name.setText(rec.device.getAddress());
holder.device_addr.setText(mContext.getResources().getString(R.string.unknown_device));
}

return convertView;

public void storeMacAddr(String MacAddr) {

editor.edit().putString("MAC_ID", MacAddr).commit();
}
}

我通过以下代码检索相同的内容:

private void initDevicePicker() {           
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if(mSharedPreference.contains("MAC_ID")){
String value=(mSharedPreference.getString("MAC_ID", ""));
}
else
// search for devices
}

我想在检索到 MAC 地址后启动一项服务,但我不知 Prop 体在何处执行此操作。任何形式的帮助表示赞赏。

最佳答案

所有你有一些蓝牙设备的 MAC 地址,你想使用它们的 MAC 地址连接到它们。我认为您需要阅读有关蓝牙发现和连接的更多信息,但无论如何,我正在放置一些代码,这些代码可能会在您阅读有关 Android 蓝牙的内容后对您有所帮助。

在您的Activity 中,您需要注册一个BroadcastReceiver,以便识别蓝牙连接变化并开始发现附近的蓝牙设备。 BroadcastReceiver 看起来像这样

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {

} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

if (device.getAddress().equals(Constants.DEVICE_MAC_ADDRESS)) {
startCommunication(device);
}

} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {


} else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
// Your bluetooth device is connected to the Android bluetooth

} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
// Your device is disconnected. Try connecting again via startDiscovery
mBluetoothAdapter.startDiscovery();
}
}
};

里面有一个 startCommunication 函数,我稍后会在这个答案中发布它。现在您需要在您的 Activity 中注册此 BroadcastReceiver

在你的 onCreate 中像这样注册接收器

// Register bluetooth receiver
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);

不要忘记在ActivityonDestroy 函数中取消注册 接收器

unregisterReceiver(mReceiver);

现在在您的 Activity 中,您需要声明一个 BluetoothAdapter 来启动蓝牙发现和一个 BluetoothSocket 来建立蓝牙连接。所以你需要在你的 Activity 中添加这两个变量并相应地初始化它们。

// Declaration
public static BluetoothSocket mmSocket;
public static BluetoothAdapter mBluetoothAdapter;

...

// Inside `onCreate` initialize the bluetooth adapter and start discovering nearby BT devices
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.enable();
mBluetoothAdapter.startDiscovery();

现在开始执行 startCommunication 函数

void startCommunication(BluetoothDevice device) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ConnectThread mConnectThread = new ConnectThread(device);
mConnectThread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
ConnectThread mConnectThread = new ConnectThread(device);
mConnectThread.execute((Void) null);
}
}

ConnectThread 是一个 AsyncTask,它在不同的线程中连接到所需的设备,并打开一个 BluetoothSocket 进行通信。

public class ConnectThread extends AsyncTask<Void, Void, String> {

private BluetoothDevice btDevice;

public ConnectThread(BluetoothDevice device) {
this.btDevice = device;
}

@Override
protected String doInBackground(Void... params) {

try {
YourActivity.mmSocket = btDevice.createRfcommSocketToServiceRecord(Constants.MY_UUID);
YourActivity.mBluetoothAdapter.cancelDiscovery();
YourActivity.mmSocket.connect();

} catch (Exception e) {
e.printStackTrace();
return null;
}

return "";
}

@Override
protected void onPostExecute(final String result) {

if (result != null){/* Success */}
else {/* Connection Failed */}

}

@Override
protected void onCancelled() {}

}

这是您如何找到附近的蓝牙设备并使用之前存储的 MAC 地址连接到它们的方法。

关于android - 通过服务使用存储的 MAC 地址连接到蓝牙设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36934506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com