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

时间:2016-04-29 09:23:53

标签: android android-activity service bluetooth sharedpreferences

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

这里我想连接到特定设备的MAC地址。我已设法通过共享首选项存储和检索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地址后启动服务,但我不知道到底要做什么。 任何形式的帮助表示赞赏。

2 个答案:

答案 0 :(得分: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);

请忘记unregister onDestroy Activity 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

BluetoothSocketpublic 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() {} } ,它连接到不同线程中的所需设备,并打开compile 'com.github.alamkanak:android-week-view:1.2.6' 进行通信。

$date1 = date_create("Fri, 22 Apr 2016 12:27:29 +0200");
$date2 = date_create("Fri, 29 Apr 2016 12:27:29 +0200");
$diff  = date_diff($date1, $date2);

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

答案 1 :(得分:-1)

Incident Identifier: XX CrashReporter Key: XX Hardware Model: iPhone8,1 Process: DJ Remake [4153] Path: /private/var/containers/Bundle/Application/567B8C2E-C288-454B-B11C-C35F93FB56DD/DJ Remake.app/DJ Remake Identifier: com.davidseek.dj-remake Version: 1 (1.0.2) Code Type: ARM-64 (Native) Parent Process: launchd [1] Date/Time: 2016-04-29 12:07:54.54 +0200 Launch Time: 2016-04-29 12:06:53.53 +0200 OS Version: iOS 9.3.1 (13E238) Report Version: 105 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Triggered by Thread: 0 Filtered syslog: None found Global Trace Buffer (reverse chronological seconds): 0.116172 CFNetwork 0x0000000181819f30 NSURLConnection finished with error - code -1001 60.589908 CFNetwork 0x0000000181729a44 TCP Conn 0x154699a70 SSL Handshake DONE 60.884066 CFNetwork 0x0000000181729954 TCP Conn 0x154699a70 starting SSL negotiation 60.884409 CFNetwork 0x00000001817cbda4 TCP Conn 0x154699a70 complete. fd: 9, err: 0 60.885311 CFNetwork 0x00000001817cd2d0 TCP Conn 0x154699a70 event 1. err: 0 61.043184 CFNetwork 0x00000001817cbda4 TCP Conn 0x1545a8190 complete. fd: 5, err: 0 61.043698 CFNetwork 0x00000001817cd2d0 TCP Conn 0x1545a8190 event 1. err: 0 之后,您可以开始服务。 Here获取数据并将数据发送到蓝牙设备所需的一切。