# 静默安装

public class AppUpgrade  {
    File file;
    String fullDownloadPath;
    
    Context wcontext;
    /**
     * 静态安装apk
     * @param url app下载的地址
     */
    public  AppUpgrade(String url) {
        file = downFile(url);
    }

    /**
     * 后台在下面一个Apk 下载完成后返回下载好的文件
     *
     * @param httpUrl
     * @return
     */
    private File downFile(final String httpUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(httpUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    FileOutputStream fileOutputStream = null;
                    InputStream inputStream;
                    if (connection.getResponseCode() == 200) {
                        inputStream = connection.getInputStream();
                        Message message = mUpdateProgressHandler.obtainMessage();
                        message.what = 1;
                        mUpdateProgressHandler.sendMessage(message);
                        if (inputStream != null) {
                            file = getFile(httpUrl);
                            fileOutputStream = new FileOutputStream(file);
                            byte[] buffer = new byte[1024];
                            int length = 0;

                            while ((length = inputStream.read(buffer)) != -1) {
                                fileOutputStream.write(buffer, 0, length);
                            }
                            fileOutputStream.close();
                            fileOutputStream.flush();

                        }
                        inputStream.close();
                    }

                    fullDownloadPath = getDownloadFileFullPath(httpUrl);
                    Log.i("download", "run: "+"下载完成");

                    // 往handler发送一条消息 更改button的text属性
                    Message message = mUpdateProgressHandler.obtainMessage();
                    message.what = 2;
                    mUpdateProgressHandler.sendMessage(message);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return file;
    }

    /**
     * 根据传过来url创建文件
     */
    private File getFile(String url) {

        File files = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "Download" + getFilePath(url));
        return files;
    }

    private String getDownloadFileFullPath(String url) {
        Log.v("路径为:",Environment.getExternalStorageDirectory().getAbsoluteFile().toString() + "/Download");
        return Environment.getExternalStorageDirectory().getAbsoluteFile().toString() + "/Download" + getFilePath(url);
    }

    /**
     * 截取出url后面的apk的文件名
     * @param url
     * @return
     */
    private String getFilePath(String url) {
        return url.substring(url.lastIndexOf("/"), url.length());
    }

    /**
     * 接收消息
     */
    @SuppressLint("HandlerLeak")
    private Handler mUpdateProgressHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Log.v("进度",""+msg);
            switch (msg.what){
                case 1:
                    Log.v("正在下载安装包...","");
                    break;
                case 2:
                    Log.i("installed:::::", fullDownloadPath);

                    int isInstalled = installCustomApp(fullDownloadPath);

                    // 检测安装成功后即可打开床旁APP,实现安装自启动
                    if (isInstalled == 1) {
                        Log.v("安装包静默安装完成","6666");
                    }
            }
        };
    };

    public int installCustomApp(String apkPath)
    {      
		RootCommand("pm install -r "+ fullDownloadPath);
        return 1;
    }

    /**
     * 安装apk
     * @param cmd 执行命令语法
     */
    public static void RootCommand(String cmd) {
        Process process = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            int aa = process.waitFor();
            is = new DataInputStream(process.getInputStream());
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            String out = new String(buffer);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }
    }


    /**
     * 获取当前时间
     * @return 返回当前时间
     */
    public  static  String getTime(){
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sim = dateFormat.format(date);
        return  sim;
    }

}

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