Java 类android.app.DownloadManager.Request 实例源码

项目:AOSP-Kayboard-7.1.2    文件:UpdateHandler.java   
/**
 * Download latest metadata from the server through DownloadManager for all relevant clients
 *
 * @param context The context for retrieving resources
 * @param metadataUri The client to update
 */
private static void updateClientsWithMetadataUri(
        final Context context, final String metadataUri) {
    Log.i(TAG, "updateClientsWithMetadataUri() : MetadataUri = " + metadataUri);
    // Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
    // DownloadManager also stupidly cuts the extension to replace with its own that it
    // gets from the content-type. We need to circumvent this.
    final String disambiguator = "#" + System.currentTimeMillis()
            + ApplicationUtils.getVersionName(context) + ".json";
    final Request metadataRequest = new Request(Uri.parse(metadataUri + disambiguator));
    DebugLogUtils.l("Request =", metadataRequest);

    final Resources res = context.getResources();
    metadataRequest.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
    metadataRequest.setTitle(res.getString(R.string.download_description));
    // Do not show the notification when downloading the metadata.
    metadataRequest.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
    metadataRequest.setVisibleInDownloadsUi(
            res.getBoolean(R.bool.metadata_downloads_visible_in_download_UI));

    final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
    if (maybeCancelUpdateAndReturnIfStillRunning(context, metadataUri, manager,
            DictionaryService.NO_CANCEL_DOWNLOAD_PERIOD_MILLIS)) {
        // We already have a recent download in progress. Don't register a new download.
        return;
    }
    final long downloadId;
    synchronized (sSharedIdProtector) {
        downloadId = manager.enqueue(metadataRequest);
        DebugLogUtils.l("Metadata download requested with id", downloadId);
        // If there is still a download in progress, it's been there for a while and
        // there is probably something wrong with download manager. It's best to just
        // overwrite the id and request it again. If the old one happens to finish
        // anyway, we don't know about its ID any more, so the downloadFinished
        // method will ignore it.
        writeMetadataDownloadId(context, metadataUri, downloadId);
    }
    Log.i(TAG, "updateClientsWithMetadataUri() : DownloadId = " + downloadId);
}
项目:rview    文件:ActivityHelper.java   
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void downloadUri(
        Context context, Uri uri, String fileName, @Nullable String mimeType) {
    // Create the destination location
    File destination = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS);
    destination.mkdirs();
    Uri destinationUri = Uri.fromFile(new File(destination, fileName));

    // Use the download manager to perform the download
    DownloadManager downloadManager =
            (DownloadManager) context.getSystemService(Activity.DOWNLOAD_SERVICE);
    Request request = new Request(uri)
            .setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationUri(destinationUri);
    if (mimeType != null) {
        request.setMimeType(mimeType);
    }
    request.allowScanningByMediaScanner();
    downloadManager.enqueue(request);
}
项目:uPods-android    文件:DownloadMaster.java   
public void download(DownloadTask task) {
    //TODO better path
    DownloadManager downloadManager = (DownloadManager) UpodsApplication.getContext().getSystemService(Context.DOWNLOAD_SERVICE);
    Uri episodUri = Uri.parse(task.track.getAudeoUrl());
    String trackName = GlobalUtils.getCleanFileName(task.track.getTitle()) + ".mp3";
    String mediaItemName = GlobalUtils.getCleanFileName(task.mediaItem.getName());
    String finalPath = PODCASTS_DOWNLOAD_DIRECTORY + "/" + mediaItemName + "/" + trackName;
    finalPath = Environment.getExternalStorageDirectory() + finalPath;
    Request request = new Request(episodUri);
    request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
    request.setTitle(task.track.getTitle());
    request.setDescription(task.track.getSubTitle());
    request.setDestinationUri(Uri.fromFile(new File(finalPath)));
    task.downloadId = downloadManager.enqueue(request);
    task.filePath = finalPath;
    allTasks.add(task);
    Logger.printInfo(DM_LOG, "Starting download episod " + trackName + " to " + finalPath);
    runProgressUpdater();
}
项目:mattermost-android-classic    文件:WebViewActivity.java   
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);
       }
    };
}
项目:Codebase    文件:DownloadUtil.java   
/**
 * 下载目标地址数据至SD卡默认目录
 *
 * @param context 当前环境
 * @param url     地址
 * @return 下载编号
 */
