Java Code Examples for android.app.DownloadManager#Request

The following examples show how to use android.app.DownloadManager#Request . 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: Index.java    From trekarta with GNU General Public License v3.0 6 votes vote down vote up
private long requestDownload(int x, int y, boolean hillshade) {
    String ext = hillshade ? "mbtiles" : "mtiles";
    String fileName = String.format(Locale.ENGLISH, "%d-%d.%s", x, y, ext);
    Uri uri = new Uri.Builder()
            .scheme("https")
            .authority("trekarta.info")
            .appendPath(hillshade ? "hillshades" : "maps")
            .appendPath(String.valueOf(x))
            .appendPath(fileName)
            .build();
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setTitle(mContext.getString(hillshade ? R.string.hillshadeTitle : R.string.mapTitle, x, y));
    request.setDescription(mContext.getString(R.string.app_name));
    File root = new File(mMapsDatabase.getPath()).getParentFile();
    File file = new File(root, fileName);
    if (file.exists()) {
        //noinspection ResultOfMethodCallIgnored
        file.delete();
    }
    request.setDestinationInExternalFilesDir(mContext, root.getName(), fileName);
    request.setVisibleInDownloadsUi(false);
    return mDownloadManager.enqueue(request);
}
 
Example 2
Source File: DownloadTreeViewAdapter.java    From satstat with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Starts a map download.
 * 
 * This will also start the progress checker.
 * 
 * @param rfile The remote file to download
 * @param mapFile The local file to which the map will be saved
 * @param view The {@link View} displaying the map file
 */
private void startDownload(RemoteFile rfile, File mapFile, View view) {
	Uri uri = rfile.getUri();
	Uri destUri = Uri.fromFile(mapFile);
	try {
		DownloadManager.Request request = new DownloadManager.Request(uri);
		//request.setTitle(rfile.name);
		//request.setDescription("SatStat map download");
		request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
		//request.setDestinationInExternalFilesDir(getActivity(), dirType, subPath)
		request.setDestinationUri(destUri);
		Log.d(TAG, String.format("Ready to download %s to %s (local name %s)", uri.toString(), destUri.toString(), mapFile.getName()));
		Long reference = downloadManager.enqueue(request);
		DownloadInfo info = new DownloadInfo(rfile, uri, mapFile, reference);
		downloadsByReference.put(reference, info);
		downloadsByUri.put(rfile.getUri(), info);
		downloadsByFile.put(mapFile, info);
		ProgressBar downloadFileProgress = (ProgressBar) view.findViewById(R.id.downloadFileProgress);
		downloadFileProgress.setVisibility(View.VISIBLE);
		downloadFileProgress.setMax((int) (rfile.size / 1024));
		downloadFileProgress.setProgress(0);
		startProgressChecker();
	} catch (SecurityException e) {
		Log.w(TAG, String.format("Permission not granted to download %s to %s", uri.toString(), destUri.toString()));
	}
}
 
Example 3
Source File: UpdataService.java    From WanAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * 下载apk
 */
private long downloadApk(String url) {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    //创建目录, 外部存储--> Download文件夹
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir() ;
    File file = new File(Constant.PATH_APK);
    if(file.exists())
        file.delete();
    //设置文件存放路径
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS  , "WanAndroid.apk");
    //设置Notification的标题
    request.setTitle(mContext.getString(R.string.app_name));
    //设置描述
    request.setDescription(mContext.getString(R.string.downloading)) ;
    // 在下载过程中通知栏会一直显示该下载的Notification,在下载完成后该Notification会继续显示,直到用户点击该Notification或者消除该Notification。
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED ) ;
    //下载的文件可以被系统的Downloads应用扫描到并管理
    request.setVisibleInDownloadsUi( true ) ;
    //设置请求的Mime
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    request.setMimeType(mimeTypeMap.getMimeTypeFromExtension(url));
    //下载网络需求 - 手机数据流量、wifi
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI ) ;
    DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    return downloadManager.enqueue(request);
}
 
