最近在做一個批量安裝卸載的管理器,在安裝的過程中要顯示安裝信息,比如說:"正在安裝XX1.apk 正在安裝XX2.apk“當然這個顯示是在對話框上面顯示的。怎麼做呢?實現是這樣的:
1、在Activity中重寫onCreateDialog(int id)方法;
2、使用Handler更新對話框的信息;
3、用線程監控安裝信息,將信息設置在Message中通過Handler發送。
具體實現請看代碼:
- package cn.tch.cdg;
-
- import Android.app.Activity;
- import android.app.AlertDialog;
- import android.app.Dialog;
- 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;
-
- public class CustomDialogActivity extends Activity {
-
- private static final int PROGRESS_DIALOG = 0;
- private Button btnShowDialog;
- private ProgressThread mProgressThread;
- private Dialog mDialog;
-
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- btnShowDialog = (Button) findViewById(R.id.progressDialog);
- btnShowDialog.setOnClickListener(new OnClickListener(){
- public void onClick(View v) {
- showDialog(PROGRESS_DIALOG);
- }
- });
- }
- protected Dialog onCreateDialog(int id) {
- switch(id) {
- case PROGRESS_DIALOG:
- mDialog = new AlertDialog.Builder(CustomDialogActivity.this).create();
- mDialog.setTitle("請稍候");
- ((AlertDialog) mDialog).setMessage("");
- mProgressThread = new ProgressThread(handler);
- mProgressThread.start();
- return mDialog;
- default:
- return null;
- }
- }
- final Handler handler = new Handler() {
- public void handleMessage(Message msg) {
- int total = msg.getData().getInt("total");
- String message = msg.getData().getString("message");
- ((AlertDialog) mDialog).setMessage(message);
- if (total >= 100){
- dismissDialog(PROGRESS_DIALOG);
- mProgressThread.setState(ProgressThread.STATE_DONE);
- }
- }
- };
-
- private class ProgressThread extends Thread {
- Handler mHandler;
- final static int STATE_DONE = 0;
- final static int STATE_RUNNING = 1;
- int mState;
- int mTotal;
- ProgressThread(Handler handler) {
- mHandler = handler;
- }
- public void run() {
- mState = STATE_RUNNING;
- mTotal = 0;
- while (mState == STATE_RUNNING) {
- Message msg = mHandler.obtainMessage();
- Bundle bundle = new Bundle();
- bundle.putInt("total", mTotal);
- bundle.putString("message", "正在安裝:"+mTotal); // 設置Message
- msg.setData(bundle);
- mHandler.sendMessage(msg);
- mTotal++;
-
- try {
- Thread.sleep(300);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public void setState(int state) {
- mState = state;
- }
- }
- }
- <?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"
- >
- <Button
- android:id="@+id/progressDialog"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="顯示對話框"/>
- </LinearLayout>