public static final long download(Context context, String url,
                                  String fileName) {
    DownloadManager downloadManager = getDownloadManager(context);
    if (downloadManager != null) {
        Uri uri = Uri.parse(url);
        File file = new File(Environment.getExternalStorageDirectory()
                .getPath() + File.separator + fileName);
        /*
* 判断文件是否存在,如果存在删除源文件
*/
        if (file.exists()) {
            file.delete();
        }
        Request request = new Request(uri);
        request.setTitle("正在下载……");
        request.setDestinationUri(Uri.parse(Uri.fromFile(
                Environment.getExternalStorageDirectory()).toString()
                + File.separator + fileName)); // 设置下载后文件存放的位置
        Toast.makeText(context, "开始下载更新包,请稍后……", Toast.LENGTH_LONG).show();
        return downloadManager.enqueue(request);
    }
    return 0;
}
项目:Studentenportal    文件:MoodleDownloadHelper.java   
@Override
public void download(Context context, Uri uri, String filename) {
    DownloadManager.Request r = null;

        try {
            r = new DownloadManager.Request(uri);
        } catch (IllegalArgumentException e) {
            /* Unmodified Android 2.3 doesn't allow downloads over HTTPS - check if
             * this is an exception related to this */
            if(e.getMessage() != null && e.getMessage().contains("HTTP URIs")) {
                Toast.makeText(context, R.string.error_download_not_supported_https, Toast.LENGTH_SHORT).show();
                return;
            } else {
                // rethrow exception if it's not about HTTPS downloads
                throw e;
            }
        }

        setupRequest(r, uri, filename);

        // Start download
        DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        dm.enqueue(r);
}
项目:netkuu.player    文件:DownloadManager.java   
public long enqueue(String uri, String name, int epi, String vid){
    Request request = new Request(Uri.parse(uri));
    request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
    String externd = uri.substring(uri.lastIndexOf('.'));
    String file = name;
    String dir = "NetVideo" ;
    if(epi != 0){
        file += epi;
        dir = dir + "/" + name;
    }
    request.setTitle(file);
    request.setDestinationInExternalPublicDir(dir, file + "." + externd);
    request.setMimeType("media/video");
    request.setDescription(vid);
    return mDownloadManager.enqueue(request);
}
项目:wikipoff    文件:WikiAvailableActivity.java   
private void do_download() { 
    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    for(WikiDBFile wdbf : wiki.getDBFiles()) {
        Request request = new Request(
                Uri.parse(wdbf.getUrl()));
        String destinationPath = new File(
                new File(storage,getString(R.string.DBDir)),
                wdbf.getFilename()).getAbsolutePath();
        request.setDestinationUri(Uri.parse("file://"+destinationPath));
        request.setTitle(wdbf.getFilename());
        dm.enqueue(request);
    }
    downloadbutton.setVisibility(View.GONE);
    stopdownloadbutton.setVisibility(View.VISIBLE);

}
项目:amar-android-demo    文件:Internet1Activity.java   
private void listing603()
{
    /**
     * Listing 6-3: Downloading files using the Download Manager
     */
    String serviceString = Context.DOWNLOAD_SERVICE;
    DownloadManager downloadManager = ( DownloadManager ) getSystemService( serviceString );

    Uri uri = Uri.parse( getString( R.string.my_feed2 ) );
    DownloadManager.Request request = new Request( uri );

    long reference = downloadManager.enqueue( request );

    //
    myDownloadReference = reference;
    Log.d( TAG, "Download Reference: " + reference );
}
项目:magpi-android    文件:IssueDetailsFragment.java   
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);
    }
}
项目:Fairphone    文件:FairphoneUpdater.java   
private Request createDownloadRequest(String url, String fileName,
        String downloadTitle) {

    Request request = new Request(Uri.parse(url));
    Environment.getExternalStoragePublicDirectory(
            Environment.getExternalStorageDirectory()
                    + VersionParserHelper.UPDATER_FOLDER).mkdirs();

    request.setDestinationInExternalPublicDir(
            VersionParserHelper.UPDATER_FOLDER, fileName);
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
    request.setAllowedOverRoaming(false);

    request.setTitle(downloadTitle);

    return request;
}
项目:Fairphone    文件:UpdaterService.java   
private Request createDownloadRequest(String url, String fileName) {


        Request request = new Request(Uri.parse(url));
        Environment.getExternalStoragePublicDirectory(
                Environment.getExternalStorageDirectory()
                        + VersionParserHelper.UPDATER_FOLDER).mkdirs();

        request.setDestinationInExternalPublicDir(
                VersionParserHelper.UPDATER_FOLDER, fileName);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setAllowedOverRoaming(false);

        Resources resources = getApplicationContext().getResources();
        request.setTitle(resources.getString(R.string.downloadUpdateTitle));

        return request;
    }
