android.app.DownloadManager Java Examples

The following examples show how to use android.app.DownloadManager. 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: DownloadStorageProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #2
Source File: DownloadBroadcastReceiver.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(final Context context, Intent intent) {
    String action = intent.getAction();
    switch (action) {
        case DownloadManager.ACTION_NOTIFICATION_CLICKED:
            openDownload(context, intent);
            break;
        case DownloadNotificationService.ACTION_DOWNLOAD_RESUME:
        case DownloadNotificationService.ACTION_DOWNLOAD_CANCEL:
        case DownloadNotificationService.ACTION_DOWNLOAD_PAUSE:
        case DownloadNotificationService.ACTION_DOWNLOAD_OPEN:
            performDownloadOperation(context, intent);
            break;
        default:
            break;
    }
}
 
Example #3
Source File: GeoPackageDownloadManager.java    From mage-android with Apache License 2.0 6 votes vote down vote up
public int getProgress(Layer layer) {
    int progress = 0;

    Long downloadId = layer.getDownloadId();
    if (downloadId != null) {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        try (Cursor cursor = downloadManager.query(query)) {

            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                if(columnIndex != -1) {
                    progress = cursor.getInt(columnIndex);
                }
            }
        }
    }

    return progress;
}
 
Example #4
Source File: UiUtils.java    From droidddle with Apache License 2.0 6 votes vote down vote up
public static void downloadFile(Context context, String url, long id) {
        DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.addRequestHeader("droidddle", "1.1");
        File file = getDownloadFile(context, url, id);

        Uri destination = Uri.fromFile(file);
        if (file.exists()) {
            file.delete();
        }
        request.setDestinationUri(destination);
//         request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
//         path);
        request.setNotificationVisibility(
                DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setTitle(file.getName());
        request.setVisibleInDownloadsUi(true);

        long downId = mgr.enqueue(request);
        String tips = context
                .getString(R.string.download_tips, file.getParentFile().getAbsolutePath());
        showToast(context, tips);
    }
 
Example #5
Source File: ChromeDownloadDelegate.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #6
Source File: OSMDownloader.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void pollDownloadManager() {
    while (downloading) {
        DownloadManager.Query q = new DownloadManager.Query();
        q.setFilterById(downloadId);
        Cursor cursor = downloadManager.query(q);
        cursor.moveToFirst();
        final int bytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
        final String msg = PROGRESS_MSG + ((double)bytesDownloaded) / 1000000.0 + " MB";
        publishProgress(msg);
        status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
        statusMessage = statusMessage(cursor, bytesDownloaded);
        Log.d("OSMDownloader", statusMessage);
        if (status != DownloadManager.STATUS_PENDING && status != DownloadManager.STATUS_RUNNING) {
            downloading = false;
        }
        // throttle the thread
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } 
}
 
Example #7
Source File: DownloadInfo.java    From ApkTrack with GNU General Public License v3.0 6 votes vote down vote up
public DownloadInfo(long download_id, Context ctx)
{
    long id = download_id;
    DownloadManager dm = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = dm.query(new DownloadManager.Query().setFilterById(id));
    if (!c.moveToFirst())
    {
        c.close();
        return;
    }

    _last_modified = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP));
    _local_uri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
    _status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
    _reason = c.getString(c.getColumnIndex(DownloadManager.COLUMN_REASON));

    c.close();
    _valid = true;
}
 
Example #8
Source File: DownloadStorageProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: DownloadsReceiver.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	
	if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())) {
		//just open the manage activity
		intent.setClass(context, ManageDownloadsActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		context.startActivity(intent);
	}
	
	else if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
		Bundle extras = intent.getExtras();
		
		// This is the only extra provided.
		long id = extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
		Log.d(LOG_TAG, "Download Complete: " + id);
		
		Intent service = new Intent(context, KADataService.class);
		service.setAction(ACTION_UPDATE_DOWNLOAD_STATUS);
		service.putExtra(EXTRA_ID, id);
		context.startService(service);
	}
}
 
Example #10
Source File: MoodleCourseDetailsFragment.java    From ETSMobile-Android2 with Apache License 2.0 6 votes vote down vote up
/**
 * Downloads an given Moodle item into the user's device.
 * @param item the item to be downloaded.
 */
@NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
void downloadMoodleObject(MoodleModuleContent item) {

    String url = item.getFileurl() + "&token=" + ApplicationManager.userCredentials.getMoodleToken();
    Uri uri = Uri.parse(url);
    DownloadManager.Request request = new DownloadManager.Request(uri);

    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, item.getFilename());

    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    MimeTypeMap mimetype = MimeTypeMap.getSingleton();
    String extension = FilenameUtils.getExtension(item.getFilename());

    request.setMimeType(mimetype.getMimeTypeFromExtension(extension));

    dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
    enqueue = dm.enqueue(request);
}
 
