UpdateManager.java
3.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.gimi.common.cinema.utils;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.squareup.okhttp.Request;
import java.io.File;
class UpdateManager {
private Context mContext;
private String apkUrl;
private Dialog downloadDialog;
private ProgressBar mProgress;
private int progress;
UpdateManager(Context context, String apkMessage) {
this.mContext = context;
this.apkUrl = apkMessage;
}
private boolean hasSDCard() {
String status = Environment.getExternalStorageState();
return status.equals(Environment.MEDIA_MOUNTED);
}
private String getRootFilePath() {
if (hasSDCard()) {
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator +
"android" + File.separator + "data" + File.separator;
} else {
return Environment.getDataDirectory().getAbsolutePath()
+ File.separator + "data" + File.separator;
}
}
void showDownloadDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("软件下载中.......");
mProgress = new ProgressBar(mContext, null,
android.R.attr.progressBarStyleHorizontal);//水平条形
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(200, -2);//长度200,高度默认
mProgress.setLayoutParams(lp2);
mProgress.setMax(100);
builder.setView(mProgress);
builder.setCancelable(false);
downloadDialog = builder.create();
downloadDialog.show();
downloadApk();
}
private void downloadApk() {
OkHttpClientManager.downloadAsyn(apkUrl, getRootFilePath() + "aa.apk",
new OkHttpClientManager.ResultCallback<String>() {
@Override
public void onError(Request request, Exception e) {
}
@Override
public void onResponse(String response) {
downloadDialog.dismiss();
installApk(response);
}
}, new OkHttpClientManager.ProgressListener() {
@Override
public void onResponseProgress(long bytesRead, long contentLength) {
progress = (int)
(((float) bytesRead / contentLength) * 100);
//更新进度
mProgress.setProgress(progress);
}
});
}
private void installApk(String path) {
File apkFile = new File(path);
if (!apkFile.exists()) {
return;
}
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(apkFile);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
mContext.startActivity(intent);
}
}