项目:Fairphone    文件:GappsInstallerHelper.java   
private Request createDownloadRequest(String url, String fileName) {

        Request request = new Request(Uri.parse(url));
        Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS).mkdirs();

        request.setDestinationInExternalPublicDir(
                Environment.DIRECTORY_DOWNLOADS, fileName);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setAllowedOverRoaming(false);

        String download = mContext.getResources().getString(
                R.string.google_apps_download_title);
        request.setTitle(download);

        return request;
    }
项目:Fairphone---DEPRECATED    文件:GappsInstallerHelper.java   
private Request createDownloadRequest(String url, String fileName) {

        Request request = new Request(Uri.parse(url));
        Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS).mkdirs();

        request.setDestinationInExternalPublicDir(
                Environment.DIRECTORY_DOWNLOADS, fileName);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI );
        request.setAllowedOverRoaming(false);


        String download = mContext.getResources().getString(
                R.string.google_apps_download_title);
        request.setTitle(download);

        return request;
    }
项目:goloader    文件:ShareActivity.java   
private void tempDownloadToSdcard(Request request) {
    videoUri = Uri.parse(dir_Downloads.toURI() + composedVideoFilename);
    Utils.logger("d", "** NEW ** videoUri: " + videoUri, DEBUG_TAG);
    request.setDestinationUri(videoUri);
    try {
        enqueue = dm.enqueue(request);
    } catch (IllegalArgumentException e) {
    Log.e(DEBUG_TAG, "tempDownloadToSdcard: " + e.getMessage());
    BugSenseHandler.sendExceptionMessage(DEBUG_TAG + "-> tempDownloadToSdcard", e.getMessage(), e);
 } catch (NullPointerException ne) {
    Log.e(DEBUG_TAG, "callDownloadApk: " + ne.getMessage());
    BugSenseHandler.sendExceptionMessage(DEBUG_TAG + "-> tempDownloadToSdcard: ", ne.getMessage(), ne);
    Toast.makeText(this, getString(R.string.error), Toast.LENGTH_LONG).show();
 }catch (SecurityException se) {
    Log.e(DEBUG_TAG, "callDownloadApk: " + se.getMessage());
    BugSenseHandler.sendExceptionMessage(DEBUG_TAG + "-> tempDownloadToSdcard: ", se.getMessage(), se);
    Toast.makeText(this, getString(R.string.error), Toast.LENGTH_LONG).show();
 }
}
项目:react-native-download-manager    文件:DownloadFileManager.java   
@ReactMethod
public void download(final ReadableMap params, Callback callback){
    // 获取参数
    String url = params.hasKey("url") ? params.getString("url") : null;
    String description = params.hasKey("description") ? params.getString("description") : "downloading";
    // 判断是否未回调继续调用
    if(rctCallback!=null){
        WritableMap map = Arguments.createMap();
        map.putInt("status", -2);
        map.putString("description", "busy");
        map.putString("url",url);
        callback.invoke(map);
        return;
    }
    rctCallback = callback;
    rctParams = params;
    // 设置参数
    DownloadManager.Request request = new Request(Uri.parse(url));
    request.setAllowedNetworkTypes(Request.NETWORK_WIFI);

    request.setNotificationVisibility(Request.VISIBILITY_VISIBLE); // 是否通知
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
    request.setMimeType(mimeString); // 下载的文件类型
    request.setTitle("下载"); // 通知栏的标题
    request.setDescription(description); // 通知栏描述
    request.setAllowedOverRoaming(false); //漫游网络是否可以下载
    request.setAllowedOverMetered(false);
    request.setVisibleInDownloadsUi(true);

    //设置文件存放目录
    request.setDestinationInExternalFilesDir(mApplicationContext, Environment.DIRECTORY_DOWNLOADS, description);
    mTaskId = downloadManager.enqueue(request);
    //注册广播接收者,监听下载状态
    mApplicationContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
项目:android-project-gallery    文件:DownloadFactory.java   
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public void downloadApk(String requestUrl, String dir, String filename)
{
    Uri resource = Uri.parse(requestUrl);
    DownloadManager.Request request = new DownloadManager.Request(resource);
    request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
    request.setAllowedOverRoaming(false);

    //设置文件类型  
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(requestUrl));
    request.setMimeType(mimeString);

    //在通知栏中显示   
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD)
    {
        request.setShowRunningNotification(true);
    }
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
    {
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }

    // 显示下载界面
    request.setVisibleInDownloadsUi(true);
    //sdcard的目录下的download文件夹  /**AppConfig.DIR_APK*/
    request.setDestinationInExternalPublicDir("/download/", filename + ".apk");
    request.setTitle(filename + "");

    long id = mDownloadManager.enqueue(request);
    mTask.put(id, filename + "");
}
项目:LitePlayer    文件:NetSearchFragment.java   
@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);
        }