Example #11
Source File: EnvironmentsManager.java    From FirefoxReality with Mozilla Public License 2.0 6 votes vote down vote up
private void downloadEnvironment(@NonNull String envId) {
    final Environment environment = EnvironmentUtils.getExternalEnvironmentById(mContext, envId);
    if (environment != null) {
        // Check if the env is being downloaded
        boolean isDownloading = mDownloadManager.getDownloads().stream()
                .filter(item ->
                        item.getStatus() == DownloadManager.STATUS_RUNNING &&
                                item.getStatus() == DownloadManager.STATUS_PAUSED &&
                                item.getStatus() == DownloadManager.STATUS_PENDING &&
                                item.getUri().equals(environment.getPayload()))
                .findFirst().orElse(null) != null;

        if (!isDownloading) {
            // If the env is not being downloaded, start downloading it
            DownloadJob job = DownloadJob.create(environment.getPayload());
            mDownloadManager.startDownload(job);
        }
    }
}
 
Example #12
Source File: DownloadStorageProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #13
Source File: DownloadsManager.java    From FirefoxReality with Mozilla Public License 2.0 6 votes vote down vote up
public List<Download> getDownloads() {
    List<Download> downloads = new ArrayList<>();

    if (mDownloadManager != null) {
        DownloadManager.Query query = new DownloadManager.Query();
        Cursor c = mDownloadManager.query(query);
        if (c != null) {
            while (c.moveToNext()) {
                downloads.add(Download.from(c));
            }
            c.close();
        }
    }

    return downloads;
}
 
Example #14
Source File: DownloadsManager.java    From FirefoxReality with Mozilla Public License 2.0 6 votes vote down vote up
@Nullable
public Download getDownload(long downloadId) {
    Download download = null;

    if (mDownloadManager != null) {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        Cursor c = mDownloadManager.query(query);
        if (c != null) {
            if (c.moveToFirst()) {
                download = Download.from(c);
            }
            c.close();
        }
    }

    return download;
}
 
Example #15
Source File: ApkInstallReceiver.java    From AndroidUpdater with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
        long downloadApkId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        long localDownloadId = UpdaterUtils.getLocalDownloadId(context);
        if (downloadApkId == localDownloadId) {
            Logger.get().d("download complete. downloadId is " + downloadApkId);
            installApk(context, downloadApkId);
        }
    } else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())) {
        //处理 如果还未完成下载,用户点击Notification
        Intent viewDownloadIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
        viewDownloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(viewDownloadIntent);
    }
}
 
Example #16
Source File: SystemBroadcastReceiver.java    From Android-Keyboard with Apache License 2.0 6 votes vote down vote up
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.");
    }
}
 
Example #17
Source File: FileDisplayActivity.java    From TBSFileBrowsing with Apache License 2.0 6 votes vote down vote up
/**
 * 下载文件
 */
@SuppressLint("NewApi")
private void startDownload() {
    mDownloadObserver = new DownloadObserver(new Handler());
    getContentResolver().registerContentObserver(
            Uri.parse("content://downloads/my_downloads"), true,
            mDownloadObserver);

    mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    //将含有中文的url进行encode
    String fileUrl = toUtf8String(mFileUrl);
    try {

        DownloadManager.Request request = new DownloadManager.Request(
                Uri.parse(fileUrl));
        request.setDestinationInExternalPublicDir(
                Environment.DIRECTORY_DOWNLOADS, mFileName);
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        mRequestId = mDownloadManager.enqueue(request);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #18
Source File: ImageViewerActivity.java    From scallop with MIT License 6 votes vote down vote up
@OnClick(R.id.download_button)
public void downloadImage() {
    String imageUrl = imageUrlList.get(imageViewPager.getCurrentItem());
    String fileName = StringUtils.getImageNameFromUrl(imageUrl);
    String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            .getAbsolutePath() + "/scallop";
    DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imageUrl));
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
            | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false)
            .setTitle(fileName)
            .setNotificationVisibility(
                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalPublicDir(path, fileName);
    downloadManager.enqueue(request);
}
 
