当前位置: 代码迷 >> Android >> Android多线程与同步- 札记 1
  详细解决方案

Android多线程与同步- 札记 1

热度:38   发布时间:2016-05-01 20:56:48.0
Android多线程与同步- 笔记 1

Android 的UItoolkit只能在UI线程即主线程被调用,否则会导致CalledFromWrongThreadException。

可以使用AsyncTask来进行一个后台操作(doInBackground),然后在UI线程公开结果,例如在onPostExecute,onProgressUpdate…。

当需要post一个runnable给非主线程时,Android为线程间交互提供了Handler和Looper。Looper线程和HandlerThread类结合使用,可以容易的避免潜在的竞争情况。

importandroid.os.Handler;

importandroid.os.HandlerThread;

importandroid.os.Looper;

importandroid.os.Message;

 

public classMineHandlerThread extends HandlerThread {

 

    private Handler handler;

 

    public MineHandlerThread(String name) {

        super(name);

    }

 

    public Handler getHandler() {

        return handler;

    }

 

    @Override

    public void start() {

        super.start();

        Looper looper = getLooper(); // willblock until thread’s Looper object is initialized.

        handler = new Handler(looper) {

            @Override

            public void handleMessage(Messagemsg) {

                switch (msg.what) {

                // process messages here

                }

            }

        };

    }

}

然后可以

        MineHandlerThread thread= new MineHandlerThread("looper thread");

        thread.start();

 

        Handler handler =thread.getHandler();

        // careful: this couldreturn null if the handler is not initialized

        // yet!

        // to post a runnable

        handler.post(newRunnable() {

            public void run() {

               Log.i("Mine", "Thread? " + Thread.currentThread().getName());

            }

        });

 

        int what = 0;

        int arg1 = 1;

        int arg2 = 2;

        Message msg =Message.obtain(handler, what, arg1, arg2);

        handler.sendMessage(msg);

 

        what = 1;

        msg = Message.obtain(handler,what, new Long(Thread.currentThread().getId()));

       handler.sendMessageAtFrontOfQueue(msg);


  相关解决方案