public class APKDownLoadUtil {
private final int LOADING_FINASH = 100;
private final int DIALOG_UPDATA = 1000;
private final int DIALOG_CANCEL = 2000;
private final int DIALOG_FINSH = 3000;
private final int DIALOG_DESTORY = 4000;
private boolean isRun = true;
private Context context;
private String url;
private String fileName;
private DownLoadProgressDialog progressDialog;
public APKDownLoadUtil(Context context, String url, String fileName) {
this.context = context;
this.url = url;
this.fileName = fileName;
initProgress();
}
private final Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case DIALOG_UPDATA:
// progressDialog.setProgress(msg.arg1);
progressDialog.showDialogProgress(msg.arg1);
break;
case DIALOG_CANCEL:
// progressDialog.cancel();
progressDialog.dismiss();
if(fileName.endsWith(".apk")){
update(context, fileName + ".apk");
}
break;
case DIALOG_FINSH:
// progressDialog.cancel();
progressDialog.dismiss();
break;
case DIALOG_DESTORY:
progressDialog.dismiss();
break;
}
};
};
public void start(){
progressDialog.show();
td.start();
}
private Thread td = new Thread() {
@SuppressWarnings("resource")
public void run() {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setConnectTimeout(3 * 60 * 1000);
// conn.setRequestMethod("GET");
int length = conn.getContentLength();
// 保存上次下载的apk的大小
InputStream is = conn.getInputStream();
// time2 = System.currentTimeMillis();
FileOutputStream fileOutputStream = null;
LogUtils.d("FileUtils", "=======" + fileName + ".apk");
File file = null;
if(fileName.endsWith(".apk")){
file = new File(Environment.getExternalStorageDirectory(), fileName + ".apk");
}else{
file = new File(Environment.getExternalStorageDirectory(), fileName);
}
if (!file.exists()) {
file.delete();
}
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[2 * 1024];
int ch = -1;
int progress = 0;
while ((ch = is.read(buf)) != -1) {
if (isRun) {
fileOutputStream.write(buf, 0, ch);
long tempFileLength = file.length();
// LogUtil.d("fj12580","tempFileLength------" +
// tempFileLength + "length------" + length);
// // 更新通知中的进度条
progress = (int) (tempFileLength * 100 / length);
// // 利用Handler在主线程中更新
Message msg = handler.obtainMessage();
msg.what = DIALOG_UPDATA;
msg.arg1 = progress;
handler.sendMessage(msg);
} else {
Message msg = handler.obtainMessage();
msg.what = DIALOG_DESTORY;
handler.sendMessage(msg);
handler.removeCallbacks(td);
break;
}
}
if (progress == LOADING_FINASH) {
Message msg = handler.obtainMessage();
msg.what = DIALOG_CANCEL;
handler.sendMessage(msg);
} else {
Message msg = handler.obtainMessage();
msg.what = DIALOG_FINSH;
handler.sendMessage(msg);
}
// time3 = System.currentTimeMillis();
fileOutputStream.flush();
} catch (Exception e) {
Message msg = handler.obtainMessage();
msg.what = DIALOG_FINSH;
handler.sendMessage(msg);
e.printStackTrace();
}
};
};
private void initProgress() {
progressDialog = new DownLoadProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setOnProgressBarListener(new OnClickListener() {
public void onClick(View v) {
if (isRun) {
isRun = false;
}
}
});
}
private void update(Context context, String fileName) {
LogUtils.e("APKDownLoadUtil","fileName:"+fileName);
File file = new File(Environment.getExternalStorageDirectory(), fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
Uri apkURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName()+ ".provider", file);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//允许临时的读和写
intent.setDataAndType(apkURI,
"application/vnd.android.package-archive");
}else{
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), fileName)),
"application/vnd.android.package-archive");
// intent.setDataAndType(Uri.parse("file://" + apkfile.toString()),
// "application/vnd.android.package-archive");
}
// intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), fileName)),
// "application/vnd.android.package-archive");
// context.startActivity(intent);
((Activity) context).startActivityForResult(intent, 22);
}
}
下载进度框DownLoadProgressDialog
public class DownLoadProgressDialog {// 右确定
private Dialog dialog;
private View view;
private Context mContext;
private ProgressBar progressBar;
private TextView tv_value;
public DownLoadProgressDialog(final Context context) {
this.mContext = context;
view = LayoutInflater.from(context).inflate(R.layout.down_laod_progress, null);
dialog = new Dialog(context, R.style.dialog_layout_progress);
progressBar = (ProgressBar) view.findViewById(R.id.my_progress);
tv_value = (TextView) view.findViewById(R.id.tv_value);
}
public void setOnProgressBarListener(OnClickListener click){
progressBar.setOnClickListener(click);
}
public void showDialogProgress(int progress){
progressBar.setProgress(progress);
tv_value.setText("下载中("+progress+"%)");
}
public void setSysAlert() {
if(Build.VERSION.SDK_INT >= 26){
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
}else{
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}
}
public void setCancelableOnTouchOutside(boolean flag) {
dialog.setCanceledOnTouchOutside(flag);
}
public void setOnDismissListener(final ICallBackListener listener) {
dialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
}
});
}
public void show() {
dialog.getWindow().setContentView(view);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
dialog.getWindow().setGravity(Gravity.BOTTOM);
dialog.show();
}
public void dismiss() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
public boolean isShowing() {
if (dialog != null)
return dialog.isShowing();
return false;
}
public void setCancelable(boolean flag) {
dialog.setCancelable(flag);
}
}
进度框layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E2E2E2"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="55dp" >
<ProgressBar
android:id="@+id/my_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:max="100"
android:progress="1"
android:progressDrawable="@drawable/down_load_progressd"
android:secondaryProgress="1" />
<TextView
android:id="@+id/tv_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text=""/>
</RelativeLayout>
</LinearLayout>
dialog style
<style name="dialog_layout_progress" parent="@android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:background">@color/transparent</item>
<item name="android:windowBackground">@color/transparent</item>
<item name="android:gravity">center</item>
<item name="android:backgroundDimAmount">0.6</item>
<item name="android:layout_marginLeft">30dp</item>
<item name="android:layout_marginRight">30dp</item>
<item name="android:backgroundDimEnabled">false</item>
</style>