0

私はAndroidでチャットアプリケーションを開発していますが、大きな問題が発生しました。常にバックグラウンドで実行する(サーバーをポーリングする)スレッドが必要であり、ハンドルを介してメインプロセスにアタッチしています。

主な問題は次のとおりです。このバックグラウンドスレッドが実行されている限り、フォアグラウンドスレッドは完全に停止します。

これは不完全なコードのチャンクです(フルバージョンははるかに長い/醜いため)...

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


}
4

1 に答える 1

6

オーバーライドしていますstart()。スレッドはそのrun()メソッドで実行されます。

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

于 2012-08-16T15:04:35.943 に答える