Android Handler用法
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.util.Log; import com.wv1124.adnroid.R; public class HandleTestActivity extends Activity { Handler handler = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.d("DEBUG", "Activity-->" + Thread.currentThread().getId()); // 生成一个HandlerThread对象,为了使Handler在此线程中执行; HandlerThread handlerThread = new HandlerThread("handler_thread") { @Override public void run() { Log.d("DEBUG", "handlerThread-->" + Thread.currentThread().getId()); super.run(); // 注意,不要重写; } }; // 启动线程; handlerThread.start(); //Looper p = Looper.myLooper(); //也可以使用主线程的Looper但会使主线程停止执行等待; // handlerThread.getLooper()初始化Handler使Hander在handlerThread的程线中执行; handler = new Handler(handlerThread.getLooper()) { @Override public void handleMessage(Message msg) { Bundle b = msg.getData(); int age = b.getInt("age"); String name = b.getString("name"); Log.d("DEBUG", "Handler-->" + Thread.currentThread().getId() + " : age is " + age + ", name is" + name); } }; // 可以这样发消息; // Message msg = handler.obtainMessage(); // Bundle b = new Bundle(); // b.putInt("age", 20); // b.putString("name", "Jhon"); // msg.setData(b); // msg.sendToTarget(); // 工作线程; Thread t = new Thread() { private int i = 0; @Override public void run() { Log.d("DEBUG", "work Thread-->" + Thread.currentThread().getId() + " start;"); Message msg = new Message(); Bundle b = new Bundle(); b.putInt("age", i++); b.putString("name", "Jhon" + i++); msg.setData(b); handler.sendMessage(msg); // 发消息给Handler所在的线程; if (i < 3) { handler.postDelayed(this, 30000); // 重复定时任务; } Log.d("DEBUG", "work Thread-->" + Thread.currentThread().getId() + " exit;"); } // 注意此方法没有在Handler被调用,Handler直接调用run方法; public synchronized void start() { Log.d("DEBUG", "work Thread start()"); super.start(); } }; t.setName("work thread"); t.start(); // 主线程中调用start()方法; // // 定时器功能; // Thread t = new Thread() { // @Override // public void run() { // Log.d("DEBUG", "*"); // handler.postDelayed(this, 3000); // } // }; // t.start(); // Log.d("DEBUG", "t.start()"); } }
相关参考:
深入理解Android消息处理系统——Looper、Handler、Thread
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28