项目:android-project-wo2b    文件:DownloadFactory.java   
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public void downloadApk(String requestUrl, String dir, String filename)
{
    Uri resource = Uri.parse(requestUrl);
    DownloadManager.Request request = new DownloadManager.Request(resource);
    request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
    request.setAllowedOverRoaming(false);

    //设置文件类型  
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(requestUrl));
    request.setMimeType(mimeString);

    //在通知栏中显示   
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD)
    {
        request.setShowRunningNotification(true);
    }
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
    {
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }

    // 显示下载界面
    request.setVisibleInDownloadsUi(true);
    //sdcard的目录下的download文件夹  /**AppConfig.DIR_APK*/
    request.setDestinationInExternalPublicDir("/download/", filename + ".apk");
    request.setTitle(filename + "");

    long id = mDownloadManager.enqueue(request);
    mTask.put(id, filename + "");
}
项目:juzidian    文件:JuzidianDownloadManager.java   
/**
 * Start a download from the given URL.
 * <p>
 * Starting a new download will overwrite any existing download.
 * 
 * @param url the URL to start a download for.
 */
public void startDownload(final String url) {
    LOGGER.debug("Starting download: {}", url);
    final Request request = new DownloadManager.Request(Uri.parse(url));
    request.setTitle("Juzidian Dictionary Database");
    final long downloadId = this.downloadManager.enqueue(request);
    this.downloadRegistry.setCurrentDownloadId(downloadId);
}
项目:edx-app-android    文件:IDownloadManagerImpl.java   
@Override
public synchronized long addDownload(File destFolder, String url, boolean wifiOnly, String title) {
    long dmid = -1;

    //Need to check first if the download manager service is enabled
    if(!isDownloadManagerEnabled())
        return dmid;

    // skip if URL is not valid
    if(url == null) {
        // URL is null
        return dmid;
    }
    url = url.trim();
    if (url.length() == 0) {
        // URL is empty
        return dmid;
    }

    logger.debug("Starting download: " + url);

    Uri target = Uri.fromFile(new File(destFolder, Sha1Util.SHA1(url)));
    Request request = new Request(Uri.parse(url));
    request.setDestinationUri(target);
    request.setTitle(title);

    if (wifiOnly) {
        request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
    } else {
        request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
    }

    dmid = dm.enqueue(request);

    return dmid;
}
项目:DUpdate    文件:HttpUpdateObserver.java   
/**
 * 普通升级,交给download manager
 * @param apkPath apk下载路径
 * @param url apk下载地址
 */
