有些地方需要用到像下载时用到的进度条,我这里简单的做了个demo。

布局文件activity_main.xml如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp">
<Button
android:id="@+id/btnAddPro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加进程"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/llPro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"/>
</ScrollView>
</LinearLayout>

接着就是往llPro中添加view,view的布局unit_process.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">

<TextView
android:id="@+id/tv_rate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="@+id/tv_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

<ProgressBar
android:id="@+id/down_pb"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100" />
</LinearLayout>

代码实现:
package com.lml.process;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

Button btnAdd;
LinearLayout llPro;
private int num=0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llPro=(LinearLayout)findViewById(R.id.llPro);

btnAdd=(Button)findViewById(R.id.btnAddPro);

btnAdd.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
final View view = inflater.inflate(R.layout.unit_process, null);
llPro.addView(view);
String source = "http://image.baidu.com/i?tn=download&ipn=dwnl&word=%E5%9B%BE%E7%89%87%E4%B8%8B%E8%BD%BD&ie=utf-8&fr=result&url=http%3A%2F%2Fimg2.pcpop.com%2FArticleImages%2F0x0%2F1%2F1061%2F001061672.jpg";
AsyTask at=new AsyTask(MainActivity.this,view,source);
at.execute();
}
});


}

private Handler handler = new Handler() {
ProgressBar pb;
TextView tv_rate,tv_name;
@Override
public void handleMessage(Message msg) {
// 定义一个Handler,用于处理下载线程与UI间通讯
if (!Thread.currentThread().isInterrupted()) {
Object[] data= (Object[])(msg.obj);
View view =(View) data[0];
switch (msg.what) {
case 0:
pb=(ProgressBar)view.findViewById(R.id.down_pb);
tv_name=(TextView)view.findViewById(R.id.tv_name);

pb.setMax((Integer)data[1]);
tv_name.setText((String)data[2]);
break;
case 1:
pb=(ProgressBar)view.findViewById(R.id.down_pb);
tv_rate=(TextView)view.findViewById(R.id.tv_rate);

pb.setProgress((Integer)data[2]);
int result = (Integer)data[2] * 100 /(Integer) data[1];
tv_rate.setText(result + "%");
break;
case 2:
Toast.makeText(MainActivity.this, "文件下载完成", Toast.LENGTH_SHORT).show();
break;

case -1:
String error = msg.getData().getString("error");
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
break;
}
}
super.handleMessage(msg);
}
};

public boolean downFile(String url, String path , View view) throws IOException {
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();

URL absUrl = conn.getURL();// 获得真实Url
String filename = conn.getHeaderField("Content-Disposition");
if (filename == null || filename.length() < 1) {
filename = absUrl.getFile();
}


int fileSize = conn.getContentLength();// 根据响应获取文件大小
if (fileSize <= 0)
return false;
if (is == null)
return false;

File dir=new File(path+"/Mytext");
dir.mkdirs();
File file=new File(dir.getAbsolutePath(),"lml"+(num++)+".jpg");
if(file.exists()){
file.delete();
}
file.createNewFile();

FileOutputStream fos = new FileOutputStream(file);

byte buf[] = new byte[1024];
int downLoadFileSize = 0;
Object[] data0=new Object[]{view,fileSize,filename };
sendMsg(0,data0);
do {
// 循环读取
int numread = is.read(buf);
if (numread == -1) {
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread;

Object[] data1=new Object[]{view,fileSize,downLoadFileSize };
sendMsg(1,data1);// 更新进度条
} while (true);

Object[] data1=new Object[]{view};
sendMsg(2,data1);// 通知下载完成
try {
is.close();
fos.close();
} catch (Exception ex) {
return false;
}
return true;
}

private void sendMsg(int flag,Object[] data) {
Message msg = Message.obtain(handler,flag, 0, 0,data);
handler.sendMessage(msg);
}

class AsyTask extends AsyncTask<String, Integer, Boolean> {

Context mContext;
View view;
String source;

public AsyTask(Context context,View view,String source) {
mContext = context;
this.view=view ;
this.source=source;
}

@Override
protected void onPreExecute() {
super.onPreExecute();

}

@Override
protected Boolean doInBackground(String... arg0) {
Boolean isSuccess = false ;
try {
isSuccess = downFile(source,
Environment.getExternalStorageDirectory().getPath(),view);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isSuccess;
}

@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(!result){
llPro.removeView(view);
Toast.makeText(MainActivity.this, "下载失败!", Toast.LENGTH_LONG).show();
}

}
}

}

更多相关文章

  1. Google Map V2在Android中的应用
  2. Android使用post方式上传图片到服务器的方法
  3. Android(安卓)7.0 以上安装Apk适配方案总结
  4. android播放视频和视频做背景
  5. FileObserver的使用
  6. NanoHttpd 构建android 手机端的HttpServer
  7. Android点击button触发Toast事件,弹出一个小小的消息框,几秒钟之
  8. LinearLayout和RelativeLayout的属性差异
  9. 一个切换的Widget

随机推荐

  1. 新RabbitMQ精讲 提升工程实践能力 培养架
  2. kubeadm初始化k8s集群延长证书过期时间
  3. 在OPNsense防火墙上使用HAProxy和“Let’
  4. Redo Log & CacheEngine 性能详解
  5. ZooKeeper 的选举机制,你了解多少?
  6. CCNP(ISCW)实验:配置AAA支持Tacacs+
  7. k8s1.18高可用集群安装-超详细中文官方文
  8. CCNP(ISCW)实验:配置AAA支持Radius
  9. IntelliJ IDEA激活码(2021年3月11日09:42:
  10. 磁盘空间-逻辑卷