gpt4 book ai didi

android - 与 AsyncTask 线程通信?处理程序不工作?

转载 作者:太空狗 更新时间:2023-10-29 13:39:45 27 4
gpt4 key购买 nike

我有我的主 UI,并且有一个 AsyncTask 正在运行。我想与 AsyncTask 通信,让它在非 UI 线程上运行一些东西。所以我尝试做的是:

protected class WifiMon extends AsyncTask<Context, Integer, String>
{
Context parent;
CoexiSyst coexisyst;
private static final String WIMON_TAG = "WiFiMonitor";
private int PCAP_HDR_SIZE = 16;
private int _scan_pkts_left;

public Handler _handler = new Handler() {
@Override
public void handleMessage(Message msg) {

// We invoke a scan, and then read in all of the packets
// captured from the scan.
if(msg.obj == ThreadMessages.WIFI_SCAN_START) {
Log.d(TAG, "Got message to start Wifi scan");
int start_rxpkts = getRxPacketCount();
runCommand("/data/data/com.gnychis.coexisyst/files/iw dev wlan0 scan");
_scan_pkts_left = getRxPacketCount() - start_rxpkts;
Log.d(TAG, "Finished Wifi scan");
}
}
};
...
}

但是,似乎当收到传入消息时,handleMessage() 实际上在 UI 线程中运行。我知道这是因为 runCommand() 阻塞了 5 秒,而我的 UI 最终无响应了 5 秒。

为什么 handleMessage() 不在非 UI 线程上运行?线程之间是否还有其他首选通信方式?

最佳答案

doInBackground() 方法中创建处理程序对象。
或者
如果它独立于 Aysnctask,您可以将处理程序放在单独的线程中。

编辑:

mHandlerThread = new HandlerThread("some_name");
mHandlerThread.start();

/* we need to wait to get the looper instance */
while(!mHandlerThread.isAlive()) {};
mHandler = new Handler(mHandlerThread.getLooper(), null);

关于android - 与 AsyncTask 线程通信?处理程序不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7225893/

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