Example usage for android.app DownloadManager enqueue

List of usage examples for android.app DownloadManager enqueue

Introduction

In this page you can find the example usage for android.app DownloadManager enqueue.

Prototype

public long enqueue(Request request) 

Source Link

Document

Enqueue a new download.

Usage

From source file:es.usc.citius.servando.calendula.fragments.MedicinesListFragment.java

public void downloadProspect(Prescription p) {

    final String uri = PROSPECT_URL.replaceAll("#ID#", p.pid);
    File prospects = new File(
            getActivity().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                    + "/prospects/");
    prospects.mkdirs();/*from ww  w .ja v a 2 s  .c om*/
    DownloadManager.Request r = new DownloadManager.Request(Uri.parse(uri));

    Log.d("MedicinesListF", "Downloading prospect from  [" + uri + "]");

    r.setDestinationInExternalFilesDir(getActivity(), Environment.DIRECTORY_DOWNLOADS,
            "prospects/" + p.pid + ".pdf");
    r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
    r.setVisibleInDownloadsUi(false);
    r.setTitle(p.shortName() + " prospect");
    // Start download
    prospectDowloadCn = p.cn;
    DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
    dm.enqueue(r);
}

From source file:org.catrobat.catroid.ui.WebViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);

    ActionBar actionBar = getActionBar();
    actionBar.hide();//from ww w  .j  a va2s .  c  om

    Intent intent = getIntent();
    url = intent.getStringExtra(INTENT_PARAMETER_URL);
    if (url == null) {
        url = Constants.BASE_URL_HTTPS;
    }
    callingActivity = intent.getStringExtra(CALLING_ACTIVITY);

    webView = (WebView) findViewById(R.id.webView);
    webView.setBackgroundColor(
            ResourcesCompat.getColor(getResources(), R.color.application_background_color, null));
    webView.setWebViewClient(new MyWebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    String language = String.valueOf(Constants.CURRENT_CATROBAT_LANGUAGE_VERSION);
    String flavor = Constants.FLAVOR_DEFAULT;
    String version = Utils.getVersionName(getApplicationContext());
    String platform = Constants.PLATFORM_DEFAULT;
    webView.getSettings().setUserAgentString(
            "Catrobat/" + language + " " + flavor + "/" + version + " Platform/" + platform);

    webView.loadUrl(url);

    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Log.d(WebViewActivity.class.getSimpleName(),
                    "contentDisposition: " + contentDisposition + "   " + mimetype);

            if (getExtensionFromContentDisposition(contentDisposition).contains(Constants.CATROBAT_EXTENSION)) {
                DownloadUtil.getInstance().prepareDownloadAndStartIfPossible(WebViewActivity.this, url);
            } else if (url.contains(Constants.LIBRARY_BASE_URL)) {
                String name = getMediaNameFromUrl(url);
                String mediaType = getMediaTypeFromContentDisposition(contentDisposition);
                String fileName = name + getExtensionFromContentDisposition(contentDisposition);
                String tempPath = null;
                switch (mediaType) {
                case Constants.MEDIA_TYPE_LOOK:
                    tempPath = Constants.TMP_LOOKS_PATH;
                    break;
                case Constants.MEDIA_TYPE_SOUND:
                    tempPath = Constants.TMP_SOUNDS_PATH;
                }
                String filePath = Utils.buildPath(tempPath, fileName);
                resultIntent.putExtra(MEDIA_FILE_PATH, filePath);
                DownloadUtil.getInstance().prepareMediaDownloadAndStartIfPossible(WebViewActivity.this, url,
                        mediaType, name, filePath, callingActivity);
            } else {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                request.setTitle(getString(R.string.notification_download_title_pending) + " "
                        + DownloadUtil.getInstance().getProjectNameFromUrl(url));
                request.setDescription(getString(R.string.notification_download_pending));
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                        DownloadUtil.getInstance().getProjectNameFromUrl(url) + ANDROID_APPLICATION_EXTENSION);
                request.setMimeType(mimetype);

                registerReceiver(onDownloadComplete,
                        new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

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

From source file:com.creativtrendz.folio.ui.FolioWebViewScroll.java

/**
 * Handles a download by loading the file from `fromUrl` and saving it to `toFilename` on the external storage
 * <p/>/*from   w w w . j a  va2 s. co m*/
 * This requires the two permissions `android.permission.INTERNET` and `android.permission.WRITE_EXTERNAL_STORAGE`
 * <p/>
 * Only supported on API level 9 (Android 2.3) and above
 *
 * @param context    a valid `Context` reference
 * @param fromUrl    the URL of the file to download, e.g. the one from `AdvancedWebView.onDownloadRequested(...)`
 * @param toFilename the name of the destination file where the download should be saved, e.g. `myImage.jpg`
 * @return whether the download has been successfully handled or not
 */
@SuppressLint("NewApi")
public static boolean handleDownload(final Context context, final String fromUrl, final String toFilename) {
    if (Build.VERSION.SDK_INT < 9) {
        throw new RuntimeException("Method requires API level 9 or above");
    }

    final Request request = new Request(Uri.parse(fromUrl));
    if (Build.VERSION.SDK_INT >= 11) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, toFilename);

    final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    try {
        try {
            dm.enqueue(request);
        } catch (SecurityException e) {
            if (Build.VERSION.SDK_INT >= 11) {
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            }
            dm.enqueue(request);
        }

        return true;
    }
    // if the download manager app has been disabled on the device
    catch (IllegalArgumentException e) {
        // show the settings screen where the user can enable the download manager app again
        openAppSettings(context, FolioWebViewScroll.PACKAGE_NAME_DOWNLOAD_MANAGER);

        return false;
    }
}

From source file:im.delight.android.webview.AdvancedWebView.java

/**
 * Handles a download by loading the file from `fromUrl` and saving it to `toFilename` on the external storage
 * <p/>/*from w w w  .java 2s .  c  om*/
 * This requires the two permissions `android.permission.INTERNET` and `android.permission.WRITE_EXTERNAL_STORAGE`
 * <p/>
 * Only supported on API level 9 (Android 2.3) and above
 *
 * @param context    a valid `Context` reference
 * @param fromUrl    the URL of the file to download, e.g. the one from `AdvancedWebView.onDownloadRequested(...)`
 * @param toFilename the name of the destination file where the download should be saved, e.g. `myImage.jpg`
 * @return whether the download has been successfully handled or not
 */
@SuppressLint("NewApi")
public static boolean handleDownload(final Context context, final String fromUrl, final String toFilename) {
    if (Build.VERSION.SDK_INT < 9) {
        throw new RuntimeException("Method requires API level 9 or above");
    }

    final Request request = new Request(Uri.parse(fromUrl));
    if (Build.VERSION.SDK_INT >= 11) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, toFilename);

    final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    try {
        try {
            dm.enqueue(request);
        } catch (SecurityException e) {
            if (Build.VERSION.SDK_INT >= 11) {
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            }
            dm.enqueue(request);
        }

        return true;
    }
    // if the download manager app has been disabled on the device
    catch (IllegalArgumentException e) {
        // show the settings screen where the user can enable the download manager app again
        openAppSettings(context, AdvancedWebView.PACKAGE_NAME_DOWNLOAD_MANAGER);

        return false;
    }
}

