Skip to content

Commit

Permalink
init download
Browse files Browse the repository at this point in the history
  • Loading branch information
LightSun committed Mar 12, 2020
1 parent b5be371 commit e343db2
Show file tree
Hide file tree
Showing 20 changed files with 896 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Android-Download/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
1 change: 1 addition & 0 deletions Android-Download/and_download/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
33 changes: 33 additions & 0 deletions Android-Download/and_download/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
group='com.github.LightSun'

android {
compileSdkVersion 28
buildToolsVersion "28.0.3"

defaultConfig {
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.heaven7.java.base:Java-base:1.2.0'
}
21 changes: 21 additions & 0 deletions Android-Download/and_download/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
7 changes: 7 additions & 0 deletions Android-Download/and_download/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.heaven7.android.download" >

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
package com.heaven7.android.download;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;

import androidx.collection.LongSparseArray;

import com.heaven7.java.base.util.Predicates;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
* the download helper use the system download manager to download
* @author heaven7
*/
public final class DownloadHelper {

public final static int STATUS_PENDING = DownloadManager.STATUS_PENDING;
public final static int STATUS_RUNNING = DownloadManager.STATUS_RUNNING;
public final static int STATUS_PAUSED = DownloadManager.STATUS_PAUSED;
public final static int STATUS_SUCCESSFUL = DownloadManager.STATUS_SUCCESSFUL;
public final static int STATUS_FAILED = DownloadManager.STATUS_FAILED;

private final LongSparseArray<Params> mCallbacks = new LongSparseArray<>();
private final DownloadManager mDM;
private final Context mContext;

public DownloadHelper(Context context) {
this.mContext = context.getApplicationContext();
this.mDM = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
}
public long download(DownloadTask task, IDownloadCallback callback) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(task.getUrl()));
request.setDestinationUri(Uri.fromFile(new File(task.getSavePath())));

callback.onPreDownload(mContext,task, request);

long id = mDM.enqueue(request);
task.setId(id);
mCallbacks.put(id, new Params(task, callback));
return id;
}
public boolean cancel(long id){
mCallbacks.remove(id);
return mDM.remove(id) > 0;
}
public void removeCallback(long id){
mCallbacks.remove(id);
}
public void registerDownloadReceiver(){
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
filter.addAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
mContext.registerReceiver(mReceiver, filter);
}
public void unregisterDownloadReceiver(){
try {
mContext.unregisterReceiver(mReceiver);
}catch (Exception e){
//ignore
}
}
public List<Long> getDownloadIds(){
int size = mCallbacks.size();
if(size == 0){
return Collections.emptyList();
}
List<Long> keys = new ArrayList<>();
for (int i = 0 ; i < size ; i ++){
keys.add(mCallbacks.keyAt(i));
}
return keys;
}

public void queryAll() {
List<Long> list = getDownloadIds();
if(!Predicates.isEmpty(list)){
queryAll(list);
}
}

public void queryAll(List<Long> ids) {
for (Long id: ids){
if(!query(id, null)){
System.out.println("Download : >> query download failed. id = " + id);
}
}
}

public boolean query(long id, Integer downloadFlags){
return query(id, downloadFlags, true);
}
public DownloadTask queryAny(long id, Integer downloadFlags){
DownloadTask task = new DownloadTask();
task.setId(id);
if(query0(id, downloadFlags, task)){
return task;
}
return null;
}
private boolean query(long id, Integer downloadFlags, boolean callback){
Params params = mCallbacks.get(id);
if(params == null){
return false;
}
if(query0(id, downloadFlags, params.task)){
if(callback){
params.callback.onQueryResult(mContext, params.task);
}
return true;
}
return false;
}
private boolean query0(long id, Integer downloadFlags, DownloadTask task){
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(id);
if(downloadFlags != null){
query.setFilterByStatus(downloadFlags);
}
Cursor cursor = mDM.query(query);
try {
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
long totalBytes = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
long alreadyBytes = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
String reason = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
long lastModifyTime = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP));
String uriStr = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

task.setTotalBytes(totalBytes);
task.setDownloadBytes(alreadyBytes);
task.setLastModifyTime(lastModifyTime);
task.setReason(reason);
task.setStatus(status);
task.setUri(Uri.parse(uriStr));
return true;
}
}finally {
cursor.close();
}
return false;
}
private void dispatchNotificationClicked(long id){
Params params = mCallbacks.get(id);
if(params == null){
return;
}
query(id, null, false);
params.callback.onNotificationClicked(mContext, params.task);
}
private void dispatchViewDownload(long id){
Params params = mCallbacks.get(id);
if(params == null){
return;
}
params.callback.startViewDownload(mContext, params.task);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())){
query(id, null);
}else if(DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())){
long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
if(ids != null){
for (long lid : ids){
dispatchNotificationClicked(lid);
}
}else {
dispatchNotificationClicked(id);
}
}else if(DownloadManager.ACTION_VIEW_DOWNLOADS.equals(intent.getAction())){
dispatchViewDownload(id);
}
}
};
private static class Params{
final DownloadTask task;
final IDownloadCallback callback;

Params(DownloadTask task, IDownloadCallback callback) {
this.task = task;
this.callback = callback;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.heaven7.android.download;

public class DownloadQueryParameter {

private long id;
private String name;
private int state;

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package com.heaven7.android.download;

import android.net.Uri;

public class DownloadTask {

private String url;
private String savePath;
private long id;

private long totalBytes; // init is -1
private long downloadBytes;
private String mediaType; // may be null
private String reason;
private long lastModifyTime; // in mills
private int status; // download state
private Uri uri;

public Uri getUri() {
return uri;
}
public void setUri(Uri uri) {
this.uri = uri;
}

public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}

public long getLastModifyTime() {
return lastModifyTime;
}

public void setLastModifyTime(long lastModifyTime) {
this.lastModifyTime = lastModifyTime;
}

public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}

public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}

public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}

public long getTotalBytes() {
return totalBytes;
}

public void setTotalBytes(long totalBytes) {
this.totalBytes = totalBytes;
}

public long getDownloadBytes() {
return downloadBytes;
}

public void setDownloadBytes(long downloadBytes) {
this.downloadBytes = downloadBytes;
}

public String getMediaType() {
return mediaType;
}

public void setMediaType(String mediaType) {
this.mediaType = mediaType;
}
}
Loading

0 comments on commit e343db2

Please sign in to comment.