private void normalDownload(final String apkPath, final String url) {
    File apkSaveFile = new File(apkPath);
    if (apkSaveFile.exists()) {
        apkSaveFile.delete();
    }
    mDownloadManager.remove(mSharedPreferences.getLong(DL_ID, 0));   
    mSharedPreferences.edit().clear().commit();
    //开始下载   
    Uri resource = Uri.parse(encodeGB(url));   
    DownloadManager.Request request = new DownloadManager.Request(resource);   
    request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);   
    request.setAllowedOverRoaming(false);   
    //设置文件类型  
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();  
    String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));  
    request.setMimeType(mimeString);  
    //在通知栏中显示   
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);  
    request.setVisibleInDownloadsUi(true);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    //sdcard的目录下的download文件夹  
    request.setDestinationInExternalPublicDir("", UpdateUtils.getApkDownloadName());
    request.setTitle(mContext.getString(R.string.app_name));   
    long id = mDownloadManager.enqueue(request);   
    //保存id   
    mSharedPreferences.edit().putLong(DL_ID, id).commit();   
    mContext.registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
项目:Studentenportal    文件:MoodleDownloadHelper.java   
protected void setupRequest(DownloadManager.Request r, Uri uri, String filename) {
    // add Moodle session cookie
    CookieManager cookieManager = CookieManager.getInstance();
    r.addRequestHeader("Cookie", cookieManager.getCookie("https://moodle.aau.at"));

    // This put the download in the same Download dir the browser uses
        r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
}
项目:Studentenportal    文件:MoodleDownloadHelper.java   
@Override
protected void setupRequest(Request r, Uri uri, String filename) {
    super.setupRequest(r, uri, filename);

    Log.d("MoodleDownloadHelper", "SR HC");

    // When downloading music and videos they will be listed in the player
        // (Seems to be available since Honeycomb only)
        r.allowScanningByMediaScanner();

        // Notify user when download is completed
        // (Seems to be available since Honeycomb only)
        r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
项目:vtu-life-android    文件:SystemFeatureChecker.java   
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static void manageApiIssues(Request request) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
            request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        } else {
            request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
        }
    } else
        request.setShowRunningNotification(true);
}
项目:geoar-app    文件:PluginDownloader.java   
public static void downloadPlugin(PluginDownloadHolder dataSource) {

        Request request = new DownloadManager.Request(
                dataSource.getDownloadLink());
        request.setDestinationInExternalFilesDir(
                GeoARApplication.applicationContext, null,
                dataSource.getIdentifier() + ".apk");
        request.setTitle("GeoAR Data Souce Download");
        request.setMimeType("application/vnd.52north.datasources");
        request.setDescription(dataSource.getName());
        currentDownloads.add(mDownloadManager.enqueue(request));
    }
