AutoUpdater.java
12.4 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package etelligens.com.foodsafety.utils;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.content.FileProvider;
import etelligens.com.foodsafety.R;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static me.pushy.sdk.config.PushyLogging.TAG;
/**
* @author wj
* @Description: 自动更新apk
* @create 2023/10/24 14:02
**/
public class AutoUpdater {
// 下载安装包的网络路径
private String apkUrl = "http://52.74.130.36/upload/app/";
protected String checkUrl = apkUrl + "output-metadata.json";
// 保存APK的文件名
private static final String saveFileName = "release.apk";
private static File apkFile;
// 下载线程
private Thread downLoadThread;
private int progress;// 当前进度
// 应用程序Context
private Context mContext;
// 是否是最新的应用,默认为false
private boolean isNew = false;
private boolean intercept = false;
// 进度条与通知UI刷新的handler和msg常量
private ProgressBar mProgress;
private TextView txtStatus;
private static final int DOWN_UPDATE = 1;
private static final int DOWN_OVER = 2;
private static final int SHOWDOWN = 3;
public AutoUpdater(Context context) {
mContext = context;
String root = Environment.getExternalStorageDirectory().getPath();
String parentPath = "";
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
parentPath = mContext.getExternalFilesDir(null).getPath();
} else {
parentPath = mContext.getFilesDir().getPath();
}
} catch (Exception e) {
Log.d(TAG, "doDownload e:" + e.getMessage());
}
Log.d(TAG, "doDownload parentPath:" + parentPath);
//Toast.makeText(mContext,"跟路径"+root,Toast.LENGTH_SHORT).show();
//Toast.makeText(mContext, "Android版本"+Build.VERSION.SDK_INT, Toast.LENGTH_SHORT).show();
apkFile = new File(parentPath, saveFileName);
//如果已有文件,删除
if (apkFile.exists()) {
Log.d(TAG, "doDownload delete APK");
apkFile.delete();
}
//Log.e("路径",mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString());
//apkFile = new File(root, saveFileName);
//apkFile = new File(mContext.getFilesDir(), saveFileName);
}
public void ShowUpdateDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setCancelable(false);
builder.setTitle("SOFTWARE UPDATE");
builder.setMessage("Please download and install the latest version !");
builder.setPositiveButton("Now", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ShowDownloadDialog();
}
});
builder.setNegativeButton("Later", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
private void ShowDownloadDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setCancelable(false);
dialog.setTitle("Updating...");
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.progress);
txtStatus = v.findViewById(R.id.txtStatus);
dialog.setView(v);
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
intercept = true;
}
});
dialog.show();
DownloadApk();
}
/**
* 检查是否更新的内容
*/
public void CheckUpdate() {
new Thread(new Runnable() {
@Override
public void run() {
String localVersion = "1";
try {
localVersion = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName;
//localVersion="20231024083955";
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String versionName = "1";
String outputFile = "";
String config = doGet(checkUrl);
if (config != null && config.length() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Matcher matcher = Pattern.compile("\"outputFile\":\\s*\"([^\"]*?)\"").matcher(config);
if (matcher.find()) {
outputFile = matcher.group(1);
}
matcher = Pattern.compile("\"versionName\":\\s*\"([^\"]*?)\"").matcher(config);
if (matcher.find()) {
String v = matcher.group(1);
versionName = v.replace("v1.0.", "");
}
}
}
if (Long.parseLong(localVersion) < Long.parseLong(versionName)) {
apkUrl = apkUrl + outputFile;
mHandler.sendEmptyMessage(SHOWDOWN);
Log.e("部署版",versionName);
Log.e("本班",localVersion);
} else {
return;
}
}
}).start();
}
/**
* 从服务器下载APK安装包
*/
public void DownloadApk() {
downLoadThread = new Thread(DownApkWork);
downLoadThread.start();
}
private Runnable DownApkWork = new Runnable() {
@Override
public void run() {
URL url;
try {
//如果下载地址是HTTPS,则把这段加上,http则不需要
SSLContext sslContext = SSLContext.getInstance("SSL");//第一个参数为 返回实现指定安全套接字协议的SSLContext对象。第二个为提供者
TrustManager[] tm = {new MyX509TrustManager()};
sslContext.init(null, tm, new SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
url = new URL(apkUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream ins = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
byte[] buf = new byte[1024];
while (!intercept) {
int numread = ins.read(buf);
count += numread;
progress = (int) (((float) count / length) * 100);
// 下载进度
mHandler.sendEmptyMessage(DOWN_UPDATE);
if (numread <= 0) {
// 下载完成通知安装
mHandler.sendEmptyMessage(DOWN_OVER);
break;
}
fos.write(buf, 0, numread);
}
fos.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//卸载
public void uninstallAPP() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + mContext.getApplicationContext().getPackageName()));
mContext.startActivity(intent);
installAPK();
}
/**
* 安装APK内容
*/
public void installAPK() {
try {
if (!apkFile.exists()) {
return;
}
Toast.makeText(mContext, "install", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//安装完成后打开新版本
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 给目标应用一个临时授权
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
//如果SDK版本>=24,即:Build.VERSION.SDK_INT >= 24,使用FileProvider兼容安装apk
String packageName = mContext.getApplicationContext().getPackageName();
String authority = new StringBuilder(packageName).append(".provider").toString();
Uri apkUri = FileProvider.getUriForFile(mContext, authority, apkFile);
Log.e("packageName",packageName);
Log.e("authority",authority);
Log.e("apkFile", String.valueOf(apkFile));
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
}
mContext.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());//安装完之后会提示”完成” “打开”。
} catch (Exception e) {
}
}
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SHOWDOWN:
ShowUpdateDialog();
break;
case DOWN_UPDATE:
txtStatus.setText(progress + "%");
mProgress.setProgress(progress);
break;
case DOWN_OVER:
Toast.makeText(mContext, "Download complete", Toast.LENGTH_SHORT).show();
uninstallAPP();
break;
default:
break;
}
}
};
public static String doGet(String httpurl) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpurl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(15000);
connection.setReadTimeout(60000);
connection.connect();
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
connection.disconnect();
}
return result;
}
}