Java Code Examples for android.app.DownloadManager#remove()

The following examples show how to use android.app.DownloadManager#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DownloadsUtil.java    From EdXposedManager with GNU General Public License v3.0 6 votes vote down vote up
private static void removeAllForUrl(Context context, String url) {
    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = dm.query(new Query());
    int columnId = c.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
    int columnUri = c.getColumnIndexOrThrow(DownloadManager.COLUMN_URI);

    List<Long> idsList = new ArrayList<>(1);
    while (c.moveToNext()) {
        if (url.equals(c.getString(columnUri)))
            idsList.add(c.getLong(columnId));
    }
    c.close();

    if (idsList.isEmpty())
        return;

    long[] ids = new long[idsList.size()];
    for (int i = 0; i < ids.length; i++)
        ids[i] = idsList.get(i);

    dm.remove(ids);
}
 
Example 2
Source File: SplashActivity.java    From pokemon-go-xposed-mitm with GNU General Public License v3.0 6 votes vote down vote up
private void storeDownload(DownloadManager dm, long downloadId) {
    try {
        android.os.ParcelFileDescriptor file = dm.openDownloadedFile(downloadId);
        java.io.InputStream fileStream = new java.io.FileInputStream(file.getFileDescriptor());
        java.io.FileOutputStream fos = openFileOutput(RUBOTO_APK, MODE_WORLD_READABLE);
        byte[] buffer = new byte[1024];
        int length;
        while((length = fileStream.read(buffer)) > 0) {
            fos.write(buffer, 0, length);
        }
        fos.flush();
        fileStream.close();
        fos.close();
        dm.remove(downloadId);
        enqueue = 0;
    } catch (java.io.IOException ioe) {
        Log.e("Exception copying RubotoCore: " + ioe);
        Toast.makeText(this, "Exception copying RubotoCore: " + ioe, Toast.LENGTH_LONG).show();
    }
}
 
Example 3
Source File: OMADownloadHandler.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
protected void onPostExecute(Boolean success) {
    DownloadManager manager =
            (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    if (success) {
        String path = mDownloadInfo.getFilePath();
        if (!TextUtils.isEmpty(path)) {
            // Move the downloaded content from the app directory to public directory.
            File fromFile = new File(path);
            String fileName = fromFile.getName();
            File toFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS), fileName);
            if (fromFile.renameTo(toFile)) {
                manager.addCompletedDownload(
                        fileName, mDownloadInfo.getDescription(), false,
                        mDownloadInfo.getMimeType(), toFile.getPath(),
                        mDownloadInfo.getContentLength(), true);
            } else if (fromFile.delete()) {
                Log.w(TAG, "Failed to rename the file.");
                return;
            } else {
                Log.w(TAG, "Failed to rename and delete the file.");
            }
        }
        showNextUrlDialog(mOMAInfo);
    } else if (mDownloadId != DownloadItem.INVALID_DOWNLOAD_ID) {
        // Remove the downloaded content.
        manager.remove(mDownloadId);
    }
}
 
Example 4
Source File: InstalledApp.java    From ApkTrack with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Deletes the APK which may have been downloaded by the app.
 * @param ctx The context of the application.
 */
public void clean_downloads(Context ctx)
{
    if (get_download_id() == 0) {
        return;
    }

    DownloadManager dm = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
    dm.remove(get_download_id());
    set_download_id(0);
    save();
    Log.v(MainActivity.TAG, get_display_name() + "'s APK cleaned.");
}
 
Example 5
Source File: DownloadManagerDelegate.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Removes a download from Android DownloadManager.
 * @param downloadGuid The GUID of the download.
 */
