· 8 years ago · Aug 04, 2018, 03:02 PM
1public class DownloadManagerActivity extends AppCompatActivity {
2
3 static String TAG = "rrDebug";
4
5 private DownloadManagerAdapter adapter;
6
7 public List<DownloadManagerModel> data_list;
8
9 @Override
10 protected void onCreate(Bundle savedInstanceState) {
11 super.onCreate(savedInstanceState);
12 setContentView(R.layout.activity_download_manager);
13
14 final ListView listView = (ListView) findViewById(R.id.dlmng_listview);
15
16 //recyclerView.setLayoutManager(new LinearLayoutManager(this));
17 //recyclerView.setAdapter(adapter = new DownloadManagerAdapter());
18
19 DownloadManager.getImpl().onCreate(new WeakReference<>(this));
20 data_list = DownloadManager.getImpl().itemList;
21 listView.setAdapter(adapter);
22 }
23
24 public void postNotifyDataChanged() {
25 if (adapter != null) {
26 runOnUiThread(new Runnable() {
27 @Override
28 public void run() {
29 if (adapter != null) {
30 adapter.notifyDataSetChanged();
31 }
32 }
33 });
34 }
35 }
36
37 @Override
38 protected void onDestroy() {
39 DownloadManager.getImpl().onDestroy();
40 adapter = null;
41 FileDownloader.getImpl().pauseAll();
42 super.onDestroy();
43 }
44
45 private AlertDialog AskForDeleteAll()
46 {
47 AlertDialog mDeleteAllDialogBox =new AlertDialog.Builder(this)
48 //set message, title, and icon
49 .setTitle("Delete All Videos")
50 .setMessage("This action is not reversible, you will all your downloaded videos permanently. Are you sure want to proceed ?")
51 .setIcon(R.drawable.ic_delete)
52
53 .setPositiveButton("Delete All", new DialogInterface.OnClickListener() {
54
55 public void onClick(DialogInterface dialog, int whichButton) {
56 //your deleting code
57 dialog.dismiss();
58 }
59
60 })
61
62 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
63 public void onClick(DialogInterface dialog, int which) {
64
65 dialog.dismiss();
66
67 }
68 })
69 .create();
70 return mDeleteAllDialogBox;
71 }
72
73
74 // ====== controller ====
75
76 public static class DownloadManager {
77
78 private final static class HolderClass {
79 private final static DownloadManager INSTANCE
80 = new DownloadManager();
81 }
82
83 public static DownloadManager getImpl() {
84 return HolderClass.INSTANCE;
85 }
86
87 private TasksManagerDBController dbController;
88 private List<DownloadManagerModel> itemList;
89
90 public DownloadManager() {
91 dbController = new TasksManagerDBController();
92 itemList = dbController.getAllTasks();
93 }
94
95 private void initDemo() {
96 if (itemList.size() <= 0) {
97 final int demoSize = Constant.BIG_FILE_URLS.length;
98 for (int i = 0; i < demoSize; i++) {
99 final String url = Constant.BIG_FILE_URLS[i];
100 addTask(url);
101 }
102 }
103 }
104
105 private SparseArray<BaseDownloadTask> taskSparseArray = new SparseArray<>();
106
107 public void addTaskForViewHolder(final BaseDownloadTask task) {
108 taskSparseArray.put(task.getId(), task);
109 }
110
111 public void removeTaskForViewHolder(final int id) {
112 taskSparseArray.remove(id);
113 }
114
115 public void updateViewHolder(final int id, final DownloadManagerAdapter.ViewHolder holder) {
116 final BaseDownloadTask task = taskSparseArray.get(id);
117 if (task == null) {
118 return;
119 }
120
121 task.setTag(holder);
122 }
123
124 public void releaseTask() {
125 taskSparseArray.clear();
126 }
127
128 private FileDownloadConnectListener listener;
129
130 private void registerServiceConnectionListener(final WeakReference<DownloadManagerActivity>
131 activityWeakReference) {
132 if (listener != null) {
133 FileDownloader.getImpl().removeServiceConnectListener(listener);
134 }
135
136 listener = new FileDownloadConnectListener() {
137
138 @Override
139 public void connected() {
140 if (activityWeakReference == null
141 || activityWeakReference.get() == null) {
142 return;
143 }
144
145 activityWeakReference.get().postNotifyDataChanged();
146 }
147
148 @Override
149 public void disconnected() {
150 if (activityWeakReference == null
151 || activityWeakReference.get() == null) {
152 return;
153 }
154
155 activityWeakReference.get().postNotifyDataChanged();
156 }
157 };
158
159 FileDownloader.getImpl().addServiceConnectListener(listener);
160 }
161
162 private void unregisterServiceConnectionListener() {
163 FileDownloader.getImpl().removeServiceConnectListener(listener);
164 listener = null;
165 }
166
167 public void onCreate(final WeakReference<DownloadManagerActivity> activityWeakReference) {
168 if (!FileDownloader.getImpl().isServiceConnected()) {
169 FileDownloader.getImpl().bindService();
170 registerServiceConnectionListener(activityWeakReference);
171 }
172 }
173
174 public void onDestroy() {
175 unregisterServiceConnectionListener();
176 releaseTask();
177 }
178
179 public boolean isReady() {
180 return FileDownloader.getImpl().isServiceConnected();
181 }
182
183 public DownloadManagerModel get(final int position) {
184 return itemList.get(position);
185 }
186
187 public DownloadManagerModel getById(final int id) {
188 for (DownloadManagerModel model : itemList) {
189 if (model.getId() == id) {
190 return model;
191 }
192 }
193
194 return null;
195 }
196
197 // Check if download item already exist by "NAME"
198 public boolean isExistAlready(final String name) {
199 for (DownloadManagerModel model : itemList) {
200 if (model.getName().equals(name)) {
201 return true;
202 }
203 }
204
205 return false;
206 }
207
208 /**
209 * @param status Download Status
210 * @return has already downloaded
211 */
212 public boolean isDownloaded(final int status) {
213 return status == FileDownloadStatus.completed;
214 }
215
216 public int getStatus(final int id, String path) {
217 return FileDownloader.getImpl().getStatus(id, path);
218 }
219
220 public long getTotal(final int id) {
221 return FileDownloader.getImpl().getTotal(id);
222 }
223
224 public long getSoFar(final int id) {
225 return FileDownloader.getImpl().getSoFar(id);
226 }
227
228 public int getTaskCounts() {
229 return itemList.size();
230 }
231
232 public DownloadManagerModel addTask(final String name, final String url) {
233 return addTask(name, url, createPath(url));
234 }
235
236 public DownloadManagerModel addTask(final String name, final String url, final String path) {
237 if (TextUtils.isEmpty(url) || TextUtils.isEmpty(path)) {
238 return null;
239 }
240
241 final int id = FileDownloadUtils.generateId(url, path);
242 DownloadManagerModel model = getById(id);
243 if (model != null) {
244 return model;
245 }
246 final DownloadManagerModel newModel = dbController.addTask(name, url, path);
247 if (newModel != null) {
248 itemList.add(newModel);
249 }
250
251 return newModel;
252 }
253
254 public String createPath(final String url) {
255 if (TextUtils.isEmpty(url)) {
256 return null;
257 }
258
259 return FileDownloadUtils.getDefaultSaveFilePath(url);
260 }
261 }
262
263 private static class TasksManagerDBController {
264 public final static String TABLE_NAME = "DownloadManager";
265 private final SQLiteDatabase db;
266
267 private TasksManagerDBController() {
268 DownloadManagerDBOpenHelper openHelper = new DownloadManagerDBOpenHelper(MyApplication.getInstance().getContext());
269
270 db = openHelper.getWritableDatabase();
271 }
272
273 public List<DownloadManagerModel> getAllTasks() {
274 final Cursor c = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
275
276 final List<DownloadManagerModel> list = new ArrayList<>();
277 try {
278 if (!c.moveToLast()) {
279 return list;
280 }
281
282 do {
283 DownloadManagerModel model = new DownloadManagerModel();
284 model.setId(c.getInt(c.getColumnIndex(DownloadManagerModel.ID)));
285 model.setName(c.getString(c.getColumnIndex(DownloadManagerModel.NAME)));
286 model.setUrl(c.getString(c.getColumnIndex(DownloadManagerModel.URL)));
287 model.setPath(c.getString(c.getColumnIndex(DownloadManagerModel.PATH)));
288 list.add(model);
289 } while (c.moveToPrevious());
290 } finally {
291 if (c != null) {
292 c.close();
293 }
294 }
295
296 return list;
297 }
298
299 public DownloadManagerModel addTask(final String name, final String url, final String path) {
300 if (TextUtils.isEmpty(url) || TextUtils.isEmpty(path)) {
301 return null;
302 }
303
304 // have to use FileDownloadUtils.generateId to associate DownloadManagerModel with FileDownloader
305 final int id = FileDownloadUtils.generateId(url, path);
306
307 DownloadManagerModel model = new DownloadManagerModel();
308 model.setId(id);
309 model.setName(MyApplication.getInstance().getContext().getString(R.string.dlmng_item_name, name));
310 model.setUrl(url);
311 model.setPath(path);
312
313 final boolean succeed = db.insert(TABLE_NAME, null, model.toContentValues()) != -1;
314 return succeed ? model : null;
315 }
316
317
318 }
319
320 // ----------------------- model
321 private static class DownloadManagerDBOpenHelper extends SQLiteOpenHelper {
322 public final static String DATABASE_NAME = "DownloadManager.db";
323 public final static int DATABASE_VERSION = 1;
324
325 public DownloadManagerDBOpenHelper(Context context) {
326 super(context, DATABASE_NAME, null, DATABASE_VERSION);
327 }
328
329
330 @Override
331 public void onCreate(SQLiteDatabase db) {
332 db.execSQL("CREATE TABLE IF NOT EXISTS "
333 + TasksManagerDBController.TABLE_NAME
334 + String.format(
335 "("
336 + "%s INTEGER PRIMARY KEY, " // id, download id
337 + "%s VARCHAR, " // name
338 + "%s VARCHAR, " // url
339 + "%s VARCHAR " // path
340 + ")"
341 , DownloadManagerModel.ID
342 , DownloadManagerModel.NAME
343 , DownloadManagerModel.URL
344 , DownloadManagerModel.PATH
345
346 ));
347 }
348
349 @Override
350 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
351 //if (oldVersion == 1 && newVersion == 2) {
352 // db.delete(TasksManagerDBController.TABLE_NAME, null, null);
353 //}
354 }
355 }
356
357 public static class DownloadManagerModel {
358 public final static String ID = "id";
359 public final static String NAME = "name";
360 public final static String URL = "url";
361 public final static String PATH = "path";
362
363 private int id;
364 private String name;
365 private String url;
366 private String path;
367
368 public int getId() {
369 return id;
370 }
371
372 public void setId(int id) {
373 this.id = id;
374 }
375
376 public String getName() {
377 return name;
378 }
379
380 public void setName(String name) {
381 this.name = name;
382 }
383
384 public String getUrl() {
385 return url;
386 }
387
388 public void setUrl(String url) {
389 this.url = url;
390 }
391
392 public String getPath() {
393 return path;
394 }
395
396 public void setPath(String path) {
397 this.path = path;
398 }
399
400 public ContentValues toContentValues() {
401 ContentValues cv = new ContentValues();
402 cv.put(ID, id);
403 cv.put(NAME, name);
404 cv.put(URL, url);
405 cv.put(PATH, path);
406 return cv;
407 }
408 }
409
410
411 }