效果如下圖:
布局 文件
- activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="支付" />
</LinearLayout>
UI 文件
- HomeActivity.java
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "HomeActivity";
/**
* 下載
*/
private Button mBtn;
private ProgressBar mPgb;
private TextView mTv;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
initView();
}
private void initView() {
mBtn = (Button) findViewById(R.id.btn);
mBtn.setOnClickListener(this);
mPgb = (ProgressBar) findViewById(R.id.pgb);
mTv = (TextView) findViewById(R.id.tv);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
case R.id.btn:
initDownload();
break;
}
}
private void initDownload() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request request = new Request.Builder()
.url("http://cdn.banmi.com/banmiapp/apk/banmi_330.apk")
.get()
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("tag", "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body(); // 獲取到請求體
InputStream inputStream = body.byteStream(); // 轉(zhuǎn)換成字節(jié)流
saveFile(inputStream, Environment.getExternalStorageDirectory() + "/" + "qq.apk", body.contentLength());
}
});
}
/**
* @param inputStream
* @param s 存放的地址
* @param l 文件的長度
*/
private void saveFile(InputStream inputStream, String s, final long l) {
long count = 0;
try {
// 獲取到輸出流挪鹏,寫入到的地址
FileOutputStream outputStream = new FileOutputStream(new File(s));
int length = -1;
byte[] bytes = new byte[1024 * 10];
while ((length = inputStream.read(bytes)) != -1) {
// 寫入文件
outputStream.write(bytes, 0, length);
count += length;
final long finalCount = count;
final int finalLenght = length;
runOnUiThread(new Runnable() {
@Override
public void run() {
mPgb.setMax((int) l); // 設(shè)置進度條最大值
mPgb.setProgress((int) finalCount); // 設(shè)置進度
mTv.setText((int) (100 * finalCount / l) + "%"); // 設(shè)置進度文本 (100 * 當前進度 / 總進度)
}
});
Log.e("tag", "progress" + count + "max" + l);
}
inputStream.close(); // 關(guān)閉輸入流
outputStream.close(); // 關(guān)閉輸出流
runOnUiThread(new Runnable() {
@Override
public void run() {
// 如果寫入的進度值完畢,Toast
Toast.makeText(HomeActivity.this, "下載完成", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}