admin
2021-04-07 edeef504e654415c25d3816a4609f43edc79fbb3
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package com.weikou.beibeivideo.ui.recent;
 
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import androidx.cursoradapter.widget.CursorAdapter;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
 
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lcjian.library.util.common.ConnectionUtils;
import com.mozillaonline.providers.DownloadManager;
import com.mozillaonline.providers.downloads.Downloads;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.weikou.beibeivideo.R;
import com.weikou.beibeivideo.db.DownloadTable;
import com.weikou.beibeivideo.entity.VideoDetailInfo;
import com.weikou.beibeivideo.entity.VideoInfo;
import com.weikou.beibeivideo.ui.media.VideoDetailActivity2;
import com.weikou.beibeivideo.util.DownloadUtils;
 
public class DownLoadAdapter extends CursorAdapter {
    public interface IGetDeleteCallback {
        public void onGetNum(int count);
    }
 
    public interface IGetSelectStatus {
        public void onGetStatus(boolean status);
    }
 
    private IGetSelectStatus getselectstatus = null;
    private IGetDeleteCallback getdeleteNumber = null;
 
    public void setDeleteCallback(IGetDeleteCallback getdeleteNumber) {
        this.getdeleteNumber = getdeleteNumber;
    }
 
    public void setSelectStatus(IGetSelectStatus getselectstatus) {
        this.getselectstatus = getselectstatus;
    }
 
    private ImageLoader imageLoader = ImageLoader.getInstance();
 
    private RequestManager glide;
 
    private DisplayImageOptions options;
 
    private DownloadManager mDownloadManager;
 
    private Context mContext;
    protected Cursor mCursor;
    private Resources mResources;
    private DateFormat mDateFormat;
    private DateFormat mTimeFormat;
 
    final private int mTitleColumnId;
    final private int mDescriptionColumnId;
    final private int mStatusColumnId;
    final private int mReasonColumnId;
    final private int mTotalBytesColumnId;
    final private int mCurrentBytesColumnId;
    final private int mDateColumnId;
    final private int mIdColumnId;
 
    private List<Long> mSelectedIds;
    private boolean mSelectedMode;
 