void removeCompletedDownload(String downloadGuid) {
    long downloadId = removeDownloadIdMapping(downloadGuid);
    if (downloadId != INVALID_SYSTEM_DOWNLOAD_ID) {
        DownloadManager manager =
                (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        manager.remove(downloadId);
    }
}
 
Example 6
Source File: OMADownloadHandler.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
protected void onPostExecute(Boolean success) {
    DownloadManager manager =
            (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    if (success) {
        String path = mDownloadInfo.getFilePath();
        if (!TextUtils.isEmpty(path)) {
            // Move the downloaded content from the app directory to public directory.
            File fromFile = new File(path);
            String fileName = fromFile.getName();
            File toFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS), fileName);
            if (fromFile.renameTo(toFile)) {
                manager.addCompletedDownload(
                        fileName, mDownloadInfo.getDescription(), false,
                        mDownloadInfo.getMimeType(), toFile.getPath(),
                        mDownloadInfo.getBytesReceived(), true);
            } else if (fromFile.delete()) {
                Log.w(TAG, "Failed to rename the file.");
                return;
            } else {
                Log.w(TAG, "Failed to rename and delete the file.");
            }
        }
        showNextUrlDialog(mOMAInfo);
    } else if (mDownloadId != DownloadItem.INVALID_DOWNLOAD_ID) {
        // Remove the downloaded content.
        manager.remove(mDownloadId);
    }
}
 
Example 7
Source File: DownloadReceiver.java    From nono-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {

    DownloadManager manager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
    if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())){
        DownloadManager.Query query = new DownloadManager.Query();
        //在广播中取出下载任务的id
        long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
        query.setFilterById(id);
        Cursor c = manager.query(query);
        if(c.moveToFirst()) {
            //获取文件下载路径
            String filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
            //如果文件名不为空,说明已经存在了,拿到文件名想干嘛都好
            if(filename != null){
                File file  = new File(filename);
                Intent anotherIntent = new Intent();
                anotherIntent.addFlags(anotherIntent.FLAG_ACTIVITY_NEW_TASK);
                anotherIntent.setAction(android.content.Intent.ACTION_VIEW);
                anotherIntent.setDataAndType(Uri.fromFile(file),
                        "application/vnd.android.package-archive");
                context.startActivity(anotherIntent);
            }
        }
    }else if(DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())){
        long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
        //点击通知栏取消下载
        manager.remove(ids);
        //ShowToastUtil.showShortToast(context, "已经取消下载");
    }

}
 
Example 8
Source File: DownloadManagerDelegate.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Removes a download from Android DownloadManager.
 * @param downloadGuid The GUID of the download.
 */
void removeCompletedDownload(String downloadGuid) {
    long downloadId = removeDownloadIdMapping(downloadGuid);
    if (downloadId != INVALID_SYSTEM_DOWNLOAD_ID) {
        DownloadManager manager =
                (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        manager.remove(downloadId);
    }
}
 
Example 9
Source File: OMADownloadHandler.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
protected void onPostExecute(Boolean success) {
    DownloadManager manager =
            (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    if (success) {
        String path = mDownloadInfo.getFilePath();
        if (!TextUtils.isEmpty(path)) {
            // Move the downloaded content from the app directory to public directory.
            File fromFile = new File(path);
            String fileName = fromFile.getName();
            File toFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS), fileName);
            if (fromFile.renameTo(toFile)) {
                manager.addCompletedDownload(
                        fileName, mDownloadInfo.getDescription(), false,
                        mDownloadInfo.getMimeType(), toFile.getPath(),
                        mDownloadInfo.getContentLength(), true);
            } else if (fromFile.delete()) {
                Log.w(TAG, "Failed to rename the file.");
                return;
            } else {
                Log.w(TAG, "Failed to rename and delete the file.");
            }
        }
        showNextUrlDialog(mOMAInfo);
    } else if (mDownloadId != DownloadItem.INVALID_DOWNLOAD_ID) {
        // Remove the downloaded content.
        manager.remove(mDownloadId);
    }
}
 
