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:net.mandaria.radioreddit.apis.RadioRedditAPI.java

public static void Download(Context context, RadioSong song, RadioEpisode episode) {
    String downloadURL = "";
    String title = "";
    String description = "radio reddit";

    String songTitle = context.getString(R.string.app_name);
    String songArtist = "";
    String filename = "";

    if (song != null && song.Download_url != null) {
        if (song.Title != null)
            songTitle = song.Title;/* w w  w . ja v a  2s.c  o  m*/
        if (song.Artist != null && song.Redditor != null)
            songArtist = song.Artist + " (" + song.Redditor + ")";

        downloadURL = song.Download_url;
    } else if (episode != null && episode.Download_url != null) {
        if (episode.EpisodeTitle != null)
            songTitle = episode.EpisodeTitle;
        if (episode.ShowTitle != null)
            songArtist = episode.ShowTitle;

        downloadURL = episode.Download_url;
    }

    title = songTitle + " by " + songArtist;

    filename = songArtist + " " + songTitle + ".mp3";
    filename = filename.replace(" ", "_");

    if (!downloadURL.equals("")) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(downloadURL);

        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
        path = new File(path, "radioreddit");
        path.mkdirs();

        DownloadManager.Request request = new DownloadManager.Request(uri);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        }

        request.setTitle(title).setDescription(description).setMimeType("audio/mpeg")
                .setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, "/radioreddit/" + filename);

        long lastDownload = -1L;
        lastDownload = downloadManager.enqueue(request);
    }
}

From source file:com.viktorrudometkin.burramys.fragment.EntryFragment.java

@Override
public void onClickEnclosure() {
    getActivity().runOnUiThread(new Runnable() {
        @Override//from w w  w.  java2 s.  co m
        public void run() {
            final String enclosure = mEntryPagerAdapter.getCursor(mCurrentPagerPos).getString(mEnclosurePos);

            final int position1 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR);
            final int position2 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR, position1 + 3);

            final Uri uri = Uri.parse(enclosure.substring(0, position1));
            final String filename = uri.getLastPathSegment();

            new AlertDialog.Builder(getActivity()).setTitle(R.string.open_enclosure)
                    .setMessage(getString(R.string.file) + ": " + filename)
                    .setPositiveButton(R.string.open_link, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showEnclosure(uri, enclosure, position1, position2);
                        }
                    }).setNegativeButton(R.string.download_and_save, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                DownloadManager.Request r = new DownloadManager.Request(uri);
                                r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
                                r.allowScanningByMediaScanner();
                                r.setNotificationVisibility(
                                        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager dm = (DownloadManager) MainApplication.getContext()
                                        .getSystemService(Context.DOWNLOAD_SERVICE);
                                dm.enqueue(r);
                            } catch (Exception e) {
                                UiUtils.showMessage(getActivity(), R.string.error);
                            }
                        }
                    }).show();
        }
    });
}

From source file:de.baumann.hhsmoodle.fragmentsMain.FragmentBrowser.java

@SuppressWarnings("ResultOfMethodCallIgnored")
@SuppressLint("SetJavaScriptEnabled")

@Override/*  ww w .  j  a  v  a2 s.co m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_screen_browser, container, false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        WebView.enableSlowWholeDocumentDraw();
    }

    PreferenceManager.setDefaultValues(getActivity(), R.xml.user_settings, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    sharedPref.edit().putString("browserStarted", "true").apply();

    customViewContainer = (FrameLayout) rootView.findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
    viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (WebView) rootView.findViewById(R.id.webView);
    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) rootView.findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) rootView.findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(getActivity(), mWebView);
    helper_webView.webView_WebViewClient(getActivity(), swipeView, mWebView);

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename,
                            Snackbar.LENGTH_INDEFINITE)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(newFileDest(), filename);
                            DownloadManager dm = (DownloadManager) getActivity()
                                    .getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_LONG).show();
                            getActivity().registerReceiver(onComplete,
                                    new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                        }
                    });
            snackbar.show();
        }
    });

    String URLtoOpen = sharedPref.getString("loadURL", "");
    if (URLtoOpen.isEmpty()) {
        mWebView.loadUrl(
                sharedPref.getString("favoriteURL", "https://moodle.huebsch.ka.schule-bw.de/moodle/my/"));
    } else {
        mWebView.loadUrl(URLtoOpen);
    }

    setHasOptionsMenu(true);
    return rootView;
}

From source file:com.appjma.appdeployer.service.Downloader.java

public void downloadFile(String appVersion, String token) {
    String url;/*from ww  w  .  j  a  va  2 s  .c om*/
    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);
}

