導xutils包java
配置權限android
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
/MainActivity.javaapp
package com.bawei.myxutils; import java.io.File; import java.math.BigDecimal; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.HttpHandler; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; public class MainActivity extends Activity { private ProgressBar pb; private TextView text1; private TextView text2; private String path; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pb = (ProgressBar) findViewById(R.id.progressBar1);// 進度條 text1 = (TextView) findViewById(R.id.text1);// 顯示當前下載了多少 text2 = (TextView) findViewById(R.id.text2);// 顯示下載總大小 path = Environment.getExternalStorageDirectory().getPath();// 獲得SD卡路徑 HttpUtils http = new HttpUtils(); /** * url 下載的路徑 target 下載文件保存的路徑 autoResume 是否支持斷點續傳 */ HttpHandler handler = http.download( "http://101.200.142.201:8080/tqyb/dancer.avi", path + "/dancer.avi", true /* 若是目標文件存在,接着未完成的部分繼續下載。 */, true/* 若是從請求返回信息中獲取到文件名,下載完成後自動重命名。 */, new RequestCallBack<File>() { @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); Toast.makeText(MainActivity.this, "開始下載", 0).show(); } /** * 加載進度 pb爲進度條,實現進度條進度加載 total 總得大小 current 當前的大小 */ @Override public void onLoading(long total, long current, boolean isUploading) { // TODO Auto-generated method stub pb.setMax((int) total); pb.setProgress((int) current); // 將字節轉換成M BigDecimal filesize = new BigDecimal(current); BigDecimal megabyte = new BigDecimal(1024 * 1024); float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue(); text1.setText(returnValue + "M"); // 將字節轉換成M BigDecimal filesize1 = new BigDecimal(total); BigDecimal megabyte1 = new BigDecimal(1024 * 1024); float returnValue1 = filesize1.divide(megabyte1, 2, BigDecimal.ROUND_UP).floatValue(); text2.setText(returnValue1 + "M"); } @Override public void onSuccess(ResponseInfo<File> arg0) { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "下載成功", 0).show(); } @Override public void onFailure(HttpException arg0, String arg1) { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "下載失敗", 0).show(); } }); } }