android.app.DownloadManager#enqueue ( )源码实例Demo

下面列出了android.app.DownloadManager#enqueue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

private DownloadListener getDownloadListener() {
    return new DownloadListener() {
        public void onDownloadStart(
            String url,
            String userAgent,
            String contentDisposition,
            String mimetype,
            long contentLength
        ) {
            Uri uri = Uri.parse(url);
            Request request = new Request(uri);
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setTitle("File download from Mattermost");

            String cookie = CookieManager.getInstance().getCookie(url);
            if (cookie != null) {
                request.addRequestHeader("cookie", cookie);
            }

            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
       }
    };
}
 
源代码2 项目: scallop   文件: ImageViewerActivity.java
@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);
}
 
源代码3 项目: TBSFileBrowsing   文件: FileDisplayActivity.java
/**
 * 下载文件
 */
@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();
    }
}
 
源代码4 项目: Ency   文件: UpdateService.java
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(downloadUrl));
    // 显示下载信息
    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();
}
 
源代码5 项目: MTweaks-KernelAdiutorMOD   文件: UtilsLibrary.java
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);
    request.setNotificationVisibility(VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

    // Guardar archivo
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
    {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,APK);
    }

    // Iniciamos la descarga
    Utils.toast(context.getString(R.string.appupdater_downloading_file) + " " + APK + " ...", context, LENGTH_LONG);
    id = downloadManager.enqueue(request);

}
 
/**
 * 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);
}
 
源代码7 项目: something.apk   文件: ThreadViewFragment.java
public void enqueueDownload(String targetUrl) {
    Uri image = Uri.parse(targetUrl);
    DownloadManager.Request request = new DownloadManager.Request(image);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, image.getLastPathSegment());
    request.allowScanningByMediaScanner();
    DownloadManager dlMngr = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
    dlMngr.enqueue(request);
    Toast.makeText(getActivity(), "Image saved to Downloads folder.", Toast.LENGTH_LONG).show();
}
 
源代码8 项目: YTPlayer   文件: PlayerActivity2.java
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);
}
 
源代码9 项目: OpenHub   文件: Downloader.java
private void start() {

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //移动网络情况下是否允许漫游
        request.setAllowedOverRoaming(false);

        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        String title = mContext.getString(R.string.downloading);
        if(fileName.contains("/")){
            title = title.concat(" ").concat(fileName.substring(fileName.lastIndexOf("/") + 1));
        }else{
            title = title.concat(" ").concat(fileName);
        }
        request.setTitle(title);
//        request.setDescription("Apk Downloading");
        request.setVisibleInDownloadsUi(true);

        request.setDestinationInExternalPublicDir("Download", fileName);

        downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        downloadId = downloadManager.enqueue(request);

        mContext.registerReceiver(receiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        Toasty.success(mContext, mContext.getString(R.string.download_start)).show();
    }
 
源代码10 项目: Ninja   文件: BrowserUnit.java
public static void download(Context context, String url, String contentDisposition, String mimeType) {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    String filename = URLUtil.guessFileName(url, contentDisposition, mimeType); // Maybe unexpected filename.

    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setTitle(filename);
    request.setMimeType(mimeType);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);

    DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
    NinjaToast.show(context, R.string.toast_start_download);
}
 
源代码11 项目: Android   文件: DownloadFile.java
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);
    }
}
 
源代码12 项目: Ouroboros   文件: NetworkHelper.java
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);
}
 
源代码13 项目: xifan   文件: DownLoadApkService.java
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);
    }
}
 
源代码14 项目: BotLibre   文件: GraphicActivity.java
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);
		}
	}
 
源代码15 项目: product-emm   文件: ApplicationManager.java
/**
 * Initiate downloading via DownloadManager API.
 *
 * @param url     - File URL.
 * @param appName - Name of the application to be downloaded.
 */
