Linjiajia
2023-07-25 82e57df230ecb744af6c8865f80870ba03c86d89
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
package com.application.zhangshi_app_android.ui.dialog;
 
import static com.blankj.utilcode.util.StringUtils.getString;
 
import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
 
import androidx.annotation.StringRes;
 
import com.android.app_base.base.dialog.BaseDialog;
import com.android.app_base.utils.Utils;
import com.application.zhangshi_app_android.MyApplication;
import com.application.zhangshi_app_android.R;
 
import java.util.Timer;
import java.util.TimerTask;
 
/**
 * @author Ljj
 * @date 2023.07.25. 16:59
 * @desc
 */
public final class VersionUpdateDialog {
    @SuppressWarnings("unchecked")
    public static class Builder<B extends VersionUpdateDialog.Builder<B>>
            extends BaseDialog.Builder<B> {
 
        private boolean mAutoDismiss = true;
 
        private final TextView mTitleView;
        private final TextView mContentView;
        private final TextView mConfirmView;
        private final ProgressBar progressBar;
        private final TextView tv_pro;
        private final TextView tv_pro_percent;
        private final RelativeLayout layout_progress;
 
        private String downloadUrl;
 
        public Builder(Context context) {
            super(context);
            setContentView(R.layout.dialog_version_update);
            setAnimStyle(BaseDialog.ANIM_IOS);
            setGravity(Gravity.CENTER);
            setBackgroundDimAmount(0.5F);
            setCanceledOnTouchOutside(true);
            mTitleView = findViewById(R.id.tv_update_dialog_title);
            mContentView = findViewById(R.id.tv_update_dialog_content);
            mConfirmView = findViewById(R.id.tv_update_dialog_confirm);
            progressBar = findViewById(R.id.pb_download);
            tv_pro = findViewById(R.id.tv_pro);
            tv_pro_percent = findViewById(R.id.tv_pro_percent);
            layout_progress = findViewById(R.id.layout_progress);
            setOnClickListener(mConfirmView);
        }
 
        public B setDownloadUrl(String downloadUrl) {
            this.downloadUrl = downloadUrl;
            return (B) this;
        }
 
        public B setTitle(@StringRes int id) {
            return setTitle(getString(id));
        }
 
        public B setTitle(CharSequence text) {
            mTitleView.setText(text);
            return (B) this;
        }
 
        public B setContent(CharSequence text) {
            mContentView.setText(text);
            return (B) this;
        }
 
        public B setConfirm(@StringRes int id) {
            return setConfirm(getString(id));
        }
 
        public B setConfirm(CharSequence text) {
            mConfirmView.setText(text);
            return (B) this;
        }
 
        public B setAutoDismiss(boolean dismiss) {
            mAutoDismiss = dismiss;
            return (B) this;
        }
 
        public void autoDismiss() {
            if (mAutoDismiss) {
                dismiss();
            }
        }
 
        @Override
        public void onClick(View v) {
            if (v == mConfirmView) {
                changeVisi(View.GONE,View.VISIBLE);
                if (downloadUrl != null){
                    startDownLoadApp(downloadUrl);
                }
            }
        }
 
 
        @Override
        public BaseDialog show() {
            return super.show();
        }
 
 
        public long totalBytes;
        public long downloadBytes;
        public int dl_progress;
 
        private Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                progressBar.setProgress(dl_progress);
                tv_pro.setText((downloadBytes * 100 / totalBytes) + "%");
                tv_pro_percent.setText((downloadBytes * 100 / totalBytes) + "/100");
            }
        };
 
        public void changeVisi(int a, int b) {
            mConfirmView.setVisibility(a);
            layout_progress.setVisibility(b);
            progressBar.setProgress(0);
            tv_pro.setText("0");
            tv_pro_percent.setText("0/100");
        }
 
        /**
         * 不涉及数据库,单独下载文件
         */
        public void startDownLoadApp(String url) {
            String fileName = "app_update";
            //创建下载任务,downloadUrl就是下载链接
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);//下载进行中和下载完成的通知栏是否显示
            //用于设置下载时时候在状态栏显示通知信息
            request.setNotificationVisibility(request.VISIBILITY_VISIBLE);
            request.allowScanningByMediaScanner();//设置允许被扫描到
            request.setVisibleInDownloadsUi(true);//下载的文件可以被系统的Downloads应用扫描到并管理
 
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); //指定下载路径和下载文件名
 
            final DownloadManager downloadManager = (DownloadManager) MyApplication.getInstance().getSystemService(Context.DOWNLOAD_SERVICE);//获取下载管理器
            final long downloadID = downloadManager.enqueue(request);//将下载任务加入下载队列,否则不会进行下载
 
            final DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadID);//筛选下载任务,传入任务ID,可变参数
 
 
            final Timer mTimer = new Timer();
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    updateDownloadSize(query, mTimer, downloadManager, fileName);
                }
            }, 0, 1000);
        }
 
        @SuppressLint("Range")
        private void updateDownloadSize(DownloadManager.Query query, Timer mTimer, DownloadManager downloadManager, String fileName) {
            Cursor c = null;
            try {
                c = downloadManager.query(query);
                if (c != null) {
                    if (c.moveToFirst()) {
                        int downloadBytesIdx = c.getColumnIndexOrThrow(
                                DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                        int totalBytesIdx = c.getColumnIndexOrThrow(
                                DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                        totalBytes = c.getLong(totalBytesIdx);
                        downloadBytes = c.getLong(downloadBytesIdx);
                        int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                        // 已下载的字节大小
                        final long downloadedSoFar = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        // 下载文件的总字节大小
                        final long totalSize = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                        dl_progress = (int) (downloadedSoFar * 100 / totalSize);
                        switch (status) {
                            case DownloadManager.STATUS_PAUSED:
                                Log.d("APPUpdate", "下载暂停:" + fileName);
                            case DownloadManager.STATUS_PENDING:
                                Log.d("APPUpdate", "下载延迟:" + fileName);
                            case DownloadManager.STATUS_RUNNING:
                                Log.d("APPUpdate", "正在下载:" + fileName);
                                handler.postDelayed(runnable, 100);
                                break;
                            case DownloadManager.STATUS_SUCCESSFUL:
                                Log.d("APPUpdate", "下载完成:" + fileName);
                                mTimer.cancel();
                                dismiss();
                                handler=null;
                                //下载完成安装APK
                                Utils.installAPK(getContext(), fileName);
                                break;
                            case DownloadManager.STATUS_FAILED:
                                Log.d("APPUpdate", "下载失败:" + fileName);
                                setContent("下载失败,请重新下载");
                                changeVisi(View.VISIBLE,View.GONE);
                                break;
                        }
                    }
                }
            } finally {
                if (c != null) {
                    c.close();
                }
            }
 
        }
 
    }
}