Android中Handler小例子

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

     在Android中,如果你的应用有一段时间响应不够灵敏,系统会向用户显示一个称作为应用程序无响应(ANR:Application Not Responding)对话框。用户可以选择“等待”而让程序继续运行,也可以选择“强制关闭”。一个合理的APP中不能也不应该出现ANR。导致原因就是安卓UI主线程中不能进行耗时操作(网络请求,文件下载等),比如在android中Activity的最长执行时间是5秒,BroadcastReceiver的最长执行时间则是10秒,否则ANR就会不期而遇。这时我们就要用到异步处理工具。Handler主要是按计划发送消息或执行某个Runnanble,从非UI线程中发送来的消息放入消息队列中,然后通过处理消息更新UI线程)。

例子1,用Handler来更新UI线程:


public class HandlerActivity extends Activity {
public static final int HANDLER_MESSAGE = 1;
private TextView mContentTv;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case HANDLER_MESSAGE:
mContentTv.setText("此时更新了数据");
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContentTv=(TextView) findViewById(R.id.t_title);
}
class myThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
Message message = new Message();
message.what = HANDLER_MESSAGE;
mHandler.sendMessage(message);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}


例子1,用Handler来完成定时(周期性)操作(当然可以用Timer,TimerTask及Android自带的AlarmManage):

public class HandlerActivity extends Activity {
private TextView mContentTv;
private Handler handler = new Handler();
private int mCounter = 0;
private Runnable mRunnable = new Runnable() {
public void run() {
handler.postDelayed(this, 5000);// 5秒后操作
mCounter++;
mContentTv.setText("Count: " + mCounter);


}
};


@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContentTv = (TextView) findViewById(R.id.t_title);
handler.post(mRunnable);
}
}