zoukankan      html  css  js  c++  java
  • android_handler(二)

    package cn.com.sxp;

    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ProgressBar;

    public class HandlerTwoActivity extends Activity {
    private ProgressBar progressBar;
    private Button startButton;
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    progressBar = (ProgressBar)findViewById(R.id.progressbar);
    startButton = (Button)findViewById(R.id.startButton);

    startButton.setOnClickListener(new buttonOnClickListener());
    }

    class buttonOnClickListener implements OnClickListener{
    public void onClick(View v) {
    // 点击一下进度条就可见
    progressBar.setVisibility(View.VISIBLE);
    updateBarHandler.post(updateThread);
    }
    }


    Handler updateBarHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
    progressBar.setProgress(msg.arg1);
    // 將要執行的線程放入隊列中
    updateBarHandler.post(updateThread);
    }
    };

    Runnable updateThread = new Runnable(){
    int counter = 0;
    public void run() {
    // TODO Auto-generated method stub
    Log.d("in updateThread run()","在updateThread run方法中");
    counter += 10;
    // 从系统处得到一个消息
    // Returns a new Message from the global message pool. More efficient than creating and allocating new instances. The retrieved message has its handler
    // set to this instance (Message.target == this). If you don't want that facility, just call Message.obtain() instead.
    Message msg = updateBarHandler.obtainMessage();
    //将Message对象的arg1参数的值设置为i
    // arg1 and arg2 are lower-cost alternatives to using setData() if you only need to store a few integer values.
    msg.arg1 = counter; //用arg1、arg2这两个成员变量传递消息,优点是系统性能消耗较少
    try {
    Thread.sleep(1000); //让当前线程休眠1000毫秒
    }catch(InterruptedException ex){
    ex.printStackTrace();
    }
    //将Message对象加入到消息队列当中
    updateBarHandler.sendMessage(msg);
    if (100 == counter){
    updateBarHandler.removeCallbacks(updateThread);
    }
    }
    };
    }

    运行效果如下:

    点击“点我”,日志打印如下:

    但是当我退出这个活动,这个线程还在输出,显然线程没有停止,因此这里必须得让handler清除队列中的消息。

  • 相关阅读:
    支持对所有文件格式的收集、同一画面编辑和关联等管理
    [转]养成好习惯是做好个人知识管理根本之道
    小心你的QQ聊天记录毁于一旦
    如果开源,服务又不一定找开发商,完全可以找更便宜就近的第三方
    不要使用没有升级保证的PKM软件
    针式PKM V5.78
    关于在英文Windows XP 企业版下运行出现乱码,甚至无法打开数据库的错误处理方法
    [收藏]你经常遇到如下困境吗
    个人资源管理的时代,已经到来,你意识到了吗?
    [转]针对文献管理软件Note谈我心目中的个人资源信息管理软件
  • 原文地址:https://www.cnblogs.com/itblog/p/2322813.html
Copyright © 2011-2022 走看看