private void downloadViaDownloadManager(String url, String appName) {
    final DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Uri downloadUri = Uri
            .parse(url);
    DownloadManager.Request request = new DownloadManager.Request(
            downloadUri);

    // Restrict the types of networks over which this download may
    // proceed.
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
                                   | DownloadManager.Request.NETWORK_MOBILE);
    // Set whether this download may proceed over a roaming connection.
    request.setAllowedOverRoaming(true);
    // Set the title of this download, to be displayed in notifications
    // (if enabled).
    request.setTitle(resources.getString(R.string.downloader_message_title));
    request.setVisibleInDownloadsUi(false);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
    // Set the local destination for the downloaded file to a path
    // within the application's external files directory
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, appName);
    // Enqueue a new download and same the referenceId
    downloadReference = downloadManager.enqueue(request);
    new Thread(new Runnable() {
        @Override
        public void run() {
            boolean downloading = true;
            int progress = 0;
            while (downloading) {
                downloadOngoing = true;
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadReference);
                Cursor cursor = downloadManager.query(query);
                cursor.moveToFirst();
                int bytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.
                                                                                  COLUMN_BYTES_DOWNLOADED_SO_FAR));
                int bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.
                        STATUS_SUCCESSFUL) {
                    downloading = false;
                }
                if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.
                        STATUS_FAILED) {
                    downloading = false;
                    Preference.putString(context, context.getResources().getString(
                            R.string.app_install_status), context.getResources().getString(
                            R.string.app_status_value_download_failed));
                    Preference.putString(context, context.getResources().getString(
                            R.string.app_install_failed_message), "App download failed due to a connection issue.");
                }
                int downloadProgress = 0;
                if (bytesTotal > 0) {
                    downloadProgress = (int) ((bytesDownloaded * 100l) / bytesTotal);
                }
                if (downloadProgress != DOWNLOAD_PERCENTAGE_TOTAL) {
                    progress += DOWNLOADER_INCREMENT;
                } else {
                    progress = DOWNLOAD_PERCENTAGE_TOTAL;
                    Preference.putString(context, context.getResources().getString(
                            R.string.app_install_status), context.getResources().getString(
                            R.string.app_status_value_download_completed));
                }

                Preference.putString(context, resources.getString(R.string.app_download_progress),
                                     String.valueOf(progress));
                cursor.close();
            }
            downloadOngoing = false;
        }
    }).start();
}
 
源代码16 项目: Infinity-For-Reddit   文件: MediaDownloaderImpl.java
@Override
public void download(String url, String fileName, Context ctx) {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setTitle(fileName);

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

    //Android Q support
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, fileName);
    } else {
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
        File directory = new File(path + "/Infinity/");
        boolean saveToInfinityFolder = true;
        if (!directory.exists()) {
            if (!directory.mkdir()) {
                saveToInfinityFolder = false;
            }
        } else {
            if (directory.isFile()) {
                if (!(directory.delete() && directory.mkdir())) {
                    saveToInfinityFolder = false;
                }
            }
        }

        if (saveToInfinityFolder) {
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES + "/Infinity/", fileName);
        } else {
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, fileName);
        }
    }

    DownloadManager manager = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);

    if (manager == null) {
        Toast.makeText(ctx, R.string.download_failed, Toast.LENGTH_SHORT).show();
        return;
    }

    manager.enqueue(request);
    Toast.makeText(ctx, R.string.download_started, Toast.LENGTH_SHORT).show();
}
 
源代码17 项目: WayHoo   文件: DownloadNewVersionJob.java
@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;
}
 
源代码18 项目: Android-Bridge-App   文件: BridgeUpdateService.java
private void updateApp() {

        String fileName = "bridgeapp.apk";
        final String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName;
        final Uri uri = Uri.parse("file://" + destination);

        //Delete update file if exists
        File file = new File(destination);
        if (file.exists())
            file.delete();


        //set downloadmanager
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(UPDATED_APP_URL));
        request.setDescription("Updating BridgeApp");
        request.setTitle("Update");

        //set destination
        request.setDestinationUri(uri);

        // get download service and enqueue file
        final DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        final long downloadId = manager.enqueue(request);

        //set BroadcastReceiver to install app when .apk is downloaded
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            public void onReceive(Context ctxt, Intent intent) {
                if (sharedPreferences.contains(getResources().getString(R.string.preference_auto_update_key))
                        && sharedPreferences.getBoolean(getResources().getString(R.string.preference_auto_update_key), false)) {
                    try {
                        Intent afterUpdateIntent = new Intent(getApplicationContext(), BridgeActivity.class);
                        intent.setAction(Intent.ACTION_MAIN);
                        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, afterUpdateIntent, 0);

                        final long DELAY_IN_MILLIS = 1000 * 2 + System.currentTimeMillis();
                        AlarmManager alarmManager = (AlarmManager)
                                getSystemService(Activity.ALARM_SERVICE);
                        alarmManager.set(AlarmManager.RTC, DELAY_IN_MILLIS, pi);
                        String command;
                        command = "pm install -r " + destination;
                        Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", command});
                        proc.waitFor();
                        pi.send();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {
                    sharedPreferences.edit().putString(getResources().getString(R.string.preference_update_uri), uri.toString()).commit();
                    sharedPreferences.edit().putString(getResources().getString(R.string.preference_update_mimetype), manager.getMimeTypeForDownloadedFile(downloadId)).commit();
                    Intent updateAvailableIntent = new Intent(getResources().getString(R.string.intent_filter_update_available));
                    sendBroadcast(updateAvailableIntent);

                }

                unregisterReceiver(this);

            }
        };
        //register receiver for when .apk download is compete
        registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
 
