1. 消息队列 Handler
2. Handler的消息传递机制
arg1\arg2传递int类型的值 obj传递对象
3. Handler的编程接口
4. Handler编程思路
1\主线程Activity创建Handler
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0x0001:
int index = msg.arg1;
test.setText(index+"");
break;
}
}
};
2\实现子线程run()方法重写
public void login(View view){
new Thread(){
@Override
public void run() {
for(int i=0;i<100;i++){
Message msg = new Message();
msg.what = 0X0001;
msg.arg1 = i;
handler.sendMessage(msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
---------------------------------------------------------------------------------------------------------------------------------
5. AsyncTask异步类
6. AsyncTask编程思路
1\创建方法继承AsyncTask,主线程中直接调用该方法即可实现
class MyTask extends AsyncTask<Void, Integer, Void>{
@Override
protected Void doInBackground(Void... voids) {
for(int i=0;i<=100;i++){
publishProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
int num = values[0];
test.setText("num:"+num);
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Void unused) {
Toast.makeText(MainActivity.this,"子线程运行结束",Toast.LENGTH_LONG).show();
super.onPostExecute(unused);
}
}
|