Android Handler源码摘录[1]
private Handler mMainHandler; //声明 mMainHandler = new MainHandler(this, getMainLooper());//初始化 private static class MainHandler extends Handler { final WeakReference<CameraActivity> mActivity; public MainHandler(CameraActivity activity, Looper looper) { super(looper); mActivity = new WeakReference<CameraActivity>(activity); } @Override public void handleMessage(Message msg) { CameraActivity activity = mActivity.get(); if (activity == null) { return; } switch (msg.what) { // do somethings } } } 使用一: mMainHandler.post(new Runnable(){ @Override public void run(){ // do somethings } }); 使用二: mMainHandler.removeMessages(MSG_XX); //Remove meesage mMainHandler.sendEmptyMessageDelayed(MSG_XX, delayTimes); 使用三: mMainHandler.removeCallbacks(mMyRunnable); //Remove Callbacks runable mMainHandler.postDelayed(mMyRunnable, DELAY_MS);
回调方式
final Handler mHandler; final Handler.Callback mCallback; private final Object mLock = new Object(); mCallback = new MyCallback(); mHandler = new Handler(context.getMainLooper(), mCallback); //方式二 HandlerThread thread = new HandlerThread(TAG); thread.start(); mHandler = new Handler(thread.getLooper(), mCallback); private final class MyCallback implements Handler.Callback { public static final int MSG_SET_STATE = 1; @Override public boolean handleMessage(Message message) { switch (message.what) { case MSG_SET_STATE: { // See comment at mClient final int state = message.arg1; message.recycle(); synchronized (mLock) { //do somethings } } break; } return true; } } mHandler.obtainMessage(msg_code).sendToTarget();
版权声明:如无特殊标注,文章均为本站原创,转载时请以链接形式注明文章出处。
评论