亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從其他活動向 Handler 發送消息

從其他活動向 Handler 發送消息

精慕HU 2023-05-17 14:48:42
我有一個連接到藍牙設備的代碼,打開一個與正在運行的線程通信的藍牙套接字,該線程運行在主要活動中運行的函數。我想將所有連接序列移動到另一個活動,然后像現在一樣從主線程操作線程。問題是它們都是相連的。我希望可以選擇在這些活動之間發送消息(意味著保持套接字從其他活動運行),即這條消息: mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name) .sendToTarget();因為不可能在活動之間傳遞處理程序,我不知道如何/如果可能的話。做這樣的事情最好的方法是什么?添加了部分代碼。謝謝。 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貢獻1851條經驗 獲得超3個贊

只需聲明mHandlerstatic,您就可以從所有其他活動中訪問它。這會造成一個小的臨時內存泄漏,但不要擔心。



查看完整回答
反對 回復 2023-05-17
  • 1 回答
  • 0 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號