标签:
Handler是开发人员在面试过程中最常见的问题之一了,这篇文章将较为全面地对Handler进行解读,包括源码层,以及使用方法。
如果看完文章有疑问,欢迎在评论中一起探讨
基本内容包括:
看完文章之后,可以用这个图片进行复习。
public class MainActivity extends AppCompatActivity { private TextView mTextView; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; private String[] str = new String[]{"傲慢","偏见","僵尸"}; private int index = 0; MyRunnable myRunnable = new MyRunnable(); private class MyRunnable implements Runnable{ @Override public void run() { index = index % 3; mTextView.setText(str[index]); index ++; mHandler.postDelayed(myRunnable,1000); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.tv); mHandler.postDelayed(myRunnable,1000); } }
public class MainActivity extends AppCompatActivity { private TextView mTextView; Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { mTextView.setText(msg.obj+""+ "arg1="+msg.arg1 + " arg2="+msg.arg2); super.handleMessage(msg); } }; private class Person{ String name; int age; @Override public String toString() { return "name="+name+" age="+age; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.tv); new Thread(){ @Override public void run() { Message msg = new Message(); msg.arg1 = 1; msg.arg2 = 2; Person person = new Person(); person.name = "pig"; person.age = 10; msg.obj = person; mHandler.sendMessage(msg); } }.start(); } }
public class MainActivity extends AppCompatActivity { private TextView mTextView; Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { mTextView.setText(msg.obj+""+ "arg1="+msg.arg1 + " arg2="+msg.arg2); super.handleMessage(msg); } }; private class Person{ String name; int age; @Override public String toString() { return "name="+name+" age="+age; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.tv); new Thread(){ @Override public void run() { Message msg = mHandler.obtainMessage();//同样可以获取Message对象 msg.arg1 = 1; msg.arg2 = 2; Person person = new Person(); person.name = "pig"; person.age = 10; msg.obj = person; msg.sendToTarget(); } }.start(); } }
public class MainActivity extends AppCompatActivity { private TextView mTextView; Handler mHandler = new Handler(new Handler.Callback() { //传入CallBack对象,对于重载的返回值为bollean的handleMessage() //返回值为false,将先执行这个方法,再执行返回值为void的handleMessage()方法 //返回值为true,只执行这个方法 @Override public boolean handleMessage(Message msg) { Toast.makeText(MainActivity.this, "截获消息", Toast.LENGTH_SHORT).show(); return false; } }){ public void handleMessage(Message msg) { Toast.makeText(MainActivity.this, "发出消息", Toast.LENGTH_SHORT).show(); } }; private class Person{ String name; int age; @Override public String toString() { return "name="+name+" age="+age; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.tv); Button btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mHandler.sendEmptyMessage(0); } }); } }
public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process, // and keep track of what that identity token actually is. Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // identity of the thread wasn't corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycleUnchecked(); } }
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
public class MainActivity extends AppCompatActivity { private TextView mTextView; public Handler mHandler = new Handler(){//主线程中的Handler @Override public void handleMessage(Message msg) { Log.d("CurrentThread",Thread.currentThread()+"");//打印Thread 的ID } }; class MyThread extends Thread{ private Handler handler;//子线程中的Handler @Override public void run() { Looper.prepare();//获取Looper handler = new Handler(){ @Override public void handleMessage(Message msg) { Log.d("CurrentThread",Thread.currentThread()+""); } }; Looper.loop();//轮询消息队列 } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyThread thread= new MyThread(); thread.start(); try { thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } thread.handler.sendEmptyMessage(1); mHandler.sendEmptyMessage(1); } }
public class MainActivity extends AppCompatActivity { private TextView mTextView; public HandlerThread mHandlerThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mHandlerThread = new HandlerThread("handler thread"); mHandlerThread.start(); Handler handler = new Handler(mHandlerThread.getLooper()){//通过getLooper()获取Looper @Override public void handleMessage(Message msg) { Log.d("current thread","" + Thread.currentThread()); } }; handler.sendEmptyMessage(1); } }
public class MainActivity extends AppCompatActivity { public Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { Log.d("current thread", "" + Thread.currentThread()); Message message = new Message(); message.what = 1; handler.sendMessageDelayed(message,1000);//向子线程的Handler发送消息 } }; public HandlerThread mHandlerThread; public Handler handler; private Button btn1,btn2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn1 = (Button) findViewById(R.id.btn); btn2 = (Button) findViewById(R.id.btn2); mHandlerThread = new HandlerThread("handler thread");//指定HandlerThread的名字 mHandlerThread.start(); handler = new Handler(mHandlerThread.getLooper()){//通过getLooper()获取Looper @Override public void handleMessage(Message msg) { Log.d("current thread", "" + Thread.currentThread()); Message message = new Message(); mHandler.sendMessageDelayed(message,1000);//向主线程中的Handler发送消息 } }; btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handler.sendEmptyMessage(1);//开始发送消息 } }); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handler.removeMessages(1);//停止发送消息 } }); } }
public class MainActivity extends AppCompatActivity { TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.tv); new Thread(){ @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { mTextView.setText("更新UI"); } }); } }.start(); } }
public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }
public class MainActivity extends AppCompatActivity { TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.tv); new Thread(){ @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } mTextView.post(new Runnable() { @Override public void run() { mTextView.setText("更新UI"); } }); } }.start(); } }
public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.post(action); } // Assume that post will succeed later ViewRootImpl.getRunQueue().post(action); return true; }
public class MainActivity extends AppCompatActivity { TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.tv); new Thread(){ @Override public void run() { mTextView.setText("更新UI了"); } }.start(); } }结果:
public class MainActivity extends AppCompatActivity { TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.tv); new Thread(){ @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } mTextView.setText("更新UI了"); } }.start(); } }
mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
标签:
原文地址:http://blog.csdn.net/chen_lian_/article/details/51031331