Example #19
Source File: IssueDetailsFragment.java    From magpi-android with MIT License 6 votes vote down vote up
public void downloadIssue() {
    if(!this.canDisplayPdf(getActivity())) {
        Toast.makeText(getActivity(), getActivity().getString(R.string.pdf_reader_required), Toast.LENGTH_LONG).show();
        return;
    }
    
    String file = issue.getId() + ".pdf";
    File magPiFolder = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Config.ISSUE_FOLDER);
    magPiFolder.mkdirs();
    File pdf = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Config.ISSUE_FOLDER, file);
    if(pdf.exists() && !isDownloading(issue.getPdfUrl())) {
        Intent intentPdf = new Intent(Intent.ACTION_VIEW);
        intentPdf.setDataAndType(Uri.fromFile(pdf), "application/pdf");
        startActivity(intentPdf);
    } else if (!isDownloading(issue.getPdfUrl())) {
    	menu.findItem(R.id.menu_view).setVisible(false);
    	menu.findItem(R.id.menu_cancel_download).setVisible(true);
        Request request = new Request(Uri.parse(issue.getPdfUrl()));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.setTitle(getActivity().getString(R.string.app_name) + " n�" + issue.getId());
        request.setDescription(getActivity().getString(R.string.download_text) + " n�" + issue.getId());
        request.setDestinationInExternalPublicDir(Config.ISSUE_FOLDER, file);
        dm.enqueue(request);
    }
}
 
Example #20
Source File: UpdatesActivity.java    From BaldPhone with Apache License 2.0 6 votes vote down vote up
/**
 * @param versionNumber version number
 * @return true if download was started;
 */
public boolean downloadApk(final int versionNumber) {
    if (manager == null)
        return false;

    downloadingToast.show();
    deleteCurrentUpdateFile();

    final Uri uri =
            Uri.parse(baldUpdateObject.apkUrl);
    final DownloadManager.Request request =
            new DownloadManager.Request(uri)
                    .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, FILENAME)
                    .setAllowedOverRoaming(true)
                    .setAllowedOverMetered(true)
                    .setDescription(getText(R.string.downloading_updates));

    downloadId = manager.enqueue(request);

    BPrefs.get(this).edit().putLong(BPrefs.LAST_DOWNLOAD_MANAGER_REQUEST_ID, downloadId).apply();
    BPrefs.get(this).edit().putInt(BPrefs.LAST_DOWNLOAD_MANAGER_REQUEST_VERSION_NUMBER, versionNumber).apply();
    apply();
    return true;
}
 
Example #21
Source File: UpdateApkReceiver.java    From Yuan-WanAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * 查询下载完成文件的状态
 */
private void checkDownloadStatus(Context context, long downloadId) {
    mDownloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(downloadId);
    Cursor cursor = mDownloadManager.query(query);
    if (cursor.moveToFirst()) {
        int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
        switch (status) {
            case DownloadManager.STATUS_SUCCESSFUL:
                LogUtil.d(LogUtil.TAG_COMMON, "下载完成!");
                installApk(context,mDownloadManager.getUriForDownloadedFile(downloadId));
                break;
            case DownloadManager.STATUS_FAILED://下载失败
                LogUtil.d(LogUtil.TAG_COMMON, "下载失败.....");
                break;
            case DownloadManager.STATUS_RUNNING://正在下载
                LogUtil.d(LogUtil.TAG_COMMON, "正在下载.....");
                break;
            default:
                break;
        }
    }
}
 
Example #22
Source File: DownloadManagerDemo.java    From LLApp with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	/**
	 * get the id of download which have download success, if the id is
	 * my id and it's status is successful, then install it
	 **/
	long completeDownloadId = intent.getLongExtra(
			DownloadManager.EXTRA_DOWNLOAD_ID, -1);
	if (completeDownloadId == downloadId) {
		initData();
		updateView();
		// if download successful, install apk
		if (downloadManagerPro.getStatusById(downloadId) == DownloadManager.STATUS_SUCCESSFUL) {
			String apkFilePath = new StringBuilder(Environment
					.getExternalStorageDirectory().getAbsolutePath())
					.append(File.separator)
					.append(DOWNLOAD_FOLDER_NAME)
					.append(File.separator).append(DOWNLOAD_FILE_NAME)
					.toString();
			install(context, apkFilePath);
		}
	}
}
 
Example #23
Source File: UpdateApkReadyListener.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 FileProviderUtil.getUriFor(context, localFile);
      }
    }
  } finally {
    if (cursor != null) cursor.close();
  }

  return null;
}
 
Example #24
Source File: DownloadBroadcastReceiver.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * 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];
    DownloadManager manager =
            (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = manager.getUriForDownloadedFile(id);
    if (uri == null) {
        // Open the downloads page
        DownloadManagerService.openDownloadsPage(context);
    } else {
        Intent launchIntent = new Intent(Intent.ACTION_VIEW);
        launchIntent.setDataAndType(uri, manager.getMimeTypeForDownloadedFile(id));
        launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(launchIntent);
        } catch (ActivityNotFoundException e) {
            DownloadManagerService.openDownloadsPage(context);
        }
    }
}
 
