代码改变世界

线程通信之handle用法

2014-12-03 14:23  我的梦想fly  阅读(174)  评论(0编辑  收藏  举报

主显示布局以及代码:

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <Button 
        android:id="@+id/btDownload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点击下载"
        />
    <ProgressBar 
        android:id="@+id/pbDownload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="2"
        style="@android:style/Widget.ProgressBar.Horizontal"
        />
<TextView 
   android:id="@+id/tvDownload"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="0%"/>

</LinearLayout>

java代码:

package com.litsoft.main;


import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

private ProgressBar pbDownload;
private TextView tvDownload;
private Handler handler;

private final static int START_DOWNING = 0;
private final static int FINISH_DOWNING = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initHandler();
setListener();
}





private void setListener() {
// TODO Auto-generated method stub
findViewById(R.id.btDownload).setOnClickListener(new OnClickListener() {

@Override
public void onClick(View view) {
// TODO Auto-generated method stub
new Thread(){


@Override
public void run() {
// TODO Auto-generated method stub
for (int i=0;i<=100;i++){
SystemClock.sleep(200);
Message message = Message.obtain();
message.what = START_DOWNING;
message.arg1 = i;
pbDownload.setProgress(i);
handler.sendMessage(message);
}
Message message = Message.obtain();
message.what = FINISH_DOWNING;
handler.sendMessage(message);
}

}.start();
}
});
}






private void initView() {
// TODO Auto-generated method stub
pbDownload = (ProgressBar) findViewById(R.id.pbDownload);
tvDownload = (TextView) findViewById(R.id.tvDownload);
}


private void initHandler() {
// TODO Auto-generated method stub
handler = new Handler(){


@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
switch (msg.what) {
case START_DOWNING:
tvDownload.setText(msg.arg1+"%");
break;
case FINISH_DOWNING:
Toast.makeText(MainActivity.this, "下载完成",20000).show();
break;
}

}

};
}
}

效果: