1.引入xutils的jar包 xUtils-2.6.14.jar2.如果是android 6.0还需要添加aphace httpclient的jar包 org.apache.http.legacy.jar
public class MainActivity extends Activity {
private TextView tv;
private ProgressBar pb;
private TextView tvProgress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv_failure);
pb = (ProgressBar) findViewById(R.id.pb);
tvProgress = (TextView) findViewById(R.id.tv_progress);
}
public void startDown(View v) {
HttpUtils http = new HttpUtils();
String fileName = "pdf.exe";
String path = "http://192.168.1.103:8080/android/" + fileName;
HttpHandler handler = http.download(path, // 下载地址
Environment.getExternalStorageDirectory() + File.separator + fileName, // 保存路径
true, // 是否支持断点续传
true, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
new RequestCallBack<File>() {
@Override
public void onLoading(long total, long current,
boolean isUploading) {
super.onLoading(total, current, isUploading);
pb.setMax((int) total);
pb.setProgress((int) current);
tvProgress.setText((current * 100 / total ) + "%");
}
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
File file = (File) responseInfo.result;
Toast.makeText(MainActivity.this, file.getPath(), 0)
.show();
}
@Override
public void onFailure(HttpException error, String msg) {
tv.setText(msg);
}
});
}
}
布局文件
<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"
tools:context="com.example.multidown.MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startDown"
android:text="开始下载" />
<TextView
android:id="@+id/tv_failure"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar
android:id="@+id/pb"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
效果图:
[图片上传中。。。(1)]