Features of using Looper.prepare () in Android

I am having trouble understanding how to use the logic Looper prepare()/ loop()/ quit().

I have three streams: one is the user interface stream, one is the game logical stream, and the last is the network communication stream (background stream, lives only when used).

The game stream has many dependencies on the results of network calls, so I wanted to turn off the network stream from the game stream and return the Handlerresult.

Of course, since the UI thread is not involved, I need to call Looper.prepare()... somewhere. I thought that it should be called in the game stream, but I can not do this because it loop()takes it.

How can I go back to the game stream from the network stream using my handler?

+5
source share
2 answers

What happens when you call Looper.prepare () and then Looper.loop () in Thread, all that Thread ever does is serve a MessageQueue until someone calls quit () on Looper.

Another thing is that by default when creating an instance of Handler, the code will always be executed in the thread that was created on

What you need to do is create a new Thread and in run () call Looper.prepare (), configure any handlers, and then call Looper.loop ().

, , . , , AsyncTask.

public class NetworkThread extends Thread {
    private Handler mHandler;
    private Handler mCallback;
    private int QUIT = 0;
    private int DOWNLOAD_FILE = 1;
    public NetworkThread(Handler onDownloaded) {
        mCallback = onDownloaded;
    }

    public void run() {
        Looper.prepare();
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    // things that this thread should do
                    case QUIT:
                        Looper.myLooper().quit();
                        break;
                    case DOWNLOAD_FILE:
                        // download the file
                        mCallback.sendMessage(/*result is ready*/);
                }
            }
        }
        Looper.loop();
    }

    public void stopWorking() {
        // construct message to send to mHandler that causes it to call 
        // Looper.myLooper().quit
    }

    public void downloadFile(String url) {
        // construct a message to send to mHandler that will cause it to
        // download the file
    }
}
+7

, ? , , Looper.

ASyncTask , . , ProgressDialog OnPreExecute, onPostExecute.

, , .

0

All Articles