Example #25
Source File: NetworkHelper.java    From Ouroboros with GNU General Public License v3.0 5 votes vote down vote up
public void downloadFile(String boardName, String tim, String ext, Context context){
    Uri uri = Uri.parse(ChanUrls.getImageUrl(boardName, tim, ext));
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setDescription(tim + ext);
    request.setTitle(tim + ext);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/Ouroboros", tim + ext);

    DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
}
 
Example #26
Source File: DownloadStorageProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
@Override
public Cursor queryRecentDocuments(String rootId, String[] projection)
        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)
                .setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL));
        //copyNotificationUri(result, cursor);
        while (cursor.moveToNext() && result.getCount() < 12) {
            final String mimeType = cursor.getString(
                    cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIA_TYPE));
            final String uri = cursor.getString(
                    cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIAPROVIDER_URI));

            // Skip images that have been inserted into the MediaStore so we
            // don't duplicate them in the recents list.
            if (mimeType == null
                    || (mimeType.startsWith("image/") && !TextUtils.isEmpty(uri))) {
                continue;
            }

            includeDownloadFromCursor(result, cursor);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
        Binder.restoreCallingIdentity(token);
    }
    return result;
}
 
Example #27
Source File: MainActivity.java    From mobile-manager-tool with MIT License 5 votes vote down vote up
private void registerReceiver(){
    IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    registerReceiver(downloadCompleteReceiver, filter);

    IntentFilter filterReceiver = new IntentFilter(ActionManager.ACTION_FILE_CHANGED);
    registerReceiver(fileChangeReceiver, filterReceiver);
}
 
Example #28
Source File: DownloadNewVersionJob.java    From WayHoo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("static-access")
private boolean checkDownloadRunning() {
	UpgradeInfo prefUpgradeInfo = Preferences.getUpgradeInfo(mContext);
	String version = prefUpgradeInfo.getVersion();
	int downloadStatus = Preferences.getDownloadStatus(mContext);
	if (version != null && version.trim().length() != 0
			&& version.equals(mUpgradeInfo.getVersion())) {
		long downloadId = Preferences.getDownloadId(mContext);
		if (downloadId != -1) {
			final DownloadManager downloadManager = (DownloadManager) mContext
					.getSystemService(mContext.DOWNLOAD_SERVICE);
			DownloadManager.Query mDownloadQuery = new DownloadManager.Query();
			mDownloadQuery.setFilterById(downloadId);
			Cursor cursor = downloadManager.query(mDownloadQuery);
			if (cursor != null && cursor.moveToFirst()) {
				int status = cursor.getInt(cursor
						.getColumnIndex(DownloadManager.COLUMN_STATUS));
				if (status == DownloadManager.STATUS_RUNNING
						|| downloadStatus == Constants.DOWNLOAD_STATUS_RUNNING) {
					return true;
				}
			}

		}
	}
	return false;
}
 
Example #29
Source File: MainActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 5 votes vote down vote up
private void listing7_6() {
  // Listing 7-6: Downloading files using the Download Manager
  DownloadManager downloadManager =
    (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

  Uri uri = Uri.parse(
    "http://developer.android.com/shareables/icon_templates-v4.0.zip");

  DownloadManager.Request request = new DownloadManager.Request(uri);
  long reference = downloadManager.enqueue(request);
}
 
Example #30
Source File: AttachmentHandler.java    From tindroid with Apache License 2.0 5 votes vote down vote up
private static long startDownload(AppCompatActivity activity, final Uri uri, final String fname, final String mime,
                          final Map<String, String> headers) {

    DownloadManager dm = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
    if (dm == null) {
        return -1;
    }

    // Ensure directory exists.
    Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .mkdirs();

    DownloadManager.Request req = new DownloadManager.Request(uri);
    // Always add Origin header to satisfy CORS. If server does not need CORS it won't hurt anyway.
    req.addRequestHeader("Origin", Cache.getTinode().getHttpOrigin());
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            req.addRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    return dm.enqueue(
            req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
                    DownloadManager.Request.NETWORK_MOBILE)
                    .setMimeType(mime)
                    .setAllowedOverRoaming(false)
                    .setTitle(fname)
                    .setDescription(activity.getString(R.string.download_title))
                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                    .setVisibleInDownloadsUi(true)
                    .setDestinationUri(Uri.fromFile(new File(Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fname))));
}