Android多線程的簡單使用

1.何時使用多線程?(耗時操作,避免主線程阻塞)

當我們進行IO操作,如文件操作,網絡操作,數據庫操作,以及一些複雜運算和開發定時功能,這時就需要用到多線程編程了。

2.如何使用?

接下來做一個定時功能的小Demo,

首先新建一個android project ,寫一個主佈局文件:main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下面是利用多線程和handler寫的一個簡易計時器:" />

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:gravity="center"
        android:text="00:00"
        android:textColor="@android:color/holo_orange_light"
        android:textSize="25sp" />

   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_start"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="開始" />

        <Button
            android:id="@+id/btn_reset"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="重置" />
    </LinearLayout>

</LinearLayout>

然後在MainActivity 初始化控件和設置按鈕監聽事件:


package comzero.threaddemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author dh
 * 
 */
public class MainActivity extends Activity implements OnClickListener {

	// 定義控件
	private Button btn_start;
	private Button btn_reset;
	private TextView tv_time;

	// 判斷是否正在計時
	public boolean IsStart = false;

	// 走過的總秒數
	public static int TOTAL = 0;

	// 定義唯一時間句柄標識
	public static final int TIME_HANDLER = 0x11;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == TIME_HANDLER) {
				// 接受到,主界面修改顯示時間
				int totals = (Integer) msg.obj;
				tv_time.setText(ToTime(totals));
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initView();
		//記得設置監聽事件
		btn_start.setOnClickListener(this);
		btn_reset.setOnClickListener(this);
	}

	// 初始化控件
	private void initView() {
		btn_start = (Button) findViewById(R.id.btn_start);
		btn_reset = (Button) findViewById(R.id.btn_reset);
		tv_time = (TextView) findViewById(R.id.tv_time);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		// 點擊開始
		case R.id.btn_start:
			if (!IsStart) {
				new TimeThread(handler).start();
				IsStart = true;
			} else {
				Toast.makeText(this, "你已經開始計時了!", Toast.LENGTH_LONG).show();
			}
			break;

		// 點擊重置
		case R.id.btn_reset:
			TOTAL = 0;
			break;
		default:
			break;
		}
	}

	// 把總秒數轉換成00:00格式的string
	private String ToTime(int time) {
		String str = "";
		int second = 0;
		int minute = 0;
		second = time % 60;
		minute = time / 60;
		if (minute < 10) {
			if (second < 10) {
				str = "0" + minute + ":" + "0" + second;
			} else {
				str = "0" + minute + ":" + second;
			}
		} else {
			if (second < 10) {
				str = minute + ":" + "0" + second;
			} else {
				str = minute + ":" + second;
			}
		}
		return str;
	}
}
新建一個TimeThread.java來寫計時功能:

package comzero.threaddemo;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class TimeThread extends Thread {
	private Handler handler ;
	
	public TimeThread(Handler handler){
		this.handler = handler;
	}
	
	@Override
	public void run() {
		// 計時功能,上限1個小時
		try {
			for (int i = 0; i < 3600; i++) {
				Thread.sleep(1000);
				MainActivity.TOTAL++;
				
				//這裏類似windows的消息機制,發一個消息到UI線程的消息隊列中
				Message msg = new Message();
				msg.what = MainActivity.TIME_HANDLER;
				msg.obj = MainActivity.TOTAL;
				handler.sendMessage(msg);
			}

		} catch (InterruptedException e) {
			Log.d("OK", e.toString());
		}
	}
}
這樣簡單的計時器就完成了,對於handler與Messge有時間再寫詳細的解釋,一下是運行圖

     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章