Android中Handler的使用

package com.example.progressdialog;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
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 NotificationTest extends Activity {
    static final int PROGRESS_DIALOG = 0;
    Button button;
    ProgressThread progressThread;
    ProgressDialog progressDialog;
   
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Setup the button that starts the progress dialog
        button = (Button) findViewById(R.id.progressDialog);
        button.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                showDialog(PROGRESS_DIALOG);
            }
        }); 
    }
   
    protected Dialog onCreateDialog(int id) {
        switch(id) {
        case PROGRESS_DIALOG:
            progressDialog = new ProgressDialog(NotificationTest.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setMessage("Loading...");
            return progressDialog;
        default:
            return null;
        }
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch(id) {
        case PROGRESS_DIALOG:
            progressDialog.setProgress(0);
            progressThread = new ProgressThread(handler);
            progressThread.start();
    }

    // Define the Handler that receives messages from the thread and update the progress
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int total = msg.arg1;
            progressDialog.setProgress(total);
            if (total >= 100){
                dismissDialog(PROGRESS_DIALOG);
                progressThread.setState(ProgressThread.STATE_DONE);
            }
        }
    };

    /** Nested class that performs progress calculations (counting) */
    private class ProgressThread extends Thread {
        Handler mHandler;
        final static int STATE_DONE = 0;
        final static int STATE_RUNNING = 1;
        int mState;
        int total;
       
        ProgressThread(Handler h) {
            mHandler = h;
        }
       
        public void run() {
            mState = STATE_RUNNING;   
            total = 0;
            while (mState == STATE_RUNNING) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Log.e("ERROR", "Thread Interrupted");
                }
                Message msg = mHandler.obtainMessage();
                msg.arg1 = total;
                mHandler.sendMessage(msg);
                total++;
            }
        }
        
        /* sets the current state for the thread,
         * used to stop the thread */
        public void setState(int state) {
            mState = state;
        }
    }
}

Android Handler 主要用于在不同线程之间传递消息和任务。Handler 可以将消息或任务传递给 MessageQueue,然后在 Looper 循环执行。在 Android ,通常将 Handler 与子线程一起使用,以便在主线程之外执行某些操作。 下面是一个简单的示例,演示如何创建和使用 Handler: 1. 在主线程创建一个 Handler 对象: ``` Handler handler = new Handler(); ``` 2. 在子线程,可以通过 Handler 对象来发送消息或任务: ``` handler.post(new Runnable() { @Override public void run() { // 在这里执行任务 } }); ``` 3. 当任务执行完成后,可以通过 Handler 对象发送一个消息给主线程,以更新 UI 界面: ``` handler.post(new Runnable() { @Override public void run() { // 更新 UI 界面 } }); ``` 4. 如果需要延迟执行任务,可以使用 Handler 对象的 postDelayed() 方法: ``` handler.postDelayed(new Runnable() { @Override public void run() { // 在这里执行延迟任务 } }, 1000); ``` 在上面的示例,post() 方法和 postDelayed() 方法都可以将任务或消息发送到 Handler 对象所关联的 MessageQueue 。然后,Looper 循环会从 MessageQueue 读取任务或消息,并在指定的线程执行它们。 注意,如果 Handler 对象被创建在主线程,那么它会自动关联到主线程的 Looper 对象。因此,如果需要在子线程使用 Handler,必须先创建一个 Looper 对象,然后将它关联到子线程
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值