Example 4
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 5
Source File: DownloadSharedLinkActivity.java    From YouTube-In-Background with MIT License 6 votes vote down vote up
private long downloadFromUrl(String youtubeDlUrl, String downloadTitle, String fileName, boolean hide)
{
    Uri uri = Uri.parse(youtubeDlUrl);
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setTitle(downloadTitle);
    if (hide) {
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        request.setVisibleInDownloadsUi(false);
    } else
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);

    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    return manager.enqueue(request);
}
 
Example 6
Source File: DownloadService.java    From DownloadManager with Apache License 2.0 6 votes vote down vote up
/**
 * 下载最新APK
 */
private void downloadApk(String url) {
    downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    downloadObserver = new DownloadChangeObserver();

    registerContentObserver();

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    /**设置用于下载时的网络状态*/
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
    /**设置通知栏是否可见*/
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
    /**设置漫游状态下是否可以下载*/
    request.setAllowedOverRoaming(false);
    /**如果我们希望下载的文件可以被系统的Downloads应用扫描到并管理,
     我们需要调用Request对象的setVisibleInDownloadsUi方法,传递参数true.*/
    request.setVisibleInDownloadsUi(true);
    /**设置文件保存路径*/
    request.setDestinationInExternalFilesDir(getApplicationContext(), "phoenix", "phoenix.apk");
    /**将下载请求放入队列, return下载任务的ID*/
    downloadId = downloadManager.enqueue(request);

    registerBroadcast();
}
 
Example 7
Source File: NetSearchFragment.java    From LitePlayer with Apache License 2.0 5 votes vote down vote up
@Override
		public void onLrc(int position, String url) {
			if(url == null) return;
			
			String musicName = mResultData.get(position).getMusicName();
			DownloadManager.Request request = new DownloadManager.Request(
					Uri.parse(Constants.MUSIC_URL + url));
			request.setVisibleInDownloadsUi(false);
			request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
//			request.setShowRunningNotification(false);
			request.setDestinationUri(Uri.fromFile(new File(MusicUtils
					.getLrcDir() + musicName + ".lrc")));
			mDownloadManager.enqueue(request);
		}
 
Example 8
Source File: APKDownloader.java    From seny-devpkg with Apache License 2.0 5 votes vote down vote up
/**
 * 执行下载任务
 *
 * @param apkUri  apk的下载地址
 * @param apkName 要保存的apk名字
 * @return 下载任务的ID
 */
public long downloadAPK(String apkUri, String apkName) {
    Assert.notNull(apkUri);
    Assert.notNull(apkName);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUri));
    request.setMimeType("application/vnd.android.package-archive");
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
    long id = mDownloadManager.enqueue(request);
    sIds.add(id);
    return id;
}
 
Example 9
Source File: DownLoadApkService.java    From xifan with Apache License 2.0 5 votes vote down vote up
private void downLoadApk(String url) {
    if (mEnqueue == 0) {
        mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setTitle(getString(R.string.app_name));
        request.setDescription(getString(R.string.text_downloading));
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, APK_NAME);
        request.setVisibleInDownloadsUi(true);
        mEnqueue = mDownloadManager.enqueue(request);
    }
}
 
Example 10
Source File: GraphicActivity.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void downloadFile(View v){
	if(gInstance.fileName.equals("")){
		MainActivity.showMessage("Missing file!", this);
		return;
	}
	
	String url=MainActivity.WEBSITE +"/"+ gInstance.media;
	
	try{
		
	DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
	request.setTitle(gInstance.fileName);
	request.setDescription(MainActivity.WEBSITE);
	
	//		request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);  only download thro wifi.
	
	request.allowScanningByMediaScanner();
	request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
	
	Toast.makeText(GraphicActivity.this, "Downloading " + gInstance.fileName, Toast.LENGTH_SHORT).show();
	
	request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, gInstance.fileName);
	DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
	
	BroadcastReceiver onComplete=new BroadcastReceiver() {
	    public void onReceive(Context ctxt, Intent intent) {
	        Toast.makeText(GraphicActivity.this, gInstance.fileName+" Downloaded!", Toast.LENGTH_SHORT).show();
	    }
	};
	manager.enqueue(request);
	registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	
	}catch(Exception e){
		MainActivity.showMessage(e.getMessage(), this);
	}
}
 
