方案一
1.创建ProcessInterface接口用于时时更新progressbar
public interface ProcessInterface {
/**
* 更新UI ,用于显示更新的进度
*
* @param progress 进度
*/
void updateProgressBar(int progress);
/**
* 设置所下载文件的最大值
*
* @param max 下载文件的最大值
*/
void setMax(int max);
void hideProgress();
}
2.MainActivity实现这个接口
@Override
public void updateProgressBar(final int progress) {
runOnUiThread(new Runnable() {
@Override
public void run() {
int max = mUpdateBar.getMax();
String precentVal = (Util.div(progress, max, 2) * 100) + "";
precentVal = precentVal.substring(0, precentVal.lastIndexOf("."));
mProgressText.setText("程序已下载" + precentVal + "%...");
mUpdateBar.setProgress(progress);
if (max == progress) {
mUpdateLayout.setVisibility(View.GONE);
UpdateApkUtil.insertApk();
}
}
});
}
@Override
public void setMax(final int max) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mUpdateBar.setMax(max);
}
});
}
@Override
public void hideProgress() {
mUpdateLayout.setVisibility(View.GONE);
}
3.ProgressBar的设计
(1)Utils类
public static double div(double v1, double v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
(2)ProgressBar布局文件
<LinearLayout
android:id="@+id/updateapkview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
android:clickable="true"
android:visibility="gone">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/tv_update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="程序准备下载..."
android:textColor="@color/white" />
<ProgressBar
android:id="@+id/progressBar_update"
style="@style/progressBarCustomStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center"
android:padding="10dp"
android:progress="10" />
</LinearLayout>
</LinearLayout>
(3)Drawable文件添加ProgressBar样式
progress_horizontal.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/background">
<shape>
<corners android:radius="5dip" />
<gradient
android:angle="270"
android:centerColor="@color/color_f6"
android:centerY="0.75"
android:endColor="@color/color_f6"
android:startColor="@color/color_f6" />
</shape>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="5dip" />
<gradient
android:angle="270&