    public DownLoadAdapter(Context context, Cursor cursor, boolean autoRequery) {
        super(context, cursor, autoRequery);
        mContext = context;
        mCursor = cursor;
        this.glide = Glide.with(context);
        mResources = mContext.getResources();
        mDateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
        mTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
 
        mIdColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
        mTitleColumnId = cursor
                .getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE);
        mDescriptionColumnId = cursor
                .getColumnIndexOrThrow(DownloadManager.COLUMN_DESCRIPTION);
        mStatusColumnId = cursor
                .getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
        mReasonColumnId = cursor
                .getColumnIndexOrThrow(DownloadManager.COLUMN_REASON);
        mTotalBytesColumnId = cursor
                .getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
        mCurrentBytesColumnId = cursor
                .getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
        cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIA_TYPE);
        mDateColumnId = cursor
                .getColumnIndexOrThrow(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP);
 
        mSelectedIds = new ArrayList<Long>();
        mVideoInfos = new HashMap<String, VideoInfo>();
 
        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.ic_default_cover)
                .showImageOnFail(R.drawable.ic_default_cover)
                .showImageOnLoading(R.drawable.ic_default_cover)
                .resetViewBeforeLoading(true).cacheInMemory(true)
                .cacheOnDisk(true).imageScaleType(ImageScaleType.EXACTLY)
                .considerExifParams(true)
                .displayer(new SimpleBitmapDisplayer()).build();
        this.mDownloadManager = new DownloadManager(
                context.getContentResolver(), context.getPackageName());
        this.mDownloadManager.setAccessAllDownloads(true);
    }
 
    public void bindView(Context context, View convertView) {
        final long downloadId = mCursor.getLong(mIdColumnId);
 
        getVideoDetail(context, downloadId, convertView);
 
        String title = mCursor.getString(mTitleColumnId);
        String description = mCursor.getString(mDescriptionColumnId);
        long totalBytes = mCursor.getLong(mTotalBytesColumnId);
        long currentBytes = mCursor.getLong(mCurrentBytesColumnId);
        int status = mCursor.getInt(mStatusColumnId);
        // 当下载文件小于1M时默认为下载失败状态
        if (status == DownloadManager.STATUS_SUCCESSFUL
                && currentBytes < 1048576) {
            status = DownloadManager.STATUS_FAILED;
            // Toast.makeText(mContext, "下载失败,请删除后重新下载",
            // Toast.LENGTH_LONG).show();
        }
        if (title.length() == 0) {
            title = mResources.getString(R.string.missing_title);
        }
        if (description.equals(title)) {
            setTextForView(convertView, R.id.tv_title, title);
        } else {
            setTextForView(convertView, R.id.tv_title,
                    title + System.getProperty("line.separator") + description);
        }
        int progress = getProgressValue(totalBytes, currentBytes);
 
        boolean indeterminate = status == DownloadManager.STATUS_PENDING;
        ProgressBar progressBar = (ProgressBar) convertView
                .findViewById(R.id.pb_download_progress);
        TextView tv_download_progress = (TextView) convertView
                .findViewById(R.id.tv_download_progress);
        // progressBar.setIndeterminate(indeterminate);
        if (!indeterminate) {
            progressBar.setProgress(progress);
            tv_download_progress.setText(String.valueOf(progress) + "%");
        }
        if (status == DownloadManager.STATUS_FAILED
                || status == DownloadManager.STATUS_SUCCESSFUL) {
            progressBar.setVisibility(View.GONE);
            tv_download_progress.setVisibility(View.GONE);
        } else {
            progressBar.setVisibility(View.VISIBLE);
            tv_download_progress.setVisibility(View.VISIBLE);
        }
 
        setTextForView(convertView, R.id.tv_download_byte,
                getSizeText(currentBytes) + "/" + getSizeText(totalBytes));
        setTextForView(convertView, R.id.tv_download_status,
                mResources.getString(getStatusStringId(status)));
        final CheckBox chb_delete = (CheckBox) convertView
                .findViewById(R.id.chb_delete);
        final Context con = context;
 
        ImageButton btn_pause_download = (ImageButton) convertView
                .findViewById(R.id.btn_pause_download);
        if (mSelectedMode) {
            convertView.findViewById(R.id.fl_download).setClickable(false);
            tv_download_progress.setVisibility(View.GONE);
            convertView.findViewById(R.id.fl_video_select).setVisibility(
                    View.VISIBLE);
            btn_pause_download.setVisibility(View.INVISIBLE);
            chb_delete.setVisibility(View.VISIBLE);
            convertView.setOnClickListener(new OnClickListener() {
 
                @Override
                public void onClick(View v) {
                    if (mSelectedIds.contains(downloadId)) {
                        mSelectedIds.remove(downloadId);
                    } else {
                        mSelectedIds.add(downloadId);
                    }
                    chb_delete.setChecked(mSelectedIds.contains(downloadId));
                    if (getdeleteNumber != null)
                        getdeleteNumber.onGetNum(mSelectedIds.size());
                }
            });
            chb_delete.setOnClickListener(new OnClickListener() {
 
                @Override
                public void onClick(View v) {
                    if (mSelectedIds.contains(downloadId)) {
                        mSelectedIds.remove(downloadId);
                    } else {
                        mSelectedIds.add(downloadId);
                    }
                    chb_delete.setChecked(mSelectedIds.contains(downloadId));
                    if (getdeleteNumber != null)
                        getdeleteNumber.onGetNum(mSelectedIds.size());
                }
            });
            chb_delete.setChecked(mSelectedIds.contains(downloadId));
        } else {
            convertView.findViewById(R.id.fl_download).setClickable(true);
            convertView.setOnClickListener(new OnClickListener() {
 
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Cursor cursor = con.getContentResolver().query(
                            DownloadTable.CONTENT_URI, null,
                            DownloadTable.TASK_ID + " = ? ",
                            new String[] { String.valueOf(downloadId) }, null);
                    if (cursor.moveToFirst()) {
                        final String videoId = cursor.getString(cursor
                                .getColumnIndexOrThrow(DownloadTable.VIDEO_ID));
                        final String videoDetailId = cursor.getString(cursor
                                .getColumnIndexOrThrow(DownloadTable.VIDEO_DETAIL_ID));
                        VideoInfo videoInfo = getVideoInfos()
                                .get(videoDetailId);
                        if (videoInfo != null) {
                            int playingPosition = 0;
                            for (int i = 0; i < videoInfo.getVideoDetailList()
                                    .size(); i++) {
                                VideoDetailInfo item =videoInfo.getVideoDetailList().get(i);
                                if (item.getId().equals(videoDetailId)) {
                                    playingPosition = i;
                                    break;
                                }
                            }
                            Intent intent = new Intent(v.getContext(),
                                    VideoDetailActivity2.class);
                            if (!TextUtils.isEmpty(DownloadUtils
                                    .getOfflinePath(v.getContext(), videoId,
                                            videoDetailId))) {
                                intent.putExtra("orientation_landscape", true);
                                intent.putExtra("video_info", videoInfo);
                                intent.putExtra("playing_position",
                                        playingPosition);
                                intent.putExtra("from", "download");
                                con.startActivity(intent);
                            } else {
                                if (!ConnectionUtils.isNetworkAvailable(v
                                        .getContext())) {
                                    Toast.makeText(con, "当前无网络,且影片未缓存完毕无法观看",
                                            Toast.LENGTH_LONG).show();
                                } else {
                                    intent.putExtra("video_info", videoInfo);
                                    intent.putExtra("playing_position",
                                            playingPosition);
                                    v.getContext().startActivity(intent);
                                }
                            }
                        }
                    }
                    cursor.close();
                }
            });
            convertView.findViewById(R.id.fl_video_select).setVisibility(
                    View.GONE);
            tv_download_progress.setVisibility(View.VISIBLE);
            chb_delete.setVisibility(View.GONE);
            btn_pause_download.setVisibility(View.VISIBLE);
            switch (status) {
            case DownloadManager.STATUS_PENDING:
                btn_pause_download.setImageResource(R.drawable.ic_pending);
                break;
            case DownloadManager.STATUS_RUNNING:
                btn_pause_download.setImageResource(R.drawable.ic_download1);
                break;
            case DownloadManager.STATUS_PAUSED:
                if (!isPausedForWifi(mCursor)) {
                    btn_pause_download.setImageResource(R.drawable.ic_pause);
                }
                break;
            case DownloadManager.STATUS_SUCCESSFUL:
                btn_pause_download.setVisibility(View.GONE);
                // btn_pause_download.setImageResource(R.drawable.ic_play);
                convertView.findViewById(R.id.tv_download_status)
                        .setVisibility(View.GONE);
                break;
            case Downloads.STATUS_INSUFFICIENT_SPACE_ERROR: {
                Toast.makeText(mContext, "内存空间不足", Toast.LENGTH_LONG).show();
            }
                break;
            case DownloadManager.STATUS_FAILED:
                btn_pause_download.setImageResource(R.drawable.ic_download1);
                break;
            }
            final int sta = status;
            final ImageButton btn = btn_pause_download;
 
            OnClickListener listener = new OnClickListener() {
 
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
 
                    switch (sta) {
                    case DownloadManager.STATUS_PENDING:
                        btn.setImageResource(R.drawable.ic_pending);
                    case DownloadManager.STATUS_RUNNING:
                        mDownloadManager.pauseDownload(downloadId);
                        break;
                    case DownloadManager.STATUS_PAUSED:
                        if (!isPausedForWifi(mCursor)) {
                            mDownloadManager.resumeDownload(downloadId);
                        }
                        break;
                    case DownloadManager.STATUS_SUCCESSFUL: {
 
                        Cursor cursor = v
                                .getContext()
                                .getContentResolver()
                                .query(DownloadTable.CONTENT_URI,
                                        null,
                                        DownloadTable.TASK_ID + " = ? ",
                                        new String[] { String
                                                .valueOf(downloadId) }, null);
                        if (cursor.moveToFirst()) {
                            String videoDetailId = cursor
                                    .getString(cursor
                                            .getColumnIndexOrThrow(DownloadTable.VIDEO_DETAIL_ID));
                            VideoInfo videoInfo = mVideoInfos
                                    .get(videoDetailId);
                            if (videoInfo != null) {
                                int playingPosition = 0;
                                for (int i = 0; i < videoInfo.getVideoDetailList().size(); i++) {
                                    VideoDetailInfo item = videoInfo.getVideoDetailList().get(i);
                                    if (item.getId().equals(videoDetailId)) {
                                        playingPosition = i;
                                        break;
                                    }
                                }
                                Intent intent = new Intent(v.getContext(),
                                        VideoDetailActivity2.class);
                                intent.putExtra("orientation_landscape", true);
                                intent.putExtra("video_info", videoInfo);
                                intent.putExtra("playing_position",
                                        playingPosition);
                                intent.putExtra("from", "download");
                                v.getContext().startActivity(intent);
                            }
                        }
                        cursor.close();
                    }
                        break;
                    case DownloadManager.STATUS_FAILED:
                        Toast.makeText(v.getContext(), "将为你重新下载",
                                Toast.LENGTH_LONG).show();
                        try {
                            mDownloadManager.restartDownload(downloadId);
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                            Toast.makeText(mContext, "请删除该项重新下载",
                                    Toast.LENGTH_LONG).show();
                        }
                        break;
                    }
 
                }
            };
 
            convertView.findViewById(R.id.fl_download).setOnClickListener(
                    listener);
            convertView.findViewById(R.id.btn_pause_download)
                    .setOnClickListener(listener);
        }
    }
 
    private String getDateString() {
        Date date = new Date(mCursor.getLong(mDateColumnId));
        if (date.before(getStartOfToday())) {
            return mDateFormat.format(date);
        } else {
            return mTimeFormat.format(date);
        }
    }
 
    private Date getStartOfToday() {
        Calendar today = new GregorianCalendar();
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        today.set(Calendar.MILLISECOND, 0);
        return today.getTime();
    }
 
    public int getProgressValue(long totalBytes, long currentBytes) {
        if (totalBytes == -1) {
            return 0;
        }
        return (int) (currentBytes * 100 / totalBytes);
    }
 
    private String getSizeText(long totalBytes) {
        String sizeText = "";
        if (totalBytes >= 0) {
            sizeText = Formatter.formatFileSize(mContext, totalBytes);
        }
        return sizeText;
    }
 
    private int getStatusStringId(int status) {
        switch (status) {
        case DownloadManager.STATUS_FAILED:
            return R.string.download_error;
 
        case DownloadManager.STATUS_SUCCESSFUL:
            return R.string.download_success;
 
        case DownloadManager.STATUS_PENDING:
            return 0;
 
        case DownloadManager.STATUS_RUNNING:
            return R.string.download_running;
 
        case DownloadManager.STATUS_PAUSED:
            if (mCursor.getInt(mReasonColumnId) == DownloadManager.PAUSED_QUEUED_FOR_WIFI) {
                return R.string.download_queued;
            } else {
                return R.string.download_paused;
            }
        }
        throw new IllegalStateException("Unknown status: "
                + mCursor.getInt(mStatusColumnId));
    }
 
    private void setTextForView(View parent, int textViewId, String text) {
        TextView view = (TextView) parent.findViewById(textViewId);
        view.setText(text);
    }
 
    private boolean isPausedForWifi(Cursor cursor) {
        return cursor.getInt(mReasonColumnId) == DownloadManager.PAUSED_QUEUED_FOR_WIFI;
    }
 
    private Map<String, VideoInfo> mVideoInfos;
 
    private void getVideoDetail(Context context, long downloadId,
            final View convertView) {
        final ImageView iconView = (ImageView) convertView
                .findViewById(R.id.iv_cover);
        Cursor cursor = context.getContentResolver().query(
                DownloadTable.CONTENT_URI, null,
                DownloadTable.TASK_ID + " = ? ",
                new String[] { String.valueOf(downloadId) }, null);
        if (cursor.moveToFirst()) {
            String videoDetailId = cursor.getString(cursor
                    .getColumnIndexOrThrow(DownloadTable.VIDEO_DETAIL_ID));
 
            convertView.setTag(videoDetailId);
            VideoInfo videoInfo = mVideoInfos.get(videoDetailId);
            if (videoInfo != null) {
                // imageLoader.displayImage(videoInfo.getPicture(), iconView,
                // options);
                try {
                    glide.load(videoInfo.getPicture())
                            .placeholder(R.drawable.ic_default_cover)
                            .error(R.drawable.ic_default_cover)
                            .into(iconView);
                }catch (IllegalArgumentException e){
                    e.printStackTrace();
                }
            } else {
                String videoInfoStr = cursor.getString(cursor
                        .getColumnIndexOrThrow(DownloadTable.VIDEO_DETAIL));
                Gson gson = new GsonBuilder().setFieldNamingPolicy(
                        FieldNamingPolicy.UPPER_CAMEL_CASE).create();
                videoInfo = gson.fromJson(videoInfoStr,
                        new TypeToken<VideoInfo>() {
                        }.getType());
                if (videoInfo != null) {
                    mVideoInfos.put(videoDetailId, videoInfo);
                    if (convertView.getTag().equals(videoDetailId)) {
//                        imageLoader.displayImage(videoInfo.getPicture(),
//                                iconView, options);
                        glide.load(videoInfo.getPicture())
                                .placeholder(R.drawable.ic_default_cover)
                                .error(R.drawable.ic_default_cover)
                                .into(iconView);
                    }
                }
            }
        }
        cursor.close();
    }
 
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.download_item, parent, false);
        return view;
    }
 
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        bindView(context, view);
    }
 
    public List<Long> getSelectedIds() {
        return mSelectedIds;
    }
 
    public boolean isSelectedMode() {
        return mSelectedMode;
    }
 
    public void setSelectedMode(boolean selectedMode) {
        this.mSelectedMode = selectedMode;
        if (getselectstatus != null) {
            getselectstatus.onGetStatus(mSelectedMode);
        }
        notifyDataSetChanged();
    }
 
    public Map<String, VideoInfo> getVideoInfos() {
        return mVideoInfos;
    }
 
    public void selectAll(boolean isSelected) {
        mSelectedIds.clear();
        if (isSelected) {
            if (mCursor.moveToFirst()) {
                do {
                    mSelectedIds.add(mCursor.getLong(mIdColumnId));
                } while (mCursor.moveToNext());
            }
        } else {
            if (mCursor.moveToFirst()) {
                do {
                    mSelectedIds.remove(mCursor.getLong(mIdColumnId));
                } while (mCursor.moveToNext());
            }
        }
        if (getdeleteNumber != null)
            getdeleteNumber.onGetNum(mSelectedIds.size());
        notifyDataSetChanged();
    }
}