Example 11
Source File: DownloadFile.java    From Android with MIT License 5 votes vote down vote up
private void downloading() {
    if(isStoragePermissionGranted()){
        DownloadManager mgr = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri =  Uri.parse(url);
        DownloadManager.Request req=new DownloadManager.Request(uri);
        req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
                | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false)
                .setTitle(title)
                .setDescription("downloading...")
                .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,title);
        mgr.enqueue(req);
    }
}
 
Example 12
Source File: FeedBackActivity.java    From shinny-futures-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * date: 7/12/17
 * author: chenli
 * description: 利用系统的下载服务
 */
private void downLoadFile(String url, String contentDisposition, String mimetype) {
    //创建下载任务,downloadUrl就是下载链接
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    //指定下载路径和下载文件名
    request.setDestinationInExternalPublicDir("/download/", URLUtil.guessFileName(url, contentDisposition, mimetype));
    //获取下载管理器
    DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    //将下载任务加入下载队列,否则不会进行下载
    if (downloadManager != null) downloadManager.enqueue(request);
    ToastUtils.showToast(BaseApplication.getContext(),
            "下载完成:" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    .getAbsolutePath() + File.separator + URLUtil.guessFileName(url, contentDisposition, mimetype));
}
 
Example 13
Source File: AbsDownloadMusic.java    From YCAudioPlayer with Apache License 2.0 5 votes vote down vote up
/**
 * 开始下载
 * @param url                   url
 * @param artist                artist
 * @param title                 title
 * @param coverPath             path
 */
void downloadMusic(String url, String artist, String title, String coverPath) {
    try {
        String fileName = FileMusicUtils.getMp3FileName(artist, title);
        Uri uri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setTitle(FileMusicUtils.getFileName(artist, title));
        request.setDescription("正在下载…");
        request.setDestinationInExternalPublicDir(FileMusicUtils.getRelativeMusicDir(), fileName);
        request.setMimeType(MimeTypeMap.getFileExtensionFromUrl(url));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        // 不允许漫游
        request.setAllowedOverRoaming(false);
        DownloadManager downloadManager = (DownloadManager) Utils.getApp().getSystemService(Context.DOWNLOAD_SERVICE);
        long id = 0;
        if (downloadManager != null) {
            id = downloadManager.enqueue(request);
        }
        String musicAbsPath = FileMusicUtils.getMusicDir().concat(fileName);
        DownloadMusicInfo downloadMusicInfo = new DownloadMusicInfo(title, musicAbsPath, coverPath);
        BaseAppHelper.get().getDownloadList().put(id, downloadMusicInfo);
    } catch (Throwable th) {
        th.printStackTrace();
        ToastUtils.showShort("下载失败");
    } finally {

    }
}
 
Example 14
Source File: PlayerActivity2.java    From YTPlayer with GNU General Public License v3.0 5 votes vote down vote up
private void downloadNormal(String fileName, YTConfig config) {
    Uri uri = Uri.parse(config.getUrl());
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setTitle(config.getTitle()+" - "+config.getChannelTitle());

    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
}
 
Example 15
Source File: GalleryDetailScene.java    From MHViewer with Apache License 2.0 5 votes vote down vote up
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Context context = getContext2();
    if (null != context && null != mTorrentList && position < mTorrentList.length) {
        String url = mTorrentList[position].first;
        String name = mTorrentList[position].second;
        // Use system download service
        DownloadManager.Request r = new DownloadManager.Request(Uri.parse(url));
        r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                FileUtils.sanitizeFilename(name + ".torrent"));
        r.allowScanningByMediaScanner();
        r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (dm != null) {
            try {
                dm.enqueue(r);
            } catch (Throwable e) {
                ExceptionUtils.throwIfFatal(e);
            }
        }
    }

    if (mDialog != null) {
        mDialog.dismiss();
        mDialog = null;
    }
}
 