From source file:com.flym.dennikn.fragment.EntryFragment.java

@Override
public void onClickEnclosure() {
    getActivity().runOnUiThread(new Runnable() {
        @Override/* www . j  a v a 2s .com*/
        public void run() {
            final String enclosure = mEntryPagerAdapter.getCursor(mCurrentPagerPos).getString(mEnclosurePos);

            final int position1 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR);
            final int position2 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR, position1 + 3);

            final Uri uri = Uri.parse(enclosure.substring(0, position1));
            final String filename = uri.getLastPathSegment();

            new AlertDialog.Builder(getActivity()).setTitle(R.string.open_enclosure)
                    .setMessage(getString(R.string.file) + ": " + filename)
                    .setPositiveButton(R.string.open_link, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showEnclosure(uri, enclosure, position1, position2);
                        }
                    }).setNegativeButton(R.string.download_and_save, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                DownloadManager.Request r = new DownloadManager.Request(uri);
                                r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
                                r.allowScanningByMediaScanner();
                                r.setNotificationVisibility(
                                        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager dm = (DownloadManager) MainApplication.getContext()
                                        .getSystemService(Context.DOWNLOAD_SERVICE);
                                dm.enqueue(r);
                            } catch (Exception e) {
                                Toast.makeText(getActivity(), R.string.error, Toast.LENGTH_LONG).show();
                            }
                        }
                    }).show();
        }
    });
}

From source file:com.carlrice.reader.fragment.EntryFragment.java

@Override
public void onClickEnclosure() {
    getActivity().runOnUiThread(new Runnable() {
        @Override//  w ww.  j  ava  2  s.c o m
        public void run() {
            final String enclosure = mEntryPagerAdapter.getCursor(mCurrentPagerPos).getString(mEnclosurePos);

            final int position1 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR);
            final int position2 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR, position1 + 3);

            final Uri uri = Uri.parse(enclosure.substring(0, position1));
            final String filename = uri.getLastPathSegment();

            new AlertDialog.Builder(getActivity()).setTitle(R.string.open_enclosure)
                    .setMessage(getString(R.string.file) + ": " + filename)
                    .setPositiveButton(R.string.open_link, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showEnclosure(uri, enclosure, position1, position2);
                        }
                    }).setNegativeButton(R.string.download_and_save, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                DownloadManager.Request r = new DownloadManager.Request(uri);
                                r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
                                r.allowScanningByMediaScanner();
                                r.setNotificationVisibility(
                                        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager dm = (DownloadManager) Application.context()
                                        .getSystemService(Context.DOWNLOAD_SERVICE);
                                dm.enqueue(r);
                            } catch (Exception e) {
                                Toast.makeText(getActivity(), R.string.error, Toast.LENGTH_LONG).show();
                            }
                        }
                    }).show();
        }
    });
}

From source file:com.giovanniterlingen.windesheim.controllers.WebViewController.java

public WebView createWebView() {
    WebView webView = new WebView(activity);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setSupportZoom(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(false);

    webView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            int lastSlash = url.lastIndexOf('/');
            String fileName = url.substring(lastSlash + 1);

            DownloadManager downloadManager = (DownloadManager) activity
                    .getSystemService(Context.DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.addRequestHeader("Cookie", new CookieController().getNatSchoolCookie()).setTitle(fileName)
                    .setDescription(activity.getResources().getString(R.string.downloading))
                    .setDestinationInExternalPublicDir(File.separator
                            + ApplicationLoader.applicationContext.getResources().getString(R.string.app_name),
                            fileName)/* w  w w  .  j  a  v  a2 s .  com*/
                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            downloadManager.enqueue(request);
        }
    });
    return webView;
}

