Handler

Handler主要用于接受子线程发送的数据, 并用此数据配合主线程更新UI,因为更新UI只能在主线程中进行。

Handler作为线程通讯工具类。用于传递消息。它有两个队列:

  • 消息队列使用sendMessage和HandleMessage的组合来发送和处理消息。
  • 线程队列类似一段代码,或者说一个方法的委托,用户传递方法。使用post,postDelayed 添加委托,使用 removeCallbacks移除委托。

下例给出两个个简单用法:

  • 采用Thread:
复制代码
public class MainActivity extends Activity {
    private TextView mTextView;
    
    private Handler handler = new Handler() {
         
        @Override
        public void handleMessage(Message msg) {
            // 接收消息并且去更新UI线程上的控件内容
            if (msg.what == 0) {
                mTextView.setText(String.valueOf(msg.obj));
            }
            super.handleMessage(msg);
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mTextView = (TextView) findViewById(R.id.text);
        
        new Thread() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 100; i++) {
                        Thread.sleep(500);
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = "更新后的值:" + i;
                        handler.sendMessage(msg);//向主线程的handler发消息
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
复制代码
  •  采用runable 和 postDealy:
复制代码
public class MainActivity extends Activity {
    private static final String TAG_ACTIVITY = "MainActivity";
    private static int tick = 0;
    private TextView mTextView;
    private Button mbutton;
    
    private Handler handler = new Handler() {
         
        @Override
        public void handleMessage(Message msg) {
            // 接收消息并且去更新UI线程上的控件内容
            super.handleMessage(msg);
            if (msg.arg1 == 0) {
                mTextView.setText(String.valueOf(msg.obj));
            }
            
            //重新把线程加入线程队列,延迟1000ms
            handler.postDelayed(updateThread,1000);
        }
    };
    
    Runnable updateThread = new Runnable(){
        
        @Override
        public void run() {
              
            Message msg = handler.obtainMessage();
            msg.arg1 = 0;
            msg.obj = "更新后的值" + tick++;
                      
            if(10 == tick){
                //移除该线程
                handler.removeCallbacks(updateThread);
                return;
            }
            
            handler.sendMessage(msg);//向主线程的handler发消息
            Log.i(TAG_ACTIVITY, String.valueOf(msg.obj)); 
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mTextView = (TextView) findViewById(R.id.text);
        mbutton   = (Button) findViewById(R.id.button1);
        
        mbutton.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                 //把线程加入线程队列
                 handler.post(updateThread);                
            }
        });
    }
}
复制代码

 

posted @   Fredric_2013  阅读(177)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示