/** * Called to open a given download item that is downloaded by the android DownloadManager. * @param context Context of the receiver. * @param intent Intent from the android DownloadManager. */ private void openDownload(final Context context, Intent intent) { long ids[] = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS); if (ids == null || ids.length == 0) { DownloadManagerService.openDownloadsPage(context); return; } long id = ids[0]; Uri uri = DownloadManagerDelegate.getContentUriFromDownloadManager(context, id); if (uri == null) { // Open the downloads page DownloadManagerService.openDownloadsPage(context); } else { String downloadFilename = IntentUtils.safeGetStringExtra( intent, DownloadNotificationService.EXTRA_DOWNLOAD_FILE_PATH); boolean isSupportedMimeType = IntentUtils.safeGetBooleanExtra( intent, DownloadNotificationService.EXTRA_IS_SUPPORTED_MIME_TYPE, false); Intent launchIntent = DownloadManagerService.getLaunchIntentFromDownloadId( context, downloadFilename, id, isSupportedMimeType); if (!DownloadUtils.fireOpenIntentForDownload(context, launchIntent)) { DownloadManagerService.openDownloadsPage(context); } } }
private void downloadAndInstall(String url) { final DownloadManager dManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse(url); DownloadManager.Request request = new DownloadManager.Request(uri); request.setDestinationInExternalPublicDir("zmtmt", "zmtmt_zhibohao_update"); request.setDescription(getString(R.string.new_version_download)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.allowScanningByMediaScanner(); } request.setMimeType("application/vnd.android.package-archive"); request.setVisibleInDownloadsUi(true); final long reference = dManager.enqueue(request); IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); upgradeReceiver = new UpgradeBroadcastReceiver(dManager, reference); registerReceiver(upgradeReceiver, filter); }
@Override public Cursor queryChildDocumentsForManage( String parentDocumentId, String[] projection, String sortOrder) throws FileNotFoundException { final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection)); // Delegate to real provider final long token = Binder.clearCallingIdentity(); Cursor cursor = null; try { cursor = mDm.query( new DownloadManager.Query());//.setOnlyIncludeVisibleInDownloadsUi(true)); //copyNotificationUri(result, cursor); while (cursor.moveToNext()) { includeDownloadFromCursor(result, cursor); } } finally { IoUtils.closeQuietly(cursor); Binder.restoreCallingIdentity(token); } return result; }
@Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { listener.onDownloadStart(); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setMimeType(mimetype); //------------------------COOKIE!!------------------------ CookieManager.getInstance().setCookie(url, getCookie()); String cookiesAlt = CookieManager.getInstance().getCookie(url); request.addRequestHeader(Constant.COOKIE, cookiesAlt); //------------------------COOKIE!!------------------------ request.addRequestHeader(Constant.USER_AGENT, userAgent); request.setDescription(activity.getString(R.string.downloading_file)); request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype)); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype)); DownloadManager dm = (DownloadManager) activity.getSystemService(activity.DOWNLOAD_SERVICE); try { dm.enqueue(request); activity.showToast(R.string.downloading_file); } catch (Exception e) { activity.showToast(R.string.download_failed); } }
public static void loadPoems(final Context context, final MainPresenter presenter) { File poems_file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "poems.json"); File poems_old_file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "poems_old.json"); if (poems_file.exists()) { poems_file.renameTo(poems_old_file); } String url = "https://almoturg.com/poems.json"; DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setDescription("Sprog poems"); request.setTitle("Sprog"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, "poems.json"); // get download service and enqueue file DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); receiver = new BroadcastReceiver() { public void onReceive(Context ctxt, Intent intent) { if (intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) != downloadID){return;} context.unregisterReceiver(PoemsLoader.receiver); PoemsLoader.receiver = null; presenter.downloadComplete(); } }; context.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); downloadID = manager.enqueue(request); }
public static void cancelAllDownloads(Context context){ if (receiver != null) { context.unregisterReceiver(receiver); receiver = null; } DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Query query = new DownloadManager.Query(); query.setFilterByStatus( DownloadManager.STATUS_FAILED|DownloadManager.STATUS_PAUSED| DownloadManager.STATUS_PENDING|DownloadManager.STATUS_RUNNING); Cursor cur = manager.query(query); while (cur.moveToNext()){ manager.remove(cur.getLong(cur.getColumnIndex(DownloadManager.COLUMN_ID))); } cur.close(); }
private void removeOldDownloads(Context context) { try { Log.i(TAG, "Removing the old downloads in progress of the previous keyboard version."); final DownloadManagerWrapper downloadManagerWrapper = new DownloadManagerWrapper( context); final DownloadManager.Query q = new DownloadManager.Query(); // Query all the download statuses except the succeeded ones. q.setFilterByStatus(DownloadManager.STATUS_FAILED | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING); final Cursor c = downloadManagerWrapper.query(q); if (c != null) { for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { final long downloadId = c .getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)); downloadManagerWrapper.remove(downloadId); Log.i(TAG, "Removed the download with Id: " + downloadId); } c.close(); } } catch (Exception e) { Log.e(TAG, "Exception while removing old downloads."); } }
public WritableMap checkDownloadStatus(long downloadId) { DownloadManager.Query downloadQuery = new DownloadManager.Query(); downloadQuery.setFilterById(downloadId); Cursor cursor = downloadManager.query(downloadQuery); HashMap<String, String> result = new HashMap<>(); if (cursor.moveToFirst()) { result = getDownloadStatus(cursor, downloadId); } else { result.put("status", "UNKNOWN"); result.put("reason", "COULD_NOT_FIND"); result.put("downloadId", String.valueOf(downloadId)); } WritableMap wmap = new WritableNativeMap(); for (HashMap.Entry<String, String> entry : result.entrySet()) { wmap.putString(entry.getKey(), entry.getValue()); } return wmap; }
private void downloadByDownloadManager() { DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(APK_URL)); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "支付宝.apk"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setTitle("通过DownloadManager下载APK"); request.setDescription("简单的演示一下DownloadManager的使用方法"); request.allowScanningByMediaScanner(); downloadId = manager.enqueue(request); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); if (id == downloadId) { ToastUtils.showShortToast("下载完成"); } } }, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); }
@Override public Cursor queryChildDocuments(String docId, String[] projection, String sortOrder) throws FileNotFoundException { final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection)); // Delegate to real provider final long token = Binder.clearCallingIdentity(); Cursor cursor = null; try { Query query = new Query(); DownloadManagerUtils.setOnlyIncludeVisibleInDownloadsUi(query); //query.setOnlyIncludeVisibleInDownloadsUi(true); query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL); //query.setFilterByStatus(DownloadManager.STATUS_PENDING | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_FAILED); cursor = mDm.query(query);//.setOnlyIncludeVisibleInDownloadsUi(true) //.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL)); //copyNotificationUri(result, cursor); while (cursor.moveToNext()) { includeDownloadFromCursor(result, cursor); } } finally { IoUtils.closeQuietly(cursor); Binder.restoreCallingIdentity(token); } return result; }
@Override protected Void doInBackground(String... params) { Uri location = Uri.parse(Utils.BASE_URL_PHP + params[0].substring(1)); String filename = params[0].substring(params[0].lastIndexOf('/') + 1); DownloadManager downloadManager = (DownloadManager) Utils.getContext().getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(location); request.setTitle(filename); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDescription(Utils.getString(R.string.download_description_news)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) request.setDestinationInExternalFilesDir(Utils.getContext(), Environment.DIRECTORY_DOCUMENTS, filename); else request.setDestinationInExternalFilesDir(Utils.getContext(), Environment.DIRECTORY_DOWNLOADS, filename); downloadManager.enqueue(request); return null; }
@SuppressLint("NewApi") public void onReceive(Context context, Intent intent) { long downLoadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); long cacheDownLoadId = PreferencesUtils.getLong(context,"download_id"); if(DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())){ DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); long downloadId = PreferencesUtils.getLong(context,"download_id"); downloader.remove(downloadId); //eventbus 关闭dialog UpdataEvent updataEvent = new UpdataEvent(); updataEvent.setResult("close dialog"); updataEvent.setState(0); EventBus.getDefault().post(updataEvent); }else if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction()) && cacheDownLoadId == downLoadId) { try { Intent install = new Intent(Intent.ACTION_VIEW); File apkFile = queryDownloadedApk(context); install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(install); }catch (Exception e){ } } }
@Override public DownloadTask download(String url, String filePath) { Uri uri = Uri.parse(url); DownloadManager.Request request = new DownloadManager.Request(uri); //设置允许使用的网络类型,这里是移动网络和wifi都可以 request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); //禁止发出通知,既后台下载,如果要使用这一句必须声明一个权限: // android.permission.DOWNLOAD_WITHOUT_NOTIFICATION //request.setShowRunningNotification(false); //不显示下载界面 request.setVisibleInDownloadsUi(false); File dstFile = new File(filePath); request.setDestinationInExternalFilesDir(mContext , dstFile.getParent() , dstFile.getName()); long id = mDownloadManager.enqueue(request); mDownloadList.add(id); DownloadTask task = new DownloadTask(id, url , filePath , 0 ,0 , System.currentTimeMillis()); task.setDownloaderType(DownloaderFactory.TYPE_SYSTEM_DOWNLOAD); return task; }
/** * 点击下载 */ public void onClickUpdate() { if (mDownloadId != 0) {//downloadID不为默认值,表示存在下载任务 int status = DownloadUtils.queryDownloadStatus(mContext, mDownloadId); Log.e("TAG", status + ""); switch (status) { case DownloadManager.STATUS_RUNNING://下载中 DownloadToast.showShort(mContext, "正在下载,请稍后"); break; case DownloadManager.STATUS_FAILED://下载失败 startDownApk();//重新开始下载 break; case DownloadManager.STATUS_SUCCESSFUL://下载成功 installApk(); break; default: break; } } else {//无下载任务,开始下载 startDownApk(); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); receiver = new MyReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("clicked"); filter.addAction("download has been paused"); filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE); this.registerReceiver(receiver, filter); bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.launcher512_qihoo); pendingIntent = PendingIntent.getBroadcast( this, 1, new Intent().setAction("clicked"), PendingIntent.FLAG_UPDATE_CURRENT); manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); }
/** * Downloads a file using DownloadManager. */ public static void downloadFile(Context context, String url, String fileName) { DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(url)); downloadRequest.setTitle(fileName); // in order for this if to run, you must use the android 3.2 to compile your app if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { downloadRequest.allowScanningByMediaScanner(); downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(downloadRequest); }
private static void descargar(Context context, URL url) { downloadManager = (DownloadManager)context.getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url.toString())); String APK = new File(url.getPath()).getName(); request.setTitle(APK); // Guardar archivo if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,APK); } // Iniciamos la descarga id = downloadManager.enqueue(request); }
@Override public void onReceive(Context context, Intent intent) { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(id, 0); Cursor cursor = downloadManager.query(query); if(cursor.moveToFirst()) { int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)); int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)); if(status == DownloadManager.STATUS_SUCCESSFUL) { // Si la descarga es correcta abrimos el archivo para instalarlo String uriString = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)).replace("file://", ""); OpenNewVersion(context, uriString); } else if(status == DownloadManager.STATUS_FAILED) { Toast.makeText(context,context.getString(R.string.appupdater_download_filed) + reason,Toast.LENGTH_LONG).show(); } } }
/** * 开始下载APK */ private void startDownload(String downUrl) { Log.i(TAG, "startDownload: "); //获得系统下载器 mManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); //设置下载地址 DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downUrl)); // 设置允许使用的网络类型,这里是移动网络和wifi都可以 request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI); request.setAllowedOverRoaming(false); //设置可以被扫描到 request.allowScanningByMediaScanner(); //设置下载文件的类型 request.setMimeType("application/vnd.android.package-archive"); // 显示下载界面 request.setVisibleInDownloadsUi(true); //设置下载存放的文件夹和文件名字 request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName); //设置下载时,通知栏是否显示 request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); //设置标题 request.setTitle(apkName.split("_")[0]); //执行下载,并返回任务唯一id enqueue = mManager.enqueue(request); }
/** * Check the external storage and notify user on error. * * @param fullDirPath The dir path to download a file. Normally this is external storage. * @param externalStorageStatus The status of the external storage. * @return Whether external storage is ok for downloading. */ private boolean checkExternalStorageAndNotify( String filename, File fullDirPath, String externalStorageStatus) { if (fullDirPath == null) { Log.e(TAG, "Download failed: no SD card"); alertDownloadFailure( filename, DownloadManager.ERROR_DEVICE_NOT_FOUND); return false; } if (!externalStorageStatus.equals(Environment.MEDIA_MOUNTED)) { int reason = DownloadManager.ERROR_DEVICE_NOT_FOUND; // Check to see if the SDCard is busy, same as the music app if (externalStorageStatus.equals(Environment.MEDIA_SHARED)) { Log.e(TAG, "Download failed: SD card unavailable"); reason = DownloadManager.ERROR_FILE_ERROR; } else { Log.e(TAG, "Download failed: no SD card"); } alertDownloadFailure(filename, reason); return false; } return true; }
/** * 开始下载 */ private void startDownload(String downUrl) { //获得系统下载器 dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); //设置下载地址 DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downUrl)); //设置下载文件的类型 request.setMimeType("application/vnd.android.package-archive"); //设置下载存放的文件夹和文件名字 request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkname); //设置下载时或者下载完成时,通知栏是否显示 request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setTitle("下载新版本"); //执行下载,并返回任务唯一id enqueue = dm.enqueue(request); }
private void startDownload() { File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "ency.apk"); AppFileUtil.delFile(file, true); // 创建下载任务 DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://ucdl.25pp.com/fs08/2017/09/19/10/2_b51f7cae8d7abbd3aaf323a431826420.apk?sf=9946816&vh=1e3a8680ee88002bdf2f00f715146e16&sh=10&cc=3646561943&appid=7060083&packageid=400525966&md5=27456638a0e6615fb5153a7a96c901bf&apprd=7060083&pkg=com.taptap&vcode=311&fname=TapTap&pos=detail-ndownload-com.taptap")); // 显示下载信息 request.setTitle("Ency"); request.setDescription("新版本下载中"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); request.setMimeType("application/vnd.android.package-archive"); // 设置下载路径 request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "ency.apk"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } // 获取DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); // 将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等等 downloadId = dm.enqueue(request); Toast.makeText(this, "后台下载中,请稍候...", Toast.LENGTH_SHORT).show(); }
private void startDownload() { Snackbar.make(activity.findViewById(R.id.fragment_container), "Downloading started.", Snackbar.LENGTH_SHORT).show(); String path = Environment.getExternalStorageDirectory().toString() + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator + "wulkanowy"; File dir = new File(path); if(!dir.mkdirs()) { for (String aChildren : dir.list()) { new File(dir, aChildren).delete(); } } DownloadManager.Request request = new DownloadManager.Request(Uri.parse(update.getUrlToDownload().toString())) .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE) .setAllowedOverRoaming(false) .setTitle("Wulkanowy v" + update.getLatestVersionCode()) .setDescription(update.getLatestVersion()) .setVisibleInDownloadsUi(true) .setMimeType("application/vnd.android.package-archive") .setDestinationUri(Uri.fromFile(new File(path + File.separator + update.getLatestVersion() + ".apk"))); downloadManager.enqueue(request); }
@Override public void onReceive(Context context, Intent intent) { long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); if (id != -1) { DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(id)); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) != DownloadManager.STATUS_SUCCESSFUL) { String title = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)); Toast.makeText(context, context.getString(R.string.toast_download_failed, title), Toast.LENGTH_SHORT).show(); return; } } ids.remove(id); if (ids.isEmpty()) { getAdapter().notifyItemChanged(getAdapterPosition(), new Object()); context.unregisterReceiver(this); mBroadcastReceiver = null; } } }
private void startDownload(View v, boolean allowDownloadOverMetered) { v.setEnabled(false); List<String> files = FontManager.getFiles(getData(), v.getContext(), true); List<Long> ids = FontManager.download(getData(), files, v.getContext(), allowDownloadOverMetered); mBroadcastReceiver = new DownloadBroadcastReceiver(ids); FontViewHolder.this.itemView.getContext().registerReceiver( mBroadcastReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); }
public static String lavStatustekst(HentetStatus hs) { if (hs.status == DownloadManager.STATUS_SUCCESSFUL) { if (hs.statusFlytningIGang) return App.res.getString(R.string.Flytter__); if (new File(hs.destinationFil).canRead()) return App.res.getString(R.string.Klar___mb_, hs.iAlt); return App.res.getString(R.string._ikke_tilgængelig_); } else if (hs.status == DownloadManager.STATUS_FAILED) { return App.res.getString(R.string.Mislykkedes); } else if (hs.status == DownloadManager.STATUS_PENDING) { return App.res.getString(R.string.Venter___); } else if (hs.status == DownloadManager.STATUS_PAUSED) { return App.res.getString(R.string.Hentning_pauset__) + App.res.getString(R.string.Hentet___mb_af___mb, hs.hentet, hs.iAlt); } // RUNNING if (hs.hentet > 0 || hs.iAlt > 0) return App.res.getString(R.string.Hentet___mb_af___mb, hs.hentet, hs.iAlt); return App.res.getString(R.string.Henter__); }
public DownloadInfo(Cursor cursor) { int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS); status = cursor.getInt(columnIndex); int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON); reason = cursor.getInt(columnReason); int columnBytesDownloadedSoFar = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR); bytesDownloadedSoFar = cursor.getLong(columnBytesDownloadedSoFar); int columnId = cursor.getColumnIndex(DownloadManager.COLUMN_ID); enquId = cursor.getLong(columnId); int columnTitlle = cursor.getColumnIndex(DownloadManager.COLUMN_TITLE); title = cursor.getString(columnTitlle); int columnTimeStamp = cursor.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP); lastModifiedTimestamp = cursor.getLong(columnTimeStamp); int columnTotlalSize = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES); totalSizeBytes = cursor.getLong(columnTotlalSize); }
@StringRes public int getStatusTextResId() { int statusText = 0; switch (status) { case DownloadManager.STATUS_FAILED: statusText = (R.string.STATUS_FAILED); break; case DownloadManager.STATUS_PAUSED: statusText = (R.string.STATUS_PAUSED); break; case DownloadManager.STATUS_PENDING: statusText = (R.string.STATUS_PENDING); break; case DownloadManager.STATUS_RUNNING: statusText = (R.string.STATUS_RUNNING); break; case DownloadManager.STATUS_SUCCESSFUL: statusText = (R.string.STATUS_SUCCESSFUL); break; } return statusText; }
/** * Checks download progress. */ private void checkProgress() { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(enqueue); Cursor cursor = dm.query(query); if (!cursor.moveToFirst()) { cursor.close(); return; } long reference = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)); int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); int progress = (int) ((bytes_downloaded * 100l) / bytes_total); WritableMap writableMap = new WritableNativeMap(); writableMap.putInt("progress", progress); sendEvent(writableMap); if(progress >= 100) { future.cancel(true); } }
private void startDownload(String downloadUrl) { String apkUrl = Constants.setAliyunImageUrl(downloadUrl); String[] arr = apkUrl.split("/"); apkName = arr[arr.length - 1]; DownloadManager downloadManager = (DownloadManager) App.getDefault().getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl)); try { FileUtil.createFolder(downloadPath); } catch (Exception e) { e.printStackTrace(); } request.setDestinationInExternalPublicDir("newVoice", apkName); String title = this.getResources().getString(R.string.app_name); request.setTitle(title); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); downloadManager.enqueue(request); }
@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)); } }
private @Nullable Uri getLocalUriForDownloadId(Context context, long downloadId) { DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadId); Cursor cursor = downloadManager.query(query); try { if (cursor != null && cursor.moveToFirst()) { String localUri = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI)); if (localUri != null) { File localFile = new File(Uri.parse(localUri).getPath()); return Uri.fromFile(localFile); } } } finally { if (cursor != null) cursor.close(); } return null; }
public SystemDownloader(Context context){ mContext = context; mDownloadManager = (DownloadManager) mContext.getSystemService(mContext.DOWNLOAD_SERVICE); mCompleteReceiver = new CompleteReceiver(); mDownloadChangeObserver = new DownloadChangeObserver(null); mCompleteFilter = new IntentFilter( ); mCompleteFilter.addAction("android.intent.action.DOWNLOAD_COMPLETE"); }
ICalendarController(MessagingController controller, DownloadManager downloadManager, MessageViewFragment messageViewFragment, ICalendarViewInfo iCalendar) { this.context = messageViewFragment.getApplicationContext(); this.controller = controller; this.downloadManager = downloadManager; this.messageViewFragment = messageViewFragment; this.iCalendar = iCalendar; }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // This fragments adds options to the action bar setHasOptionsMenu(true); Context context = getActivity().getApplicationContext(); mController = MessagingController.getInstance(context); downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); messageCryptoPresenter = new MessageSecurityPresenter(savedInstanceState, messageSecurityMvpView); messageLoaderHelper = new MessageLoaderHelper(context, getLoaderManager(), getFragmentManager(), messageLoaderCallbacks); mInitialized = true; }
AttachmentController(MessagingController controller, DownloadManager downloadManager, MessageViewFragment messageViewFragment, AttachmentViewInfo attachment) { this.context = messageViewFragment.getApplicationContext(); this.controller = controller; this.downloadManager = downloadManager; this.messageViewFragment = messageViewFragment; this.attachment = attachment; }
private void startDownload() { DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request( Uri.parse(MyApis.APK_DOWNLOAD_URL)); request.setTitle("GeekNews"); request.setDescription("新版本下载中"); request.setMimeType("application/vnd.android.package-archive"); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "geeknews.apk"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } dm.enqueue(request); ToastUtil.shortShow("后台下载中,请稍候..."); }