From source file:jupiter.broadcasting.live.holo.JBPlayer.java

public void DownLoad(String url) {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    String ver = (av == 0) ? getString(R.string.audio) : getString(R.string.video);
    request.setDescription(getString(R.string.progress) + "(" + ver + ")...");
    request.setTitle(getIntent().getStringExtra("title"));

    down.setClickable(false);/*w  w  w . j  a v  a 2  s . c  om*/

    // 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);
    }
    String ext = (av == 0) ? "mp3" : "mp4";
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PODCASTS + "/JB",
            getIntent().getStringExtra("title") + "." + ext);

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

    //register receiver to be notified when download finishes
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(enqueue);
                Cursor c = manager.query(query);
                if (c != null) {
                    if (c.moveToFirst()) {
                        int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                        if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                            Toast.makeText(getBaseContext(), "Finished", Toast.LENGTH_LONG).show();
                            hasit = true;
                            down.setClickable(true);
                        }
                    }
                }
            }
        }
    };

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

From source file:org.cgnet.swara.fragment.EntryFragment.java

@Override
public void onClickEnclosure() {
    getActivity().runOnUiThread(new Runnable() {
        //TODO/* ww  w. j  a  v  a  2  s. c  om*/

        @Override
        public void run() {
            final String enclosure = mEntryPagerAdapter.getCursor(mCurrentPagerPos).getString(mEnclosurePos);

            final int position1 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR);
            final int position2 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR, position1 + 3);

            final Uri uri = Uri.parse(enclosure.substring(0, position1));
            final String filename = uri.getLastPathSegment();

            t.send(new HitBuilders.EventBuilder().setCategory("Button to download audio file was clicked on")
                    .setAction(filename).build());

            new AlertDialog.Builder(getActivity()).setTitle(R.string.open_enclosure)
                    //                        .setMessage(getString(R.string.file) + ": " + filename)
                    .setNegativeButton(R.string.cancel_phone, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // showEnclosure(uri, enclosure, position1, position2);
                            t.send(new HitBuilders.EventBuilder()
                                    .setCategory("Button to download audio file was clicked on")
                                    .setAction(filename).setValue(0).build());
                        }
                    }).setPositiveButton(R.string.download_and_save, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                t.send(new HitBuilders.EventBuilder()
                                        .setCategory("Button to download audio file was clicked on")
                                        .setAction(filename).setValue(1).build());

                                DownloadManager.Request r = new DownloadManager.Request(uri);
                                r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
                                r.allowScanningByMediaScanner();
                                r.setNotificationVisibility(
                                        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                r.setVisibleInDownloadsUi(true);

                                String name = new File(uri.toString()).getName();

                                String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                                path += "/CGNet_Swara";
                                File dir = new File(path);
                                if (!dir.exists() || !dir.isDirectory()) {
                                    dir.mkdirs();
                                }

                                r.setDestinationInExternalPublicDir("CGNet_Swara", name);

                                DownloadManager dm = (DownloadManager) MainApplication.getContext()
                                        .getSystemService(Context.DOWNLOAD_SERVICE);
                                dm.enqueue(r);

                                Cursor c = mEntryPagerAdapter.getCursor(mCurrentPagerPos);

                                refreshUI(c);

                                // TODO
                            } catch (Exception e) {
                                Toast.makeText(getActivity(), R.string.error, Toast.LENGTH_LONG).show();
                            }
                        }
                    }).show();
        }
    });
}

From source file:com.avalond.ad_blocak.MainActivity.java

private void refresh() {
    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

    for (Configuration.Item item : config.hosts.items) {
        File file = FileHelper.getItemFile(this, item);

        if (file != null && item.state != 2) {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(item.location));
            Log.d("MainActivity",
                    String.format("refresh: Downkoading %s to %s", item.location, file.getAbsolutePath()));
            file.delete();/*from www  .j  a v  a2s. c o  m*/
            request.setDestinationUri(Uri.fromFile(file));
            request.setTitle(item.title);
            request.setVisibleInDownloadsUi(false);
            dm.enqueue(request);
        }
    }
}