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

3

我是一名新手,正在学习Android并试图理解蓝牙连接的工作原理。为此,我使用了Wiced Sense应用程序来了解其工作方式。

在这里,我想根据MAC地址连接到特定的设备。我已经成功通过Shared Preferences存储和检索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地址后,我想启动一个服务,但不知道确切的位置。任何帮助都将不胜感激。


我看到了一个适合我情况的答案这里。如果有人能够提供更多细节,特别是关于MyApplication和Abstract类的,那将非常有帮助。 - ADI
2个回答

1
你拥有一些蓝牙设备的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的函数,我稍后会在答案中发布。现在你需要在你的活动中注册这个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地址找到附近的蓝牙设备并连接它们的方法。

谢谢您提供的信息。但是,我想在服务中包含蓝牙连接。我这样做是因为一旦应用程序断开连接,服务应该开始运行并搜索具有MAC地址的设备,然后连接到它(如果可用)。我如何在服务中实现上述代码? - ADI

-1

String value=(mSharedPreference.getString("MAC_ID", ""));之后,您可以启动服务。这里提供了获取数据并将数据发送到蓝牙设备所需的所有内容。


这个问题与BLE无关。请更新您的答案或将其删除。 - Reaz Murshed
@ReazMurshed 请阅读问题,它涉及蓝牙连接。 - Sanjay Kakadiya
我没有给你的答案点踩。无论如何,这个问题是关于蓝牙连接的 - 是的!蓝牙和BLE之间有基本的区别。请在回答SO上的问题时提供一些可行的代码。 - Reaz Murshed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接