Example 10
Source File: DownloadManagerService.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<Integer, Boolean> doInBackground(Void...voids) {
    DownloadManager manager =
            (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = manager.query(new DownloadManager.Query().setFilterById(
            mDownloadItem.getSystemDownloadId()));
    int statusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
    int reasonIndex = c.getColumnIndex(DownloadManager.COLUMN_REASON);
    int titleIndex = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
    int status = DownloadManager.STATUS_FAILED;
    Boolean canResolve = false;
    if (c.moveToNext()) {
        status = c.getInt(statusIndex);
        String title = c.getString(titleIndex);
        if (mDownloadInfo == null) {
            // Chrome has been killed, reconstruct a DownloadInfo.
            mDownloadInfo = new DownloadInfo.Builder()
                    .setFileName(title)
                    .setDescription(c.getString(
                            c.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION)))
                    .setMimeType(c.getString(
                            c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE)))
                    .setContentLength(Long.parseLong(c.getString(
                            c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))))
                    .build();
        }
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            mDownloadInfo = DownloadInfo.Builder.fromDownloadInfo(mDownloadInfo)
                    .setFileName(title)
                    .build();
            mDownloadItem.setDownloadInfo(mDownloadInfo);
            canResolve = canResolveDownloadItem(mContext, mDownloadItem, false);
        } else if (status == DownloadManager.STATUS_FAILED) {
            mFailureReason = c.getInt(reasonIndex);
            manager.remove(mDownloadItem.getSystemDownloadId());
        }
    }
    c.close();
    return Pair.create(status, canResolve);
}
 
Example 11
Source File: DownloadsUtil.java    From EdXposedManager with GNU General Public License v3.0 5 votes vote down vote up
public static DownloadInfo getById(Context context, long id) {
    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = dm.query(new Query().setFilterById(id));
    if (!c.moveToFirst()) {
        c.close();
        return null;
    }

    int columnUri = c.getColumnIndexOrThrow(DownloadManager.COLUMN_URI);
    int columnTitle = c.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE);
    int columnLastMod = c.getColumnIndexOrThrow(
            DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP);
    int columnLocalUri = c.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI);
    int columnStatus = c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
    int columnTotalSize = c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
    int columnBytesDownloaded = c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
    int columnReason = c.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON);

    int status = c.getInt(columnStatus);
    String localFilename;
    try {
        localFilename = getFilenameFromUri(c.getString(columnLocalUri));
    } catch (UnsupportedOperationException e) {
        Toast.makeText(context, "An error occurred. Restart app and try again.\n" + e.getMessage(), Toast.LENGTH_SHORT).show();
        return null;
    }
    if (status == DownloadManager.STATUS_SUCCESSFUL && !new File(localFilename).isFile()) {
        dm.remove(id);
        c.close();
        return null;
    }

    DownloadInfo info = new DownloadInfo(id, c.getString(columnUri),
            c.getString(columnTitle), c.getLong(columnLastMod),
            localFilename, status,
            c.getInt(columnTotalSize), c.getInt(columnBytesDownloaded),
            c.getInt(columnReason));
    c.close();
    return info;
}
 
Example 12
Source File: RxDownloader.java    From RxDownloader with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0L);
    PublishSubject<String> publishSubject = subjectMap.get(id);

    if (publishSubject == null)
        return;

    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(id);
    DownloadManager downloadManager = getDownloadManager();
    Cursor cursor = downloadManager.query(query);

    if (!cursor.moveToFirst()) {
        cursor.close();
        downloadManager.remove(id);
        publishSubject.onError(new IllegalStateException("Cursor empty, this shouldn't happened"));
        subjectMap.remove(id);
        return;
    }

    int statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
    if (DownloadManager.STATUS_SUCCESSFUL != cursor.getInt(statusIndex)) {
        cursor.close();
        downloadManager.remove(id);
        publishSubject.onError(new IllegalStateException("Download Failed"));
        subjectMap.remove(id);
        return;
    }

    int uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
    String downloadedPackageUriString = cursor.getString(uriIndex);
    cursor.close();

    publishSubject.onNext(downloadedPackageUriString);
    publishSubject.onComplete();
    subjectMap.remove(id);
}
 
