主要方法
- post(Runnable)
- postAtTime(Runnable,long)
- postDelayed(Runnable,long)
- sendEmptyMessage(int)
- sendMessage(Message)
- sendMessageAtTime(Message,long)
- sendMessageDelayed(Message,long)
页面布局
添加一个进度条和按钮模拟文件下载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_height="match_parent" android:id="@+id/linear1" android:layout_width="match_parent" android:orientation="vertical" android:gravity="center_horizontal" xmlns:android="http://schemas.android.com/apk/res/android"> <ProgressBar android:id="@+id/progress" style="@style/Widget.AppCompat.ProgressBar.Horizontal" android:progress="0" android:layout_width="match_parent" android:layout_height="wrap_content"/> <Button android:text="下载" android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
|
程序设计
创建Handler对象,并重写它的handleMessage方法
1 2 3 4 5 6 7 8 9
| Handler handler = new Handler(){ @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg);
progress.setProgress(msg.arg1); } };
|
在方法中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 100;i++){
Message message = new Message();
message.arg1 = i+1;
handler.sendMessage(message); try {
Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start();
|