我有一個(gè)連接到藍(lán)牙設(shè)備的代碼,打開一個(gè)與正在運(yùn)行的線程通信的藍(lán)牙套接字,該線程運(yùn)行在主要活動(dòng)中運(yùn)行的函數(shù)。我想將所有連接序列移動(dòng)到另一個(gè)活動(dòng),然后像現(xiàn)在一樣從主線程操作線程。問題是它們都是相連的。我希望可以選擇在這些活動(dòng)之間發(fā)送消息(意味著保持套接字從其他活動(dòng)運(yùn)行),即這條消息: mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name) .sendToTarget();因?yàn)椴豢赡茉诨顒?dòng)之間傳遞處理程序,我不知道如何/如果可能的話。做這樣的事情最好的方法是什么?添加了部分代碼。謝謝。 mHandler = new Handler(){ public void handleMessage(android.os.Message msg){ if(msg.what == MESSAGE_READ){ String readMessage = null; try { readMessage = new String((byte[]) msg.obj, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } RxMessage = readMessage.split(" "); if (sH.isStringInCorrectOrder(RxMessage,Weight)) populateListView(RxMessage); mReadBuffer.setText(readMessage); } if(msg.what == CONNECTING_STATUS){ if(msg.arg1 == 1) mBluetoothStatus.setText("Connected to Device: " + (String)(msg.obj)); else mBluetoothStatus.setText("Connection Failed"); } } };private void connectBT (){ mBluetoothStatus.setText("Connecting..."); // Get the device MAC address, which is the last 17 chars in the View final String address = "98:D3:31:30:39:75"; final String name = "HC-06"; // Spawn a new thread to avoid blocking the GUI one new Thread() { public void run() { boolean fail = false; BluetoothDevice device = mBTAdapter.getRemoteDevice(address); try { mBTSocket = createBluetoothSocket(device); } catch (IOException e) { fail = true; Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show(); }
1 回答
皈依舞
TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個(gè)贊
只需聲明mHandler為static,您就可以從所有其他活動(dòng)中訪問它。這會(huì)造成一個(gè)小的臨時(shí)內(nèi)存泄漏,但不要擔(dān)心。
添加回答
舉報(bào)
0/150
提交
取消