项目:Flight-Computer-Android-Flightradar24    文件:DownloadActivity.java   
public void onClick(View view) {
    dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    Request request = new Request(
            Uri.parse(urlET.getText().toString()));
    Log.v("MapActivity", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
            "baseline.mbtiles");
    enqueue = dm.enqueue(request);   
}
项目:onedrive-picker-android    文件:PickerMain.java   
@Override
public void onClick(final View v) {
    if (mDownloadUrl == null) {
        return;
    }

    final DownloadManager downloadManager = (DownloadManager)v.getContext().getSystemService(DOWNLOAD_SERVICE);
    final Request request = new Request(mDownloadUrl);
    request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    downloadManager.enqueue(request);
}
项目:amar-android-demo    文件:Internet1Activity.java   
private void listing603( String url )
{
    /**
     * Listing 6-3: Downloading files using the Download Manager
     */
    String serviceString = Context.DOWNLOAD_SERVICE;
    DownloadManager downloadManager = ( DownloadManager ) getSystemService( serviceString );

    DownloadManager.Request request = new Request( Uri.parse( url ) );
    long reference = downloadManager.enqueue( request );

    myDownloadReference = reference;
    Log.d( TAG, "Download Reference: " + reference );
}
项目:Fairphone    文件:FairphoneUpdater.java   
private void startUpdateDownload() {
    // use only on WiFi
    if (isWiFiEnabled()) {
        // set the download for the latest version on the download manager
        String fileName = VersionParserHelper
                .getNameFromVersion(mLatestVersion);
        Request request = createDownloadRequest(
                mLatestVersion.getDownloadLink(), fileName,
                mLatestVersion.getName() + " FP Update");
        mLatestUpdateDownloadId = mDownloadManager.enqueue(request);

        // save it on the shared preferences
        savePreference(PREFERENCE_DOWNLOAD_ID, mLatestUpdateDownloadId);

        // change state to download
        changeState(UpdaterState.DOWNLOAD);
    } else {
        Resources resources = this.getResources();

        AlertDialog.Builder disclaimerDialog = new AlertDialog.Builder(this);

        disclaimerDialog.setTitle(resources
                .getString(R.string.wifiDiscaimerTitle));

        // Setting Dialog Message
        disclaimerDialog.setMessage(resources
                .getString(R.string.wifiDiscaimerMessage));
        disclaimerDialog.setPositiveButton(
                resources.getString(android.R.string.ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // do nothing, since the state is still the same
                    }
                });
        disclaimerDialog.create();
        disclaimerDialog.show();
    }
}
项目:Fairphone    文件:UpdaterService.java   
public void startDownloadLatest() {
    if(hasConnection()){
        Resources resources = getApplicationContext().getResources();

        // set the download for the latest version on the download manager
        Request request = createDownloadRequest(resources.getString(R.string.downloadUrl), resources.getString(R.string.versionFilename) + resources.getString(R.string.versionFilename_zip));
        mLatestFileDownloadId = mDownloadManager.enqueue(request);
    }
}
项目:codeexamples-android    文件:DownloadManagerActivity.java   
public void onClick(View view) {
    dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    Request request = new Request(
            Uri.parse("http://www.vogella.de/img/lars/LarsVogelArticle7.png"));
    enqueue = dm.enqueue(request);

}
项目:detlef    文件:DetlefDownloadManager.java   
public void enqueue(DownloadCallback callback) throws IOException {
    if (!isExternalStorageWritable()) {
        throw new IOException("Cannot write to external storage");
    }

    Uri source = callback.getSource();

    /* Ensure the destination directory already exists. */

    File destination = new File(Detlef.getAppContext().getExternalFilesDir(
                                    callback.getDestinationDirType()), callback.getDestinationSubPath());
    destination.getParentFile().mkdirs();

    Request request = new Request(source);
    request.setDestinationInExternalFilesDir(context, callback.getDestinationDirType(),
            callback.getDestinationSubPath());
    request.addRequestHeader("user-agent", Detlef.USER_AGENT);
    request.setTitle(callback.getTitle());
    request.setDescription(callback.getDescription());
    request.setNotificationVisibility(callback.getNotificationVisibility());

    long id = downloadManager.enqueue(request);
    activeDownloads.put(id, callback);

    callback.onStart(destination.getAbsolutePath());

    Log.v(TAG, String.format("Enqueued download with id %d", id));
}
项目:GuiLib    文件:Downloader.java   
public void download(String path,boolean unzip) {
    Request request = new Request(Uri.parse(path));
    if (unzip)
        todoUnzip.add(downloadManager.enqueue(request));
    else
        downloadManager.enqueue(request);
}
项目:goloader    文件:FfmpegDownloadService.java   
private void downloadFfmpeg() {
    String link = getString(R.string.ffmpeg_download_dialog_msg_link, cpuVers);

    Utils.logger("d", "FFmpeg download link: " + link, DEBUG_TAG);

       Request request = new Request(Uri.parse(link));
       request.setDestinationInExternalFilesDir(nContext, null, ffmpegBinName);
       request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
       request.setVisibleInDownloadsUi(false);
       request.setTitle(getString(R.string.ffmpeg_download_notification));
       dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
       try {
        enqueue = dm.enqueue(request);
       } catch (IllegalArgumentException e) {
        Log.e(DEBUG_TAG, "downloadFfmpeg: " + e.getMessage());
        Toast.makeText(this,  this.getString(R.string.no_downloads_sys_app), Toast.LENGTH_LONG).show();
        BugSenseHandler.sendExceptionMessage(DEBUG_TAG + "-> downloadFfmpeg", e.getMessage(), e);
    } catch (SecurityException se) {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, ffmpegBinName);
        enqueue = dm.enqueue(request);
        DIR = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        BugSenseHandler.sendExceptionMessage(DEBUG_TAG + "-> downloadFfmpeg", se.getMessage(), se);
    } catch (NullPointerException ne) {
        Log.e(DEBUG_TAG, "callDownloadApk: " + ne.getMessage());
        BugSenseHandler.sendExceptionMessage(DEBUG_TAG + "-> callDownloadApk: ", ne.getMessage(), ne);
        Toast.makeText(this, getString(R.string.error), Toast.LENGTH_LONG).show();
    }

    ffmpegBinObserver = new Observer.YtdFileObserver(DIR);
       ffmpegBinObserver.startWatching();
}
项目:AndroidAppDeployer    文件:Downloader.java   
public void downloadFile(String appVersion, String token) {
    String url;
    String name;
    String version;
    Cursor cursor = mCr.query(
            AppContract.AppVersions.CONTENT_URI.buildUpon()
                    .appendPath(appVersion)
                    .appendQueryParameter("limit", "1").build(),
            new String[] { AppContract.AppVersions.VERSION,
                    AppContract.Apps.NAME,
                    AppContract.AppVersions.DOWNLOAD_URL }, null, null,
            null);
    try {
        if (!cursor.moveToFirst()) {
            return;
        }
        version = cursor.getString(0);
        name = cursor.getString(1);
        url = cursor.getString(2);

    } finally {
        cursor.close();
    }
    if (url == null) {
        return;
    }
    Uri uri = Uri.parse(url);
    DownloadManager downloadManager = (DownloadManager) mContext
            .getSystemService(Context.DOWNLOAD_SERVICE);
    String title = String.format("%s (%s)", name, version);
    Request request = new DownloadManager.Request(uri)
            .addRequestHeader("Authorization", "Bearer " + token)
            .setTitle(title).setVisibleInDownloadsUi(true)
            .setMimeType("application/vnd.android.package-archive");
    setRequestNotificationStatus(request);
    downloadManager.enqueue(request);
}
项目:AndroidAppDeployer    文件:Downloader.java   
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setRequestNotificationStatus(Request request) {
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        request.setNotificationVisibility(
                DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    } else {
        request.setShowRunningNotification(true);
    }
}
项目:DsaTab    文件:Downloader.java   
public void download(String path,boolean unzip) {
    Request request = new Request(Uri.parse(path));
    if (unzip)
        todoUnzip.add(downloadManager.enqueue(request));
    else
        downloadManager.enqueue(request);
}
项目:FicsaveMiddleware    文件:FicsaveDownloadListener.java   
private void downloadFile() {
    // Guess file name from metadata
    fileName = URLUtil.guessFileName(downloadUrl, downloadContentDisposition, downloadMimeType);
    Request request = new Request(Uri.parse(downloadUrl));

    // Make media scanner scan this file so that other apps can use it.
    request.allowScanningByMediaScanner();

    // show notification when downloading and after download completes
    request.setNotificationVisibility(
            Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
    );

    // Set the directory where to save the file
    Log.d("ficsaveM/filePath", Environment.DIRECTORY_DOCUMENTS + "/" + fileName);
    request.setDestinationInExternalPublicDir(
            Environment.DIRECTORY_DOCUMENTS, fileName);

    request.setMimeType(downloadMimeType);
    request.setTitle(fileName);

    // Set headers needed to download the file
    String cookies = CookieManager.getInstance().getCookie(downloadUrl);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", downloadUserAgent);

    fileDownloadId = mDownloadManager.enqueue(request);
    Log.d("ficsaveM/DownloadStartd", "fileID: " + fileDownloadId + ", fileName: " + fileName);
    Toast.makeText(mContext, R.string.downloading_file_toast_msg, //To notify the Client that the file is being downloaded
            Toast.LENGTH_LONG).show();

    mGTracker.send(new HitBuilders.EventBuilder()
            .setCategory(DOWNLOAD_LISTENER_CATEGORY)
            .setAction("Download Enqueued")
            .setLabel(FILE_LABEL + fileName)
            .setValue(1)
            .build());
    Bundle bundle = new Bundle();
    bundle.putString("File", fileName);
    mFTracker.logEvent("DownloadEnqueued", bundle);
}
项目:AOSP-Kayboard-7.1.2    文件:ActionBatch.java   
@Override
public void execute(final Context context) {
    if (null == mWordList) { // This should never happen
        Log.e(TAG, "UpdateAction with a null parameter!");
        return;
    }
    DebugLogUtils.l("Downloading word list");
    final SQLiteDatabase db = MetadataDbHelper.getDb(context, mClientId);
    final ContentValues values = MetadataDbHelper.getContentValuesByWordListId(db,
            mWordList.mId, mWordList.mVersion);
    final int status = values.getAsInteger(MetadataDbHelper.STATUS_COLUMN);
    final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
    if (MetadataDbHelper.STATUS_DOWNLOADING == status) {
        // The word list is still downloading. Cancel the download and revert the
        // word list status to "available".
        manager.remove(values.getAsLong(MetadataDbHelper.PENDINGID_COLUMN));
        MetadataDbHelper.markEntryAsAvailable(db, mWordList.mId, mWordList.mVersion);
    } else if (MetadataDbHelper.STATUS_AVAILABLE != status
            && MetadataDbHelper.STATUS_RETRYING != status) {
        // Should never happen
        Log.e(TAG, "Unexpected state of the word list '" + mWordList.mId + "' : " + status
                + " for an upgrade action. Fall back to download.");
    }
    // Download it.
    DebugLogUtils.l("Upgrade word list, downloading", mWordList.mRemoteFilename);

    // This is an upgraded word list: we should download it.
    // Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
    // DownloadManager also stupidly cuts the extension to replace with its own that it
    // gets from the content-type. We need to circumvent this.
    final String disambiguator = "#" + System.currentTimeMillis()
            + ApplicationUtils.getVersionName(context) + ".dict";
    final Uri uri = Uri.parse(mWordList.mRemoteFilename + disambiguator);
    final Request request = new Request(uri);

    final Resources res = context.getResources();
    request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
    request.setTitle(mWordList.mDescription);
    request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
    request.setVisibleInDownloadsUi(
            res.getBoolean(R.bool.dict_downloads_visible_in_download_UI));

    final long downloadId = UpdateHandler.registerDownloadRequest(manager, request, db,
            mWordList.mId, mWordList.mVersion);
    Log.i(TAG, String.format("Starting the dictionary download with version:"
                    + " %d and Url: %s", mWordList.mVersion, uri));
    DebugLogUtils.l("Starting download of", uri, "with id", downloadId);
    PrivateLog.log("Starting download of " + uri + ", id : " + downloadId);
}