今天在做http网络事件的响应网络接收处理一般不能放在主线程中使用,目前也只会使用AsyncTask进行处理!之前虽然写过handler处理的一些文章但是发现全不会了!无奈~
关于handler某位兄弟已经整理的很透彻了!现在引用下原话如下:
Handler监听者框架:子线程是事件源,主线程是监听者。
Handler作为子线程的监听器出现:主线程中生成Handler的子类,并重写handleMessage(Message msg) 方法,用来对子线程响应。子线程调用Hanlder的sendMessage(message)发送事件。
import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.util.Log; import android.widget.TextView; public class MainActivity extends Activity { private final static String TAG = "ThreadTest"; TextView myTv = null; int i = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myTv = (TextView) this.findViewById(R.id.tv1); // 执行该线程 new Thread(runnable).start(); } /** * 主线程监听者 */ Handler myHandler = new Handler() { public void handleMessage(android.os.Message msg) { Log.i(TAG, "begin--->handleMessage"); if (msg.what == 0x000001) { myTv.setText(String.valueOf(i)); } Log.i(TAG, "end--->handleMessage"); super.handleMessage(msg); }; }; /** * 子线程事件源 */ Runnable runnable = new Runnable() { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { i++; Message msg = new Message(); msg.what = 0x000001; Log.i(TAG, "begin--->sendMessage"); myHandler.sendMessage(msg); Log.i(TAG, "end--->sendMessage"); Log.i(TAG, "begin--->dosomething"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Log.i(TAG, "end--->dosomething"); } } }; }
打印下输出:发现它并不是等dosomething执行完毕之后再调用handlemessage事件,而是一旦调用sendmessage后就会执行handlemessage。
Handler钩子方式:在主线程中生成一个Hanlder,用Handler的Post(Runnable)方法可以将Runnable钩到主线程中运行。
import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.widget.TextView; public class MainActivity extends Activity { private final static String TAG = "ThreadTest"; TextView myTv = null; //handler在主线程中创建,调用post的时候钩子会把它钩回主线程 Handler myHandler = new Handler(); int i = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myTv = (TextView) this.findViewById(R.id.tv1); new Thread(runnable1).start(); } /** * 子线程 */ Runnable runnable1 = new Runnable() { @Override public void run() { while (true) { i++; myHandler.post(runnable2); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }; /** * 使用钩子将该子线程钩到主线程中 */ Runnable runnable2 = new Runnable() { @Override public void run() { myTv.setText(String.valueOf(i)); } }; }