首页 > 代码库 > Android Handler简单示例
Android Handler简单示例
package com.firstapp.foo.firstapp;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import java.util.Date;public class ThreadDemoActivity extends AppCompatActivity { private static final String TAG = "foo"; private ProgressBar bar; private Button btnStartThread; private TextView tvMsg; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handler = new MyHandler(); setContentView(R.layout.activity_thread_demo); bar = (ProgressBar)findViewById(R.id.progressBar); btnStartThread = (Button)findViewById(R.id.btnStartThread); tvMsg = (TextView)findViewById(R.id.tvMsg); btnStartThread.setOnClickListener(v -> { new Thread(()->{ for (int i=0; i< 100; i++){ bar.setProgress(i); try { Thread.sleep(30); } catch (InterruptedException e) { e.printStackTrace(); } Log.i(TAG, "Thread Info:" + i); } Bundle bundle = new Bundle(); bundle.putString("msg","你好"); // other ... Message message = handler.obtainMessage(); message.what = 2; message.setData(bundle); handler.sendMessage(message); /* 若消息除消息码外,无附加参数,则下面一句更简便 */ //handler.sendEmptyMessage(2); }).start(); }); } class MyHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what){ case 2: Bundle data = msg.getData(); String txt = data.getString("msg"); tvMsg.setText(txt + ", 线程完成:" + new Date().toString() ); break; } } }}
Android Handler简单示例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。