From source file:com.slarker.tech.hi0734.view.widget.webview.AdvancedWebView.java

/**
 * Handles a download by loading the file from `fromUrl` and saving it to `toFilename` on the external storage
 * <p>//w  ww .j  a  va2  s.  co  m
 * This requires the two permissions `android.permission.INTERNET` and `android.permission.WRITE_EXTERNAL_STORAGE`
 * <p>
 * Only supported on API level 9 (Android 2.3) and above
 *
 * @param context    a valid `Context` reference
 * @param fromUrl    the URL of the file to download, e.g. the one from `AdvancedWebView.onDownloadRequested(...)`
 * @param toFilename the name of the destination file where the download should be saved, e.g. `myImage.jpg`
 * @return whether the download has been successfully handled or not
 */
@SuppressLint("NewApi")
public static boolean handleDownload(final Context context, final String fromUrl, final String toFilename) {
    if (Build.VERSION.SDK_INT < 9) {
        throw new RuntimeException("Method requires API level 9 or above");
    }

    final Request request = new Request(Uri.parse(fromUrl));
    if (Build.VERSION.SDK_INT >= 11) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, toFilename);

    final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    try {
        try {
            dm.enqueue(request);
        } catch (SecurityException e) {
            if (Build.VERSION.SDK_INT >= 11) {
                request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
            }
            dm.enqueue(request);
        }

        return true;
    }
    // if the download manager app has been disabled on the device
    catch (IllegalArgumentException e) {
        // show the settings screen where the user can enable the download manager app again
        openAppSettings(context, AdvancedWebView.PACKAGE_NAME_DOWNLOAD_MANAGER);

        return false;
    }
}

