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
|
private void downloadApk(final String fileUrl) {
new Thread() {
public void run() {
String filePath = Environment.getExternalStorageDirectory().getPath() + "/" + APK_NAME;
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
File file = new File(filePath);
file.createNewFile();// 新建文件
is = conn.getInputStream();
fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
while (true) {
int numread = is.read(buffer);
if (numread <= 0) {
break;
}
fos.write(buffer, 0, numread);
}
fos.flush();
} catch (MalformedURLException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
is.close();
fos.close();
System.out.println("下载成功!");
installApk(filePath);
} catch (IOException e) {
System.out.println("下载失败!");
System.out.println(e.getMessage());
}
}
}
}.start();
}
private void installApk(final String filePath) {
new Thread() {
public void run() {
Process process = null;
OutputStream out = null;
try {
// 请求root
process = Runtime.getRuntime().exec("su");
out = process.getOutputStream();
// 调用安装
out.write(("pm install -r " + filePath + "\n").getBytes());
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
out.flush();
out.close();
System.out.println("安装成功!");
startApk();
} catch (IOException e) {
System.out.println("安装失败!");
System.out.println(e.getMessage());
}
}
}
}.start();
} |