Example 13
Source File: DownloadMaster.java    From uPods-android with Apache License 2.0 5 votes vote down vote up
public void cancelDownload(String itemName) {
    DownloadManager downloadManager = (DownloadManager) UpodsApplication.getContext().getSystemService(Context.DOWNLOAD_SERVICE);
    DownloadTask task = getTaskByName(itemName);
    task.progressUpdater = null;
    downloadManager.remove(task.downloadId);
    allTasks.remove(task);
    Logger.printInfo(DM_LOG, "Task for item name: " + itemName + " canceled ");
}
 
Example 14
Source File: PlayerAdapter.java    From IdealMedia with Apache License 2.0 5 votes vote down vote up
private static void stopDownload(Context context, TrackViewHolder holder) {
    final DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.remove(holder.track.downloadID);

    holder.track.isDownloadInAction = false;
    holder.downloadProgress.setProgress(0);
    holder.downloadProgress.setVisibility(View.GONE);
}
 
Example 15
Source File: UpdateAppReceiver.java    From TvPlayer with Apache License 2.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    // 处理下载完成
    Cursor c = null;

    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
        if (DownloadAppUtils.downloadUpdateApkId >= 0) {
            long downloadId = DownloadAppUtils.downloadUpdateApkId;
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            DownloadManager downloadManager = (DownloadManager) context
                    .getSystemService(Context.DOWNLOAD_SERVICE);
            c = downloadManager.query(query);
            if (c.moveToFirst()) {
                int status = c.getInt(c
                        .getColumnIndex(DownloadManager.COLUMN_STATUS));
                if (status == DownloadManager.STATUS_FAILED) {
                    downloadManager.remove(downloadId);

                } else if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    if (DownloadAppUtils.downloadUpdateApkFilePath != null) {
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        File apkFile = new File(DownloadAppUtils.downloadUpdateApkFilePath);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            Uri contentUri = FileProvider.getUriForFile(
                                    context, context.getPackageName() + ".fileprovider", apkFile);
                            i.setDataAndType(contentUri, "application/vnd.android.package-archive");
                        } else {
                            i.setDataAndType(Uri.fromFile(apkFile),
                                    "application/vnd.android.package-archive");
                        }
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(i);
                    }
                }
            }
            c.close();
        }
    }


}
 
Example 16
Source File: DownloadProgressActivity.java    From IslamicLibraryAndroid with GNU General Public License v3.0 4 votes vote down vote up
@Nullable
@Override
protected DownloadInfoUpdate doInBackground(Void... voids) {
    //Convert Long[] to long[]

    while (true) {

        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Query BooksDownloadQuery = new DownloadManager.Query();

        BooksDownloadQuery.setFilterByStatus(DownloadManager.STATUS_RUNNING |
                DownloadManager.STATUS_PAUSED |
                DownloadManager.STATUS_PENDING);

        //Query the download manager about downloads that have been requested.
        Cursor cursor = downloadManager.query(BooksDownloadQuery);
        int progressingDownloadCount = cursor.getCount();

        List<DownloadInfo> progressDownloadInfo = new ArrayList<>();
        if (progressingDownloadCount != 0) {
            for (int i = 0; i < progressingDownloadCount; i++) {
                cursor.moveToPosition(i);
                DownloadInfo downloadInfo = new DownloadInfo(cursor);
                progressDownloadInfo.add(i, downloadInfo);
                Log.d("download_iter", downloadInfo.toString());
            }
            Collections.sort(progressDownloadInfo, (o1, o2) -> {
                if (o1.getProgressPercent() != 0 && o2.getProgressPercent() != 0) {
                    return o1.compareTo(o2);
                } else if (o1.getProgressPercent() != 0 && o2.getProgressPercent() == 0) {
                    return -1;

                } else if (o1.getProgressPercent() == 0 && o2.getProgressPercent() != 0) {
                    return 1;

                } else //(o1.getProgressPercent() == 0 && o2.getProgressPercent() == 0)
                {
                    return o1.compareTo(o2);
                }

            });
        }
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(
                new DownloadInfo.DownloadInfoDiffCallback(mOldDownloadList, progressDownloadInfo));
        mOldDownloadList = progressDownloadInfo;
        cursor.close();


        if (progressingDownloadCount != 0) {
            publishProgress(new DownloadInfoUpdate(progressDownloadInfo, diffResult));
        } else {
            return new DownloadInfoUpdate(progressDownloadInfo, diffResult);
        }

        if (isCancelled()) {
            publishProgress(new DownloadInfoUpdate(DownloadInfoUpdate.TYPE_CANCEL));
            DownloadManager.Query non_complete_query = new DownloadManager.Query();
            non_complete_query.setFilterByStatus(DownloadManager.STATUS_FAILED |
                    DownloadManager.STATUS_PENDING |
                    DownloadManager.STATUS_RUNNING);
            Cursor c = downloadManager.query(non_complete_query);
            int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_ID);
            //TODO this loop may cause problems if a download completed and the broadcast is triggered before we cancel it
            while (c.moveToNext()) {
                long enquId = c.getLong(columnIndex);
                downloadManager.remove(enquId);
            }
            DownloadProgressActivity.this.cancelMultipleDownloads(c, columnIndex);
            Intent localIntent =
                    new Intent(BROADCAST_ACTION)
                            .putExtra(EXTRA_NOTIFY_WITHOUT_BOOK_ID, true);
            DownloadProgressActivity.this.sendOrderedBroadcast(localIntent, null);
            c.close();

            return null;
        }
        try {
            Thread.sleep(40);
        } catch (InterruptedException e) {
            Timber.e(e);
        }
    }
}
 