源代码19 项目: product-emm   文件: ApplicationManager.java
/**
 * Initiate downloading via DownloadManager API.
 *
 * @param url     - File URL.
 * @param appName - Name of the application to be downloaded.
 */
private void downloadViaDownloadManager(String url, String appName) {
    final DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Uri downloadUri = Uri
            .parse(url);
    DownloadManager.Request request = new DownloadManager.Request(
            downloadUri);

    // Restrict the types of networks over which this download may
    // proceed.
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
                                   | DownloadManager.Request.NETWORK_MOBILE);
    // Set whether this download may proceed over a roaming connection.
    request.setAllowedOverRoaming(false);
    // Set the title of this download, to be displayed in notifications
    // (if enabled).
    request.setTitle(resources.getString(R.string.downloader_message_title));
    // Set a description of this download, to be displayed in
    // notifications (if enabled)
    request.setDescription(resources.getString(R.string.downloader_message_description) + appName);
    // Set the local destination for the downloaded file to a path
    // within the application's external files directory
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, appName);
    // Enqueue a new download and same the referenceId
    downloadReference = downloadManager.enqueue(request);
    new Thread(new Runnable() {
        @Override
        public void run() {
            boolean downloading = true;
            int progress = 0;
            while (downloading) {
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadReference);
                Cursor cursor = downloadManager.query(query);
                cursor.moveToFirst();
                int bytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.
                                                                                  COLUMN_BYTES_DOWNLOADED_SO_FAR));
                int bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.
                        STATUS_SUCCESSFUL) {
                    downloading = false;
                }
                int downloadProgress = (int) ((bytesDownloaded * 100l) / bytesTotal);
                if (downloadProgress != DOWNLOAD_PERCENTAGE_TOTAL) {
                    progress += DOWNLOADER_INCREMENT;
                } else {
                    progress = DOWNLOAD_PERCENTAGE_TOTAL;
                }

                Preference.putString(context, resources.getString(R.string.app_download_progress),
                                     String.valueOf(progress));
                cursor.close();
            }
        }
    }).start();
}
 
源代码20 项目: MissZzzReader   文件: DownloadMangerUtils.java
/**
 * 文件下载
 *
 * @param context
 * @param fileDir
 * @param url
 * @param fileName
 */
public static void downloadFile(Context context, String fileDir, String url, String fileName) {

    try {
        Log.d("http download:", url);
        //String Url = "10.10.123.16:8080/gxqdw_ubap/mEmailController.thumb?getAttachmentStream&fileId=1&fileName=自我探索——我是谁.ppt&emailId=36&token=d1828248-cc71-4719-8218-adc31ffc9cca&type=inbox&fileSize=14696446";

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        // DownloadManager.Request.setDestinationInExternalPublicDir();

        request.setDescription(fileName);
        request.setTitle("附件");
        // 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) {
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            // request.setNotificationVisibility(VISIBILITY_HIDDEN);
        }
        // int i = Build.VERSION.SDK_INT;
        if (Build.VERSION.SDK_INT > 17) {
            request.setDestinationInExternalPublicDir(fileDir, fileName);
        } else {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                request.setDestinationInExternalPublicDir(fileDir, fileName);
            } else {
                Log.d("download", "android版本过低,不存在外部存储,下载路径无法指定,默认路径:/data/data/com.android.providers.downloads/cache/");
                DialogCreator.createCommonDialog(context, "文件下载", "android版本过低或系统兼容性问题,不存在外部存储,无法指定下载路径,文件下载到系统默认路径,请到文件管理搜索文件名",
                        "关闭", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

            }
        }
        // get download service and enqueue file
        DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);
    } catch (Exception e) {
        e.printStackTrace();
        lowVersionNoSDDownload(context, url, fileName);
    }
}