From source file:com.murrayc.galaxyzoo.app.SubjectFragment.java

private void doDownloadImage() {
    //We download the image from the remote server again,
    //even though we already have it in the ContentProvider,
    //available via the mUriImageStandard content: URI,
    //just to get it into the DownloadManager UI.
    //Unfortunately the DownloadManager rejects content: URIs.
    if (TextUtils.isEmpty(mUriStandardRemote)) {
        Log.error("doDownloadImage(): mUriStandardRemote was null.");
        return;//from   ww  w . j a v  a  2s .  c  o  m
    }

    final Uri uri = Uri.parse(mUriStandardRemote);
    if (uri == null) {
        Log.error("doDownloadImage(): uri was null.");
        return;
    }

    final DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

    final Activity activity = getActivity();
    if (activity == null) {
        Log.error("doDownloadImage(): activity was null.");
        return;
    }

    final Object systemService = activity.getSystemService(Context.DOWNLOAD_SERVICE);
    if (systemService == null || !(systemService instanceof DownloadManager)) {
        Log.error("doDownloadImage(): Could not get DOWNLOAD_SERVICE.");
        return;
    }

    final DownloadManager downloadManager = (DownloadManager) systemService;
    downloadManager.enqueue(request);
}

From source file:me.kartikarora.transfersh.activities.DownloadActivity.java

private void beginDownload(String name, String type, String url) {
    mTracker.send(new HitBuilders.EventBuilder().setCategory("Action").setAction("Download : " + url).build());
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse(url);/*from   w  w w .j  a  va 2  s  .  c o  m*/
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setDescription(getString(R.string.app_name));
    request.setTitle(name);
    String dir = "/" + getString(R.string.app_name) + "/" + type + "/" + name;
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, dir);
    manager.enqueue(request);
}

From source file:org.botlibre.sdk.activity.graphic.GraphicActivity.java

public void downloadFile(View v) {

    if (gInstance.fileName.equals("")) {
        MainActivity.showMessage("Missing file!", this);
        return;/*  w ww. ja  v  a 2  s.  c o  m*/
    }

    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);
    }
}

From source file:com.p3authentication.preferences.Prefs.java

public void downloadFile(String BASEURL, String imagename) {
    // TODO Auto-generated method stub
    String DownloadUrl = BASEURL + "images/" + imagename;
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
    request.setDescription("P3 Resources"); // appears the same
    // in Notification
    // bar while/*from  ww  w.ja  v  a2  s  .  com*/
    // downloading
    request.setTitle("P3 Resources");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
    }
    String fileName = DownloadUrl.substring(DownloadUrl.lastIndexOf('/') + 1, DownloadUrl.length());
    request.setDestinationInExternalFilesDir(getApplicationContext(), null, fileName);

    // get download service and enqueue file
    DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    enqueue.offer(dm.enqueue(request));

}

From source file:com.pemikir.youtubeplus.DownloadDialog.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    arguments = getArguments();//  w  ww . jav  a2  s  .  c o m
    super.onCreateDialog(savedInstanceState);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.downloadDialogTitle).setItems(R.array.downloadOptions,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Context context = getActivity();
                    SharedPreferences defaultPreferences = PreferenceManager
                            .getDefaultSharedPreferences(context);
                    String suffix = "";
                    String title = arguments.getString(TITLE);
                    String url = "";
                    switch (which) {
                    case 0: // Video
                        suffix = arguments.getString(FILE_SUFFIX_VIDEO);
                        url = arguments.getString(VIDEO_URL);
                        break;
                    case 1:
                        suffix = arguments.getString(FILE_SUFFIX_AUDIO);
                        url = arguments.getString(AUDIO_URL);
                        break;
                    default:
                        Log.d(TAG, "lolz");
                    }
                    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                    request.setDestinationUri(
                            Uri.fromFile(new File(defaultPreferences.getString("download_path_preference",
                                    "/storage/emulated/0/NewPipe") + "/" + title + suffix)));
                    try {
                        dm.enqueue(request);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
    return builder.create();
}