HandlerThread

HandlerThread is a thread with a message queue that incorporates a Thread, a Looper, and a MessageQueue.

HandlerThread handlerThread = new HandlerThread(“HandlerThread”);
handlerThread.start();
mHandler = new Handler(handlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) { super.handleMessage(msg);
// Process messages here
}
};

  1. Creation: The constructor for HandlerThread takes a mandatory name argument and an optional priority for the thread:
    **HandlerThread(String name)
    HandlerThread(String name, int priority)**
    The default priority is Pro cess.THREAD_PRIORITY_DEFAULT—the same priority as the UI thread—and can be lowered to Process.THREAD_PRIORITY_BACKGROUND to execute noncritical tasks

  2. Execution:A HandlerThread is always ready to receive messages when the Handler can be created, as getLooper blocks until the Looper is prepared

  3. Reset:The message queue can be reset so that no more of the queued messages will be processed, but the thread remains alive and can process new messages. The reset will remove all pending messages in the queue, but not affect a message that has been dispatched and is executing on the thread:
    **public void resetHandlerThread() {
    mHandler.removeCallbacksAndMessages(null);
    }**

  4. Termination: A HandlerThread is terminated either with quit or quitSafely.With quit, no further messages will be dispatched to the HandlerThread, whereas quitSafely ensures that messages that have passed the dispatch barrier are processed before the thread is terminated
    You can also send an interrupt to the HandlerThread to cancel the currently executing message:
    **public void stopHandlerThread(HandlerThread handlerThread) {
    handlerThread.quit();
    handlerThread.interrupt();
    }**

    A HandlerThread can also be terminated by sending a finalization task to the Han dler that quits the Looper, and consequently the HandlerThread:
    **handler.post(new Runnable() {
    @Override
    public void run() {
    Looper.myLooper().quit();
    }
    });**
    The finalization task ensures that this will be the last executed task on this thread, once it has been dispatched by the Looper. There is, however, no guarantee that other tasks will not move ahead of the finalization task by being posted to the front of the queue through Handler.postAtFrontOfQueue


public class SharedPreferencesActivity extends Activity {
    TextView mTextValue;
    //Show read value in a TextView.
    private Handler mUiHandler = new Handler() {
         @Override
        public void handleMessage(Message msg) { 
            super.handleMessage(msg);
            if (msg.what == 0) {
                Integer i = (Integer)msg.obj;
                mTextValue.setText(Integer.toString(i));
            }
        } 
    };

    private class SharedPreferenceThread extends HandlerThread {
        private static final String KEY = "key"; 
        private static final int READ = 1; 
        private static final int WRITE = 2;
        private Handler mHandler;

        public SharedPreferenceThread() {
            super("SharedPreferenceThread", Process.THREAD_PRIORITY_BACKGROUND);
            mPrefs = getSharedPreferences("LocalPrefs", MODE_PRIVATE);
        }

        @Override
        protected void onLooperPrepared() { 
            super.onLooperPrepared();
            mHandler = new Handler(getLooper()) {
                @Override
                public void handleMessage(Message msg) { 
                    switch(msg.what) {
                        case READ: 
                            mUiHandler.sendMessage(mUiHandler.obtainMessage(0,mPrefs.getInt(KEY, 
                                                    0)));
                            break;
                        case WRITE:
                            SharedPreferences.Editor editor = mPrefs.edit(); 
                            editor.putInt(KEY, (Integer)msg.obj); 
                            editor.commit();
                            break;
                    }
                }
            };
        }

        public void read() {
             mHandler.sendEmptyMessage(READ);
        }

        public void write(int i) {
            mHandler.sendMessage(Message.obtain(Message.obtain(mHandler,WRITE, i)));
        } 
    }

    private int mCount;
    private SharedPreferenceThread mThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        mTextValue = (TextView) findViewById(R.id.text_value);
         mThread = new SharedPreferenceThread(); mThread.start();
    }

    //Write dummy value from the UI thread.

    public void onButtonClickWrite(View v) { 
        mThread.write(mCount++);
    }

    //Initiate a read from the UI thread.

    public void onButtonClickRead(View v) { 
        mThread.read();
    }

    //Ensure that the background thread is terminated with the Activity.

    @Override
    protected void onDestroy() {
        super.onDestroy(); 
        mThread.quit();
    } 
}

public class ChainedNetworkActivity extends Activity { 
    private static final int DIALOG_LOADING = 0; 
    private static final int SHOW_LOADING = 1;
    private static final int DISMISS_LOADING = 2;
    Handler dialogHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
             super.handleMessage(msg);
            switch (msg.what) {
                case SHOW_LOADING: 
                    showDialog(DIALOG_LOADING); 
                    break;
                case DISMISS_LOADING: 
                    dismissDialog(DIALOG_LOADING);
            } 
        }
    };

    private class NetworkHandlerThread extends HandlerThread { 
        private static final int STATE_A = 1;
        private static final int STATE_B = 2;
        private Handler mHandler;
        public NetworkHandlerThread() {
            super("NetworkHandlerThread", Process.THREAD_PRIORITY_BACKGROUND);
        }

        @Override
        protected void onLooperPrepared() { 
            super.onLooperPrepared();
            mHandler = new Handler(getLooper()) {
                @Override
                public void handleMessage(Message msg) { 
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case STATE_A: 
                            dialogHandler.sendEmptyMessage(SHOW_LOADING); 
                            String result = networkOperation1();
                            if (result != null) {
                                    sendMessage(obtainMessage(STATE_B, result)); 
                            } else {
                                dialogHandler.sendEmptyMessage(DISMISS_LOADING);
                            }
                            break; 
                        case STATE_B:
                            networkOperation2((String) msg.obj);
                            dialogHandler.sendEmptyMessage(DISMISS_LOADING);
                            break;
                    }
                }
            };
            fetchDataFromNetwork();
        }

        private String networkOperation1() { 
            SystemClock.sleep(2000); // Dummy
        }

        private void networkOperation2(String data) {
            // Pass data to network, e.g. with HttpPost. 
            SystemClock.sleep(2000); // Dummy
        }

        // Publically exposed network operation      
        public void fetchDataFromNetwork() { 
            mHandler.sendEmptyMessage(STATE_A);
        } 
    }

    private NetworkHandlerThread mThread;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mThread = new NetworkHandlerThread(); mThread.start();
    }

    @Override
    protected Dialog onCreateDialog(int id) { 
        Dialog dialog = null;
        switch (id) {
            case DIALOG_LOADING:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Loading...");
                dialog = builder.create();
                break;
        }
        return dialog; 
    }

    //Ensure that the background thread is terminated with the Activity.
    @Override
    protected void onDestroy() { 
        super.onDestroy(); 
        mThread.quit();
    }
} 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章