下面列出了android.app.DownloadManager#STATUS_SUCCESSFUL 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** Check first, if map is finished, or on pending status register receiver. **/
private static void broadcastReceiverCheck(Activity activity,
final MyMap myMap,
final StatusUpdate stUpdate,
final long enqueueId)
{
int preStatus = getDownloadStatus(activity, enqueueId);
if (preStatus == DownloadManager.STATUS_SUCCESSFUL)
{
stUpdate.logUserThread("Unzipping: " + myMap.getMapName());
unzipBg(activity, myMap, stUpdate);
return;
}
else if (preStatus == DownloadManager.STATUS_FAILED)
{
DownloadMapActivity.clearDlFile(myMap);
stUpdate.logUserThread("Error post-downloading map: " + myMap.getMapName());
}
else
{
stUpdate.onRegisterBroadcastReceiver(activity, myMap, enqueueId);
}
}
@Override
public synchronized boolean isDownloadComplete(long dmid) {
//Need to check first if the download manager service is enabled
if(!isDownloadManagerEnabled())
return false;
Query query = new Query();
query.setFilterById(dmid);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int status = c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS));
c.close();
return (status == DownloadManager.STATUS_SUCCESSFUL);
}
c.close();
return false;
}
@Override
protected List<Layer> doInBackground(Layer... layers) {
List<Layer> layersToDownload = new ArrayList<>();
for (Layer layer : layers) {
Long downloadId = layer.getDownloadId();
if (downloadId == null) {
layersToDownload.add(layer);
} else {
DownloadManager.Query ImageDownloadQuery = new DownloadManager.Query();
ImageDownloadQuery.setFilterById(downloadId);
try(Cursor cursor = downloadManager.query(ImageDownloadQuery)) {
int status = getDownloadStatus(cursor);
if (status == DownloadManager.STATUS_SUCCESSFUL) {
loadGeopackage(downloadId, null);
} else {
layersToDownload.add(layer);
}
}
}
}
return layersToDownload;
}
public static void download(Context context, String url, String title) {
long downloadId = SPUtils.getLong(DOWNLOAD_ID, -1L);
if (downloadId != -1L) {
ApkDownloadManager apkDownloadManager = ApkDownloadManager.getInstance(context);
int status = apkDownloadManager.getDownloadStatus(downloadId);
if (status == DownloadManager.STATUS_SUCCESSFUL) {
//启动更新界面
Uri uri = apkDownloadManager.getDownloadUri(downloadId);
if (uri != null) {
if (compare(getApkInfo(context, uri.getPath()))) {
startInstall(context, uri);
return;
} else {
apkDownloadManager.getDownloadManager().remove(downloadId);
}
}
start(context, url, title);
} else if (status == DownloadManager.STATUS_FAILED) {
start(context, url, title);
} else {
Log.d(TAG, "apk is already downloading");
}
} else {
start(context, url, title);
}
}
@PhonkMethod(description = "Downloads a file from a given Uri. Returns the progress", example = "")
public void downloadWithSystemManager(String url, final ReturnInterface callback) {
final DownloadManager dm = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
final long enqueue = dm.enqueue(request);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
if (callback != null) callback.event(null);
// callback successful
}
}
}
}
};
getContext().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Override
public void onReceive(Context context, Intent intent) {
final DownloadManager dm = (DownloadManager) context.getSystemService(
Context.DOWNLOAD_SERVICE);
Long downloadingTaskId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
if (NetworkManagerUtil.downloadingTaskQueue.containsKey(downloadingTaskId)) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadingTaskId);
Cursor cursor = dm.query(query);
// retrieve downloaded content's information through download manager.
if (!cursor.moveToFirst()) {
return;
}
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
!= DownloadManager.STATUS_SUCCESSFUL) {
return;
}
String path = cursor.getString(
cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
final DownloadingTaskDescription desc =
NetworkManagerUtil.downloadingTaskQueue.get(downloadingTaskId);
// update local storage path
desc.setStoragePath(path);
for (final DownloadCompleteListener listener: downloadingCompletionListener) {
listener.onDownloadingCompleted(desc);
}
}
}
/**
* @return true if progress was checked successfully
*/
private boolean checkProgress() {
final Cursor cursor = manager.query(new DownloadManager.Query());
if (!cursor.moveToFirst()) {
cursor.close();
return false;
}
if (downloadId == -1)
downloadId = BPrefs.get(this).getLong(BPrefs.LAST_DOWNLOAD_MANAGER_REQUEST_ID, -1);
if (downloadId == -1)
return false;
do {
final long reference = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
if (reference == downloadId) {
final int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL)
return true;
final long progress = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
final long progressMax = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
final int intProgress = (int) ((progress * 100.0) / ((double) progressMax));
pb.setProgress(intProgress);
return true;
}
} while (cursor.moveToNext());
cursor.close();
return false;
}
@Override
public void onReceive(Context context, Intent intent) {
final DownloadManager dm = (DownloadManager) context.getSystemService(
Context.DOWNLOAD_SERVICE);
Long downloadingTaskId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
if (NetworkManagerUtil.downloadingTaskQueue.containsKey(downloadingTaskId)) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadingTaskId);
Cursor cursor = dm.query(query);
// retrieve downloaded content's information through download manager.
if (!cursor.moveToFirst()) {
return;
}
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
!= DownloadManager.STATUS_SUCCESSFUL) {
return;
}
String path = cursor.getString(
cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
final DownloadingTaskDescription desc =
NetworkManagerUtil.downloadingTaskQueue.get(downloadingTaskId);
// update local storage path
desc.setStoragePath(path);
for (final DownloadCompleteListener listener: downloadingCompletionListener) {
listener.onDownloadingCompleted(desc);
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
final long downloadedId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
final DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadedId);
final Cursor cursor = mDownloadManager.query(query);
if (cursor.moveToFirst() &&
DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(
cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
mIds.remove(downloadedId);
if (mIds.isEmpty()) {
Global.getInstance().getBus()
.post(new MSNEvent<>(MSNEvent.DOWNLOAD_COMPLETE, true));
}
} else {
for (Long id : mIds) {
mDownloadManager.remove(id);
}
Global.getInstance().getBus()
.post(new MSNEvent<>(MSNEvent.DOWNLOAD_COMPLETE, false));
}
}
@Override
public void onReceive(Context context, Intent intent) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadRef);
Cursor c = downloadManager.query(q);
if (c != null && c.moveToFirst()) {
dlStatus = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
long refId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (refId == downloadRef && dlStatus == DownloadManager.STATUS_SUCCESSFUL) {
SystemClock.sleep(5000);
waitDialog.dismiss();
generateHash();
}
}
}
protected String statusMessage(Cursor c, int bytesDownloaded) {
String msg;
switch (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
case DownloadManager.STATUS_FAILED:
msg = "Download failed: " + bytesDownloaded + " bytes downloaded.";
break;
case DownloadManager.STATUS_PAUSED:
msg = "Download paused: " + bytesDownloaded + " bytes downloaded.";
break;
case DownloadManager.STATUS_PENDING:
msg = "Download pending: " + bytesDownloaded + " bytes downloaded.";
break;
case DownloadManager.STATUS_RUNNING:
msg = "Download in progress: " + bytesDownloaded + " bytes downloaded.";
break;
case DownloadManager.STATUS_SUCCESSFUL:
msg = "Download complete: " + bytesDownloaded + " bytes downloaded.";
break;
default:
msg = "STATUS MESSAGE ERROR";
break;
}
return (msg);
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(idDownloadedFile);
Cursor c = downloadManager.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
//get the url
String pictureUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
// Create the URI from the media
File media = new File(Uri.parse(pictureUri).getPath());
Uri uri = Uri.fromFile(media);
//to share
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, getString(R.string.share)));
//reset
idDownloadedFile = -1;
}
}
}
}
public boolean wasSuccessful() {
return DownloadManager.STATUS_SUCCESSFUL == mStatus;
}
public boolean wasSuccessful() {
return DownloadManager.STATUS_SUCCESSFUL == mStatus;
}
@Override
public DownloadQueryResult doInBackground(Void... voids) {
DownloadManager manager =
(DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor c = manager.query(
new DownloadManager.Query().setFilterById(mDownloadItem.getSystemDownloadId()));
if (c == null) {
return new DownloadQueryResult(mDownloadItem,
DownloadManagerService.DOWNLOAD_STATUS_CANCELLED, 0, 0, false, 0);
}
long bytesDownloaded = 0;
boolean canResolve = false;
int downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_IN_PROGRESS;
int failureReason = 0;
long lastModifiedTime = 0;
if (c.moveToNext()) {
int statusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_COMPLETE;
DownloadInfo.Builder builder = mDownloadItem.getDownloadInfo() == null
? new DownloadInfo.Builder()
: DownloadInfo.Builder.fromDownloadInfo(
mDownloadItem.getDownloadInfo());
builder.setFileName(
c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE)));
mDownloadItem.setDownloadInfo(builder.build());
if (mShowNotifications) {
canResolve = DownloadManagerService.isOMADownloadDescription(
mDownloadItem.getDownloadInfo())
|| DownloadManagerService.canResolveDownloadItem(
mContext, mDownloadItem, false);
}
} else if (status == DownloadManager.STATUS_FAILED) {
downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_FAILED;
failureReason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
}
lastModifiedTime =
c.getLong(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP));
bytesDownloaded =
c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
} else {
downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_CANCELLED;
}
c.close();
long totalTime = Math.max(0, lastModifiedTime - mDownloadItem.getStartTime());
return new DownloadQueryResult(mDownloadItem, downloadStatus, totalTime,
bytesDownloaded, canResolve, failureReason);
}
/**
* Sets the right status icon when the app is currently downloading or has downloaded an APK.
* @param info The object containing the information about the download.
* @param ctx The context of the application.
* @return Whether an icon was set.
*/
private boolean _set_action_icon_download(final DownloadInfo info, final Context ctx)
{
switch (info.get_status())
{
case DownloadManager.STATUS_SUCCESSFUL: // APK was downloaded. Install on click.
final File apk = new File(Uri.parse(info.get_local_uri()).getPath());
if (apk.exists())
{
_action_icon.setImageDrawable(ContextCompat.getDrawable(ctx, R.drawable.install));
_action_icon.setVisibility(View.VISIBLE);
_action_icon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW);
Uri apk_uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
{
// Starting from Android N, file:// ACTION_VIEW intents can no longer be passed to other apps.
apk_uri = FileProvider.getUriForFile(ctx, BuildConfig.APPLICATION_ID + ".provider", apk);
}
else
{
// However, it seems that no system component handles content://[...].apk in previous
// versions, which is why the URI is still passed the old way here.
apk_uri = Uri.parse(info.get_local_uri());
}
i.setDataAndType(apk_uri, "application/vnd.android.package-archive");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (i.resolveActivity(ctx.getPackageManager()) != null) {
ctx.startActivity(i);
}
else
{
Log.v(MainActivity.TAG, "Could not find anyone to receive ACTION_VIEW for " +
"the downloaded APK. (" + info.get_local_uri() + ")");
}
}
});
return true;
}
else { // For some reason the APK is not present anymore. Remove the download information.
return false;
}
case DownloadManager.STATUS_PENDING:
case DownloadManager.STATUS_RUNNING:
_action_icon.setImageDrawable(ContextCompat.getDrawable(ctx, android.R.drawable.stat_sys_download));
// Fix the icon color for the white background.
_action_icon.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
((Animatable) _action_icon.getDrawable()).start();
_action_icon.setVisibility(View.VISIBLE);
return true;
default:
return false;
}
}
/**
* 检查下载状态
*/
private void checkStatus(Context context) {
DownloadManager.Query query = new DownloadManager.Query();
//通过下载的id查找
query.setFilterById(downloadId);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
//下载暂停
case DownloadManager.STATUS_PAUSED:
break;
//下载延迟
case DownloadManager.STATUS_PENDING:
break;
//正在下载
case DownloadManager.STATUS_RUNNING:
break;
//下载完成
case DownloadManager.STATUS_SUCCESSFUL:
//下载完成安装APK
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "ency.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
context.startActivity(intent);
break;
//下载失败
case DownloadManager.STATUS_FAILED:
Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
break;
}
}
c.close();
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void queryDownloadStatus() {
DownloadManager.Query query = new DownloadManager.Query()
.setFilterById(mRequestId);
Cursor cursor = null;
try {
cursor = mDownloadManager.query(query);
if (cursor != null && cursor.moveToFirst()) {
// 已经下载的字节数
long currentBytes = cursor
.getLong(cursor
.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
// 总需下载的字节数
long totalBytes = cursor
.getLong(cursor
.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
// 状态所在的列索引
int status = cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_STATUS));
tv_download.setText("下载中...(" + formatKMGByBytes(currentBytes)
+ "/" + formatKMGByBytes(totalBytes) + ")");
// 将当前下载的字节数转化为进度位置
int progress = (int) ((currentBytes * 1.0) / totalBytes * 100);
progressBar_download.setProgress(progress);
Log.i("downloadUpdate: ", currentBytes + " " + totalBytes + " "
+ status + " " + progress);
if (DownloadManager.STATUS_SUCCESSFUL == status
&& tv_download.getVisibility() == View.VISIBLE) {
tv_download.setVisibility(View.GONE);
tv_download.performClick();
if (isLocalExist()) {
tv_download.setVisibility(View.GONE);
displayFile();
}
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public DownloadQueryResult doInBackground(Void... voids) {
DownloadManager manager =
(DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor c = manager.query(
new DownloadManager.Query().setFilterById(mDownloadItem.getSystemDownloadId()));
if (c == null) {
return new DownloadQueryResult(mDownloadItem,
DownloadManagerService.DOWNLOAD_STATUS_CANCELLED, 0, 0, false, 0);
}
long bytesDownloaded = 0;
boolean canResolve = false;
int downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_IN_PROGRESS;
int failureReason = 0;
long lastModifiedTime = 0;
if (c.moveToNext()) {
int statusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_COMPLETE;
if (mShowNotifications) {
canResolve = DownloadManagerService.isOMADownloadDescription(
mDownloadItem.getDownloadInfo())
|| DownloadManagerService.canResolveDownloadItem(
mContext, mDownloadItem, false);
}
} else if (status == DownloadManager.STATUS_FAILED) {
downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_FAILED;
failureReason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
}
lastModifiedTime =
c.getLong(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP));
bytesDownloaded =
c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
} else {
downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_CANCELLED;
}
c.close();
long totalTime = Math.max(0, lastModifiedTime - mDownloadItem.getStartTime());
return new DownloadQueryResult(mDownloadItem, downloadStatus, totalTime,
bytesDownloaded, canResolve, failureReason);
}
public boolean wasSuccessful() {
return DownloadManager.STATUS_SUCCESSFUL == mStatus;
}