handle 我理解的意思就是消息传递器,他可以实现更新ui和阻塞线程,发送消息等等,我注释掉的代码是异步任务处理,没注释的是利用handle控制ui的自增实现数字自增长和充电效果。
package com.example.handel;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public static final String TAG = "MainActivity";
private TextView text;
final static int Test = 1;
private TextView tvtext;
private int count = 0;
ProgressBar progressBar = null;
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.hello);
// new ActivityThread().start();
findViewById(R.id.start).setOnClickListener(this);
findViewById(R.id.stop).setOnClickListener(this);
findViewById(R.id.prgsta).setOnClickListener(this);
findViewById(R.id.prgstop).setOnClickListener(this);
progressBar = findViewById(R.id.prg);
tvtext = findViewById(R.id.tvcount);
}
// Handler handler = new Handler(){
// public void handleMessage(Message message){
// switch (message.what){
// case Test:
// text.setText("工作线程");
// break;
// }
// }
// };
Runnable mRunCount = new Runnable() {
@Override
public void run() {
tvtext.setText("count:"+String.valueOf(++count));
handler.postDelayed(mRunCount,1000);
}
};
Handler prgHandler = new Handler(){
public void handleMessage(Message message) {
Log.d("消息内容为",""+message.arg1);
progressBar.setProgress(message.arg1);
prgHandler.post(PrgThread);
if (message.arg1 >=100) {
removeCallbacks(PrgThread);
}
}
};
public void log(String str) {
Log.d(TAG,str);
}
Runnable PrgThread = new Runnable() {
int i =0;
@Override
public void run() {
i=i+10;
Message msg = prgHandler.obtainMessage();
msg.arg1 = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
prgHandler.sendMessage(msg);
}
};
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
handler.postDelayed(mRunCount,1000);
break;
case R.id.stop:
handler.removeCallbacks(mRunCount);
break;
case R.id.prgsta:
prgHandler.post(PrgThread);
break;
case R.id.prgstop:
prgHandler.removeCallbacks(PrgThread);
break;
}
}
// class ActivityThread extends Thread{
// public void run(){
// try {
// Thread.sleep(3000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// Message message = new Message();
// message.what = 1;
// handler.sendMessage(message);
// }
//
//
//
// }
}