Android中多线程下载
[java]
public class MainActivity extends Activity {
// 声明控件
// 路径与线程数量
private EditText et_url, et_num;
// 进度条
public static ProgressBar pb_thread;
// 显示进度的操作
private TextView tv_pb;
// 线程的数量
public static int threadNum = 3;
// 每个线程负责下载的大小
public int blockSize;
public static int threadCount;// 数量
// 访问的path
public String path;
public static boolean flag = true;
// 记录进度条的值
public static int pb_count = 0;
public static Handler handler;
public static final int TEXTVALUE = 1;
public static int pb_num = 0;
public static int size = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_url = (EditText) findViewById(R.id.et_path);
et_num = (EditText) findViewById(R.id.et_threadNum);
pb_thread = (ProgressBar) findViewById(R.id.pb_down);
tv_pb = (TextView) findViewById(R.id.tv_pb);
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case TEXTVALUE:
System.out.println("-----------------------"
+ MainActivity.pb_count + "//////"
+ MainActivity.size);
// 改变TEXTView
pb_num = (MainActivity.pb_count * 100) / MainActivity.size;
tv_pb.setText("当前进度是+" + pb_num + "%");
break;
default:
break;
}
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.down, menu);
return true;
}
//下载操作
public void downLoad(View v) {
// 改变变量值:
MainActivity.flag = true;
MainActivity.pb_count = 0;
path = et_url.getText().toString();
String threadNum_et = et_num.getText().toString();
if (TextUtils.isEmpty(path) || TextUtils.isEmpty(threadNum_et)) {
Toast.makeText(this, "不能为空", Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(this, "url:" + path + "--" + threadNum_et,
Toast.LENGTH_LONG).show();
// 转换成数字
threadNum = Integer.valueOf(threadNum_et);
new Thread(new Runnable() {
@Override
public void run() {
try {
// 创建出URL对象
URL url = new URL(path);
// 创建出 HttpURLConnection对象
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
 
补充:移动开发 , Android ,