效果如下图:
布局 文件
- 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(); // 转换成字节流
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); // 设置进度条最大值
mPgb.setProgress((int) finalCount); // 设置进度
mTv.setText((int) (100 * finalCount / l) + "%"); // 设置进度文本 (100 * 当前进度 / 总进度)
}
});
Log.e("tag", "progress" + count + "max" + l);
}
inputStream.close(); // 关闭输入流
outputStream.close(); // 关闭输出流
runOnUiThread(new Runnable() {
@Override
public void run() {
// 如果写入的进度值完毕,Toast
Toast.makeText(HomeActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}