首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步任务不是异步任务

异步任务不是异步任务
EN

Stack Overflow用户
提问于 2012-08-16 22:58:50
回答 1查看 132关注 0票数 0

我正在用Android开发一个聊天应用,遇到了一个很大的问题。我需要一个线程在后台持续运行(轮询服务器),并通过句柄将其附加到我的主进程。

主要的问题是:只要后台线程还在运行,前台线程就会完全停止!

下面是一段不完整的代码(因为完整版本要长得多/难看)……

代码语言:javascript
复制
public class ChatActivity extends Activity {
    ...

    private Thread chatUpdateTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        ...

        chatUpdateTask = new ChatUpdateTask(handler);
        chatUpdateTask.start();
    }

    public void updateChat(JSONObject json) {
        // ...
        // Updates the chat display
    }


    // Define the Handler that receives messages from the thread and update the progress
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            // Get json from the sent Message and display it
            updateChat(json);
        }
    };

    public class ChatUpdateTask extends Thread {
        Handler mHandler;   // for handling things outside of the thread.

        public ChatUpdateTask(Handler h) {
            mHandler = h;               // When creating, make sure we request one!
        }//myTask

        @Override
        public void start() {
            while(mState==STATE_RUNNING) {

                // ...
                // Send message to handler here

                Thread.sleep(500);  // pause on completion

            }//wend
        }//end start

        /* sets the current state for the thread,
         * used to stop the thread */
        public void setState(int state) {
            mState = state;
        }//end setState


        public JSONObject getChatMessages() {
            // ... call server, return messages (could take up to 50 seconds to execute; 
            // server only returns messages when there are new ones
            return json;
        }
    }//end class myTask


}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-16 23:04:36

您正在覆盖start()。线程在它们的run()方法中运行。

http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11990043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档