Example 16
Source File: GraphicActivity.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void downloadFile(View v){

		if(gInstance.fileName.equals("")){
			MainActivity.showMessage("Missing file!", this);
			return;
		}
		
		String url=MainActivity.WEBSITE +"/"+ gInstance.media;
		
		try{
			
		DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
		request.setTitle(gInstance.fileName);
		request.setDescription(MainActivity.WEBSITE);
		
		//		request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);  only download thro wifi.
		
		request.allowScanningByMediaScanner();
		request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
		
		Toast.makeText(GraphicActivity.this, "Downloading " + gInstance.fileName, Toast.LENGTH_SHORT).show();
		
		request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, gInstance.fileName);
		DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
		
		BroadcastReceiver onComplete=new BroadcastReceiver() {
		    public void onReceive(Context ctxt, Intent intent) {
		        Toast.makeText(GraphicActivity.this, gInstance.fileName+" Downloaded!", Toast.LENGTH_SHORT).show();
		    }
		};
		manager.enqueue(request);
		registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
		
		}catch(Exception e){
			MainActivity.showMessage(e.getMessage(), this);
		}
	}
 
Example 17
Source File: RxDownloader.java    From RxDownloader with MIT License 5 votes vote down vote up
private DownloadManager.Request createRequest(@NonNull String url,
                                              @NonNull String filename,
                                              @Nullable String destinationPath,
                                              @NonNull String mimeType,
                                              boolean inPublicDir,
                                              boolean showCompletedNotification) {

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setDescription(filename);
    request.setMimeType(mimeType);

    if (destinationPath == null) {
        destinationPath = Environment.DIRECTORY_DOWNLOADS;
    }

    File destinationFolder = inPublicDir
            ? Environment.getExternalStoragePublicDirectory(destinationPath)
            : new File(context.getFilesDir(), destinationPath);

    createFolderIfNeeded(destinationFolder);
    removeDuplicateFileIfExist(destinationFolder, filename);

    if (inPublicDir) {
        request.setDestinationInExternalPublicDir(destinationPath, filename);
    } else {
        request.setDestinationInExternalFilesDir(context, destinationPath, filename);
    }

    request.setNotificationVisibility(showCompletedNotification
            ? DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
            : DownloadManager.Request.VISIBILITY_VISIBLE);

    return request;
}
 
Example 18
Source File: Utils.java    From ROMInstaller with MIT License 4 votes vote down vote up
public static void StartDownloadROM(String downloadLink, String downloadDirectory, String downloadedFileFinalName) {

        FILE_NAME = downloadedFileFinalName;

        Uri mDownloadLink = Uri.parse(downloadLink);

        File mDownloadDirectory = new File(downloadDirectory);

        DownloadManager.Request mRequest = new DownloadManager.Request(mDownloadLink);

        mRequest.setDestinationInExternalPublicDir(mDownloadDirectory.getPath(), downloadedFileFinalName);

        mRequest.setTitle(ACTIVITY.getString(R.string.app_name));

        mRequest.setDescription(downloadedFileFinalName);

        new Download(
                mRequest,
                mDownloadDirectory,
                FILE_NAME, true).execute();

    }
 
Example 19
Source File: Utils.java    From ROMInstaller with MIT License 4 votes vote down vote up
public static void StartFlashRecovery(String downloadLink, String downloadDirectory, String downloadedFileFinalName, String recoveryPartition) {

        Uri mDownloadLink = Uri.parse(downloadLink);

        File mDownloadDirectory = new File(downloadDirectory);

        DownloadManager.Request mRequest = new DownloadManager.Request(mDownloadLink);

        mRequest.setDestinationInExternalPublicDir(mDownloadDirectory.getPath(), downloadedFileFinalName);

        mRequest.setTitle(ACTIVITY.getString(R.string.app_name));

        mRequest.setDescription(downloadedFileFinalName);

        new FlashRecovery(
                mRequest,
                mDownloadDirectory,
                downloadedFileFinalName,
                recoveryPartition, false).execute();

    }
 
Example 20
Source File: FlashRecovery.java    From ROMInstaller with MIT License 3 votes vote down vote up
FlashRecovery(DownloadManager.Request request, File downloadDirectory, String downloadedFileFinalName, String recoveryPartition, Boolean hasAddOns) {

        this.mRequest = request;

        this.mDownloadDirectory = downloadDirectory;

        this.mDownloadedFileFinalName = downloadedFileFinalName;

        this.mRecoveryPartition = recoveryPartition;

        this.mHasAddOns = hasAddOns;

    }