1、修改main.xml文件
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:Android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <ProgressBar
- style="?android:attr/progressBarStyleHorizontal"
- android:id="@+id/progressBar1"
- android:max="100"
- android:progress="0"
- android:secondaryProgress="0"
- android:visibility="visible"
- android:layout_height="wrap_content"
- android:layout_width="match_parent"></ProgressBar>
- </LinearLayout>
2、聲明子線程SonThread.java
- package com.bison;
-
- import android.os.Message;
-
- public class SonThread extends Thread {
- private int i = 0;
-
- @Override
- public void run() {
- while (i < 100) {
- i = i + 10;
- Message msg = new Message();
- msg.arg1 = i;
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- HandlerTestActivity.myHandler.sendMessage(msg);
-
- }
- if (i == 100) {
- HandlerTestActivity.myHandler.removeCallbacks(this);
- }
- }
- }
3、MainActivity代碼
- package com.bison;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.widget.ProgressBar;
-
- public class HandlerTestActivity extends Activity {
- private ProgressBar progressBar;
- private SonThread myThread;
-
- public static Handler myHandler;
-
- public void init() {
- progressBar = (ProgressBar) findViewById(R.id.progressBar1);
- myThread = new SonThread();
- myThread.start();
- myHandler = new Handler() {
-
- @Override
- public void handleMessage(Message msg) {
-
- super.handleMessage(msg);
- progressBar.setProgress(msg.arg1);
- }
- };
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- init();
- }
-
- }
PS:沒有打上注釋,不過Handler的通信機制還是比較好理解的。
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11