1

我正在编写一个使用两个线程的 Android 应用程序。一个是 UI 线程,另一个处理服务器通信。其他线程是否可以等待指定的时间,然后处理所有到达的消息,然后再次等待?

我需要这个,以便我可以收集不同的数据并在一个会话中将其发送到服务器。

我已经用 HandlerThread 构建了我的线程,但现在我被卡住了。谁能指出我正确的方向?

这是我在第二个线程中使用的代码:

public synchronized void waitUntilReady() {
        serverHandler = new Handler(getLooper()){

            public void handleMessage(Message msg) {  // msg queue
                switch(msg.what) {
                case TEST_MESSAGE:
                    testMessage(msg);
                    break;
                case UI_MESSAGE:
                    break;
                case SERVER_MESSAGE:
                    break;
                default:
                    System.out.println(msg.obj != null ? msg.obj.getClass().getName() : "is null");
                    break;
                 } 

            }


        };

}

编辑:

我通过使用 Thread 而不是 HandlerThread 并使用队列解决了我的问题。

我是编程新手,所以我为任何可怕的错误道歉,但这是我最终使用的代码。

public class ServiceThread extends Thread {

    // TODO maybe set the thread priority to background?
    static ServiceThread sThread = new ServiceThread();  // service thread instance
    private volatile Handler mainHandler;

    //
    public Thread mainThread;
    private boolean OK = true;
    public Queue<MessageService> msgQueue;
    private ThreadPoolExecutor exec;

    private ServiceThread() { }


    @Override
    public void run()  {
        synchronized (this){
            msgQueue = new ConcurrentLinkedQueue<MessageService>();
            notifyAll();
        }

        mainHandler = new Handler(Looper.getMainLooper());

        ThreadPoolExecutor exPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
        exec = exPool;      

        // MAIN LOOP
            try {

                while(OK) {

                    getMessagesFromQueue();
                    Thread.sleep(3000);

                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //end of loop

    }

public void ProcessMessage(MessageService message) {
System.err.println("ProcessMessage with command: " + message.command);
}           
    /** Called from the Main thread. Waits until msgQueue is instantiated and then passes the reference
     * @return Message Queue
     */
    public Queue<MessageService> sendQueue() {
        synchronized (this){
            while(msgQueue == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block  -- move the try block!
                    e.printStackTrace();
                }
            }
        }

        return msgQueue;
    }

    public void setOkFalse () {
        if (OK == true)
            OK = false;
    }

    // Message handling methods



    /** Priority message from UI thread, processed in another thread ASAP.
     * Should be used on commands like getBigPicture or getPics when cached pics are running out
     * or upload picture etc.
     * @param message - Message should always be MessageService class
     * TODO check that it really is.
     */
    public void prioTask (MessageService message) {
        final MessageService taskMsg = message;
        Runnable task = new Runnable() {
            @Override
            public void run(){

                ProcessMessage(taskMsg);    
            }
        };
        exec.execute(task);
    }

    /**
     * Gets messages from queue, puts them in the list, saves the number of messages retrieved
     * and sends them to MessageService.handler(int commands, list messageList) 
     *  (method parameters may change and probably will =) ) 
     */
    public void getMessagesFromQueue() {
        int commands = 0;
        ArrayList <MessageService> msgList = new ArrayList <MessageService>(); 
        while(!msgQueue.isEmpty()) {
            if(msgQueue.peek() instanceof MessageService) {
                //put into list?
                msgList.add(msgQueue.remove());
                commands++;

            } else {
                //Wrong type of message
                msgQueue.remove();
                System.err.println("getMessagesFromQueue: Message not" +
                        " instanceof MessageService, this shouldn't happen!");
            }
        }       
        if (commands > 0) {
            HTTPConnection conn;
            try {
                conn = new HTTPConnection();
                    MessageService.handleSend(commands, msgList, conn);
                    conn.disconnect();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } 
    }
}

PS这也是我在这里的第一篇文章。我应该标记它已解决还是什么?如何?

4

0 回答 0