【问题标题】:Android AsyncTask in another AsyncTask另一个 AsyncTask 中的 Android AsyncTask
【发布时间】:2016-04-07 08:06:54
【问题描述】:

我想用这段代码在另一个 AsyncTask 中运行一个 AsyncTask:

   protected Integer doInBackground(Void... params) {
    InetAddress inetAddress;
    try {
        while (true) {
            inetAddress = InetAddress.getByName("192.168.1.1");
            mSocket = new Socket(inetAddress, 4444);

            SocketData data = new SocketData();


            GetPacket pack = new GetPacket();
            AsyncTask<SocketData, Integer, Integer> running = pack.execute(data);

但有一个错误: 方法必须从主线程调用android当前推断线程是worker

【问题讨论】:

  • 你到底想做什么?为什么你不能在一个 AsyncTask 中完成所有你需要做的事情?

标签: java android multithreading android-asynctask


【解决方案1】:

做在onProgressUpdate这个方法在MainThread上运行

protected Integer doInBackground(Void... params) {
    publishProgress(data);
}

protected void onProgressUpdate(SocketData... data) {
    GetPacket pack = new GetPacket();
    AsyncTask<SocketData, Integer, Integer> running = pack.execute(data[0]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    相关资源
    最近更新 更多