rk
昨天 4a8ff39b0fab0627ef8f7459587d514cc01c3676
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 com.doumee.keyCabinet.utils.update;
 
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
 
import androidx.core.content.FileProvider;
 
import com.doumee.keyCabinet.R;
import com.nostra13.universalimageloader.utils.L;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
 
/***
 * dialog文件下载
 *
 */
public class DownloadDialog extends Dialog {
    private static final int DOWNLOAD_PREPARE = 0;
    private static final int DOWNLOAD_WORK = 1;
    private static final int DOWNLOAD_OK = 2;
    private static final int DOWNLOAD_ERROR = 3;
    private static final String TAG = "IndexActivity";
    private Context mContext;
 
    private ProgressBar pb;
    /** 下载过程中不能点击 */
    public static boolean downloadOk;
    private TextView tv;
    private boolean iscancel;
    private UpdateDialog updateDialog;
    /**
     * 下载的url
     */
    private String url = null;
    private String filePath;
 
    /**
     * 文件大小
     */
    int fileSize = 0;
 
    /**
     * 下载的大小
     */
    int downloadSize = 0;
 
    /**
     * handler
     */
    private Handler handler = new Handler() {
 
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case DOWNLOAD_PREPARE:
                pb.setVisibility(ProgressBar.VISIBLE);
                Log.e(TAG, "文件大小:" + fileSize);
                pb.setMax(fileSize);
                break;
            case DOWNLOAD_WORK:
                pb.setProgress(downloadSize);
                long size = downloadSize;
                long res = (size*100/fileSize);
                tv.setText(res + "%");
                // bt.setText(FileUtil.FormetFileSize(downloadSize) + "/"
                // + FileUtil.FormetFileSize(fileSize));
                break;
            case DOWNLOAD_OK:
                downloadSize = 0;
                fileSize = 0;
                try {
                    Activity ac = null;
                    if (mContext != null) {
                        ac = (Activity) mContext;
                    } else {
                        L.d("mContext====null");
                    }
                    if (ac != null && !ac.isFinishing()) {
                        L.d("ac===!!!!!!!!!!=null");
                        cancel();
                        if (updateDialog != null) {
                            updateDialog.show();
                        }
                        if (downloadOk) {
                            initUpdate();
                        }
                    }
                } catch (Exception e) {
                    L.d("出现异常-----窗口关闭-");
                    L.d("出现异常-----窗口关闭-");
                }
 
                break;
            case DOWNLOAD_ERROR:
                downloadSize = 0;
                fileSize = 0;
                Toast toast1 = Toast.makeText(mContext, mContext.getString(R.string.download_3),
                        Toast.LENGTH_SHORT);
                toast1.setGravity(Gravity.CENTER, 0, 0);
                toast1.show();
                cancel();
                break;
            }
            super.handleMessage(msg);
        }
    };
 
    private void getPermision(final Intent intent){
        PermissionUtils.getPermission2(mContext, new PermissionUtils.CallBack() {
                    @Override
                    public void sucess() {
                        if(intent!=null){
                            mContext.startActivity(intent);
                        }else {
                            initUpdate();
                        }
                    }
 
                    @Override
                    public void fail(List<String> permissions) {
                        //showNoPermissionTip();
                        Uri packageURI = Uri.parse("package:" + mContext.getPackageName());
                        //注意这个是8.0新API
                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                        mContext.startActivity(intent);
                        updateDialog.show();
                        dismiss();
                    }
                },new String[]{"android.permission.REQUEST_INSTALL_PACKAGES"});
    }
 
    private PermissiondDialog permissiondDialog;
    /**
     * 没有权限的提醒
     *
     */
    private void showNoPermissionTip() {
        try {
            Toast.makeText(mContext, mContext.getString(R.string.download_1), Toast.LENGTH_LONG).show();
            if(permissiondDialog==null){
                permissiondDialog=new PermissiondDialog(mContext, mContext.getString(R.string.help), mContext.getString(R.string.download_2), mContext.getString(R.string.cancel),
                        mContext.getString(R.string.empower), new PermissiondDialog.OnClickListener() {
                    @Override
                    public void clickOk() {
                        permissiondDialog.dismiss();
                        Uri packageURI = Uri.parse("package:" + mContext.getPackageName());
                        //注意这个是8.0新API
                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                        mContext.startActivity(intent);
                        updateDialog.show();
                        dismiss();
                    }
 
                    @Override
                    public void clickNo() {
                        permissiondDialog.dismiss();
                    }
                });
            }
            if(!permissiondDialog.isShowing()){
                permissiondDialog.show();
            }
        }catch (Exception e){
 
        }
    }
 
    private Intent intent;
    // 安装应用
    void initUpdate() {
        try {
            intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri contentUri = FileProvider.getUriForFile(mContext, "com.doumee.keyCabinet.fileProvider", new File(filePath));
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                //Toast.makeText(mContext, contentUri.toString(), Toast.LENGTH_SHORT).show();
                //兼容8.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    boolean hasInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
                    if (!hasInstallPermission) {
                        //startInstallPermissionSettingActivity();
                        getPermision(intent);
                        return;
                    }
                }
            } else {
                intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            mContext.startActivity(intent);
 
            //MApplication.getInstance().setDestroyActivitys(true);
            //MApplication.getInstance().exitApp();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public DownloadDialog(Context context, String url) {
        super(context, R.style.dialog_style);
        mContext = context;
        this.url = url;
        filePath = FileUtil.getPath(mContext, url);
    }
 
    public void setUpdateDialog(UpdateDialog updateDialog) {
        this.updateDialog = updateDialog;
    }
 
    @Override
    public void cancel() {
        super.cancel();
        iscancel = true;
    }
 
    /**
     * 下载文件
     */
    private void downloadFile() {
        try {
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setConnectTimeout(10000);
            int responeCode = conn.getResponseCode();
            InputStream is;
            if (responeCode == 200) {
                is = conn.getInputStream();
            } else {
                sendMessage(DOWNLOAD_ERROR);
                return;
            }
 
            fileSize = conn.getContentLength();
            if (fileSize < 1 || is == null) {
                sendMessage(DOWNLOAD_ERROR);
            } else {
                sendMessage(DOWNLOAD_PREPARE);
                if (FileUtil.deleteFile(filePath)) {// 删除原来的安装文件再下载
                    FileOutputStream fos = new FileOutputStream(filePath);
                    byte[] bytes = new byte[1024];
                    int len = -1;
                    while ((len = is.read(bytes)) != -1) {
                        if (!iscancel) {
                            fos.write(bytes, 0, len);
                            fos.flush();
                            downloadSize += len;
                            sendMessage(DOWNLOAD_WORK);
                        } else {
                            return;
                        }
                    }
                    sendMessage(DOWNLOAD_OK);
                    is.close();
                    fos.close();
                }
            }
        } catch (Exception e) {
            sendMessage(DOWNLOAD_ERROR);
            e.printStackTrace();
        }
    }
 
    /***
     * 得到文件的路径
     *
     * @return
     */
    public String getFilePath() {
        return filePath;
    }
 
    private void init() {
        // bt.setOnClickListener(this);
        tv = (TextView) this.findViewById(R.id.progre_num);
        pb = (ProgressBar) this.findViewById(R.id.down_pb);
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_download);
        downloadOk = true;
        init();
    }
 
    /**
     * @param what
     */
    private void sendMessage(int what) {
        Message m = new Message();
        m.what = what;
        handler.sendMessage(m);
    }
 
    @Override
    public void show() {
        super.show();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean hasInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
            if (!hasInstallPermission) {
                //startInstallPermissionSettingActivity();
                getPermision(null);
                return;
            }
        }
        // 弹出就开始下载
        new Thread(new Runnable() {
            @Override
            public void run() {
                downloadFile();
            }
        }).start();
    }
}