Example 17
Source File: OMADownloadHandler.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
public Pair<Integer, Boolean> doInBackground(Void... voids) {
    DownloadManager manager =
            (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = manager.query(
            new DownloadManager.Query().setFilterById(mDownloadItem.getSystemDownloadId()));
    int statusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
    int reasonIndex = c.getColumnIndex(DownloadManager.COLUMN_REASON);
    int titleIndex = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
    int status = DownloadManager.STATUS_FAILED;
    Boolean canResolve = false;
    if (c.moveToNext()) {
        status = c.getInt(statusIndex);
        String title = c.getString(titleIndex);
        if (mDownloadInfo == null) {
            // Chrome has been killed, reconstruct a DownloadInfo.
            mDownloadInfo =
                    new DownloadInfo.Builder()
                            .setFileName(title)
                            .setDescription(c.getString(
                                    c.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION)))
                            .setMimeType(c.getString(
                                    c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE)))
                            .setBytesReceived(Long.parseLong(c.getString(c.getColumnIndex(
                                    DownloadManager.COLUMN_TOTAL_SIZE_BYTES))))
                            .build();
        }
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            mDownloadInfo = DownloadInfo.Builder.fromDownloadInfo(mDownloadInfo)
                                    .setFileName(title)
                                    .build();
            mDownloadItem.setDownloadInfo(mDownloadInfo);
            canResolve = DownloadManagerService.canResolveDownloadItem(
                    mContext, mDownloadItem, false);
        } else if (status == DownloadManager.STATUS_FAILED) {
            mFailureReason = c.getInt(reasonIndex);
            manager.remove(mDownloadItem.getSystemDownloadId());
        }
    }
    c.close();
    return Pair.create(status, canResolve);
}
 
Example 18
Source File: DownloadNewVersionJob.java    From WayHoo with Apache License 2.0 4 votes vote down vote up
@Override
public Void run(JobContext jc) {
	try {
		if (checkDownloadRunning())
			return null;
		if (checkApkExist()) {
			Intent installApkIntent = new Intent();
			installApkIntent.setAction(Intent.ACTION_VIEW);
			installApkIntent.setDataAndType(
					Uri.parse(Preferences.getDownloadPath(mContext)),
					"application/vnd.android.package-archive");
			installApkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
			mContext.startActivity(installApkIntent);
		} else {
			String apkName = mContext.getPackageName()
					+ System.currentTimeMillis() + Constants.APK_SUFFIX;
			// 系统下载程序
			final DownloadManager downloadManager = (DownloadManager) mContext
					.getSystemService(mContext.DOWNLOAD_SERVICE);

			Long recommendedMaxBytes = DownloadManager
					.getRecommendedMaxBytesOverMobile(mContext);

			// 可以在移动网络下下载
			if (recommendedMaxBytes == null
					|| recommendedMaxBytes.longValue() > MAX_ALLOWED_DOWNLOAD_BYTES_BY_MOBILE) {
				allowMobileDownload = true;
			}

			Uri uri = Uri.parse(mUpgradeInfo.getUrl());

			final Request request = new Request(uri);

			request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
			request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

			int NETWORK_TYPE = DownloadManager.Request.NETWORK_WIFI;
			if (allowMobileDownload) {
				NETWORK_TYPE |= DownloadManager.Request.NETWORK_MOBILE;
			}
			request.setAllowedNetworkTypes(NETWORK_TYPE);
			request.allowScanningByMediaScanner();
			request.setShowRunningNotification(true);
			request.setVisibleInDownloadsUi(true);
			request.setDestinationInExternalPublicDir(
					Environment.DIRECTORY_DOWNLOADS, apkName);
			PackageManager packageManager = mContext.getPackageManager();
			ApplicationInfo applicationInfo = packageManager
					.getApplicationInfo(mContext.getPackageName(), 0);
			Log.i("liweiping",
					"appName = "
							+ packageManager
									.getApplicationLabel(applicationInfo));
			request.setTitle(packageManager
					.getApplicationLabel(applicationInfo));
			request.setMimeType("application/vnd.android.package-archive");

			// id 保存起来跟之后的广播接收器作对比
			long id = downloadManager.enqueue(request);

			long oldId = Preferences.getDownloadId(mContext);
			if (oldId != -1) {
				downloadManager.remove(oldId);
			}

			Preferences.removeAll(mContext);
			Preferences.setDownloadId(mContext, id);
			Preferences.setUpgradeInfo(mContext, mUpgradeInfo);
			Preferences.setDownloadStatus(mContext,
					Constants.DOWNLOAD_STATUS_RUNNING);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 19
Source File: DownloadsUtil.java    From EdXposedManager with GNU General Public License v3.0 4 votes vote down vote up
public static void removeById(Context context, long id) {
    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    dm.remove(id);
}
 
Example 20
Source File: DownloadsUtil.java    From EdXposedManager with GNU General Public License v3.0 4 votes vote down vote up
private static List<DownloadInfo> getAllForUrl(Context context, String url) {
    DownloadManager dm = (DownloadManager) context
            .getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = dm.query(new Query());
    int columnId = c.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
    int columnUri = c.getColumnIndexOrThrow(DownloadManager.COLUMN_URI);
    int columnTitle = c.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE);
    int columnLastMod = c.getColumnIndexOrThrow(
            DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP);
    int columnLocalUri = c.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI);
    int columnStatus = c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
    int columnTotalSize = c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
    int columnBytesDownloaded = c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
    int columnReason = c.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON);

    List<DownloadInfo> downloads = new ArrayList<>();
    while (c.moveToNext()) {
        if (!url.equals(c.getString(columnUri)))
            continue;

        int status = c.getInt(columnStatus);
        String localFilename;
        try {
            localFilename = getFilenameFromUri(c.getString(columnLocalUri));
        } catch (UnsupportedOperationException e) {
            Toast.makeText(context, "An error occurred. Restart app and try again.\n" + e.getMessage(), Toast.LENGTH_SHORT).show();
            return null;
        }
        if (status == DownloadManager.STATUS_SUCCESSFUL && !new File(localFilename).isFile()) {
            dm.remove(c.getLong(columnId));
            continue;
        }

        downloads.add(new DownloadInfo(c.getLong(columnId),
                c.getString(columnUri), c.getString(columnTitle),
                c.getLong(columnLastMod), localFilename,
                status, c.getInt(columnTotalSize),
                c.getInt(columnBytesDownloaded), c.getInt(columnReason)));
    }
    c.close();

    Collections.sort(downloads);
    return downloads;
}