Example usage for android.content Context DOWNLOAD_SERVICE

List of usage examples for android.content Context DOWNLOAD_SERVICE

Introduction

In this page you can find the example usage for android.content Context DOWNLOAD_SERVICE.

Prototype

String DOWNLOAD_SERVICE

To view the source code for android.content Context DOWNLOAD_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.app.DownloadManager for requesting HTTP downloads.

Usage

From source file:com.concentricsky.android.khanacademy.data.KADataService.java

private void updateDownloadStatus(Intent intent, final PendingIntent pendingIntent, final int startId) {
    final long id = intent.getLongExtra(EXTRA_ID, -1);
    final DownloadManager mgr = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    final DownloadManager.Query q = new DownloadManager.Query();
    q.setFilterById(id);//from   ww  w  . j a  v a  2 s .com

    new AsyncTask<Void, Void, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... arg) {
            Cursor cursor = mgr.query(q);
            String youtubeId = null;
            int status = -1;
            if (cursor.moveToFirst()) {
                String filename = cursor
                        .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                youtubeId = OfflineVideoManager.youtubeIdFromFilename(filename);
                status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            }
            cursor.close();

            if (status == DownloadManager.STATUS_SUCCESSFUL && youtubeId != null) {
                try {
                    Dao<Video, String> videoDao = helper.getVideoDao();
                    UpdateBuilder<Video, String> q = videoDao.updateBuilder();
                    q.where().eq("youtube_id", youtubeId);
                    q.updateColumnValue("download_status", Video.DL_STATUS_COMPLETE);
                    q.update();
                    return true;
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            return false;
        }

        @Override
        protected void onPostExecute(Boolean successful) {
            if (successful) {
                broadcastOfflineVideoSetChanged();
                finish(startId, pendingIntent, RESULT_SUCCESS);
            } else {
                finish(startId, pendingIntent, RESULT_ERROR);
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

}

From source file:com.android.mail.browse.AttachmentActionHandler.java

private File performAttachmentSave(final Attachment attachment) {
    try {//from w  ww  .ja  va  2 s . co m
        File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        downloads.mkdirs();
        File file = createUniqueFile(downloads, attachment.getName());
        Uri contentUri = attachment.contentUri;
        InputStream in = mContext.getContentResolver().openInputStream(contentUri);
        OutputStream out = new FileOutputStream(file);
        int size = IOUtils.copy(in, out);
        out.flush();
        out.close();
        in.close();
        String absolutePath = file.getAbsolutePath();
        MediaScannerConnection.scanFile(mContext, new String[] { absolutePath }, null, null);
        DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        dm.addCompletedDownload(attachment.getName(), attachment.getName(),
                false /* do not use media scanner */, attachment.getContentType(), absolutePath, size,
                true /* show notification */);
        Toast.makeText(mContext, mContext.getResources().getString(R.string.save_to) + absolutePath,
                Toast.LENGTH_SHORT).show();
        return file;
    } catch (IOException ioe) {
        // Ignore. Callers will handle it from the return code.
    }

    return null;
}

From source file:org.apache.cordova.backgroundDownload.BackgroundDownload.java

private long findActiveDownload(String uri) {
    DownloadManager mgr = (DownloadManager) cordova.getActivity().getSystemService(Context.DOWNLOAD_SERVICE);

    long downloadId = DOWNLOAD_ID_UNDEFINED;

    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING
            | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_SUCCESSFUL);
    Cursor cur = mgr.query(query);
    int idxId = cur.getColumnIndex(DownloadManager.COLUMN_ID);
    int idxUri = cur.getColumnIndex(DownloadManager.COLUMN_URI);
    for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
        if (uri.equals(cur.getString(idxUri))) {
            downloadId = cur.getLong(idxId);
            break;
        }/*  w ww .ja  v  a 2  s  . c  om*/
    }
    cur.close();

    return downloadId;
}

From source file:com.workingagenda.democracydroid.Adapters.ViewHolders.EpisodeViewHolder.java

@RequiresApi(api = Build.VERSION_CODES.M)
private void Download(String url, String title, String desc) {
    if (ContextCompat.checkSelfPermission(itemView.getContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ((Activity) itemView.getContext())
                .requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
        // TODO: catch onRequestPermissionsResult
    } else {//from w w  w  . j  a  v a  2s.c  om
        if ("http://democracynow.videocdn.scaleengine.net/democracynow-iphone/play/democracynow/playlist.m3u8"
                .equals(url)) {
            Toast toast = Toast.makeText(itemView.getContext(), "You can't download the Live Stream",
                    Toast.LENGTH_LONG);
            toast.show();
            return;
        }
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setDescription(desc);
        request.setTitle(title);
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        String fileext = url.substring(url.lastIndexOf('/') + 1);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PODCASTS, fileext);
        //http://stackoverflow.com/questions/24427414/getsystemservices-is-undefined-when-called-in-a-fragment

        // get download service and enqueue file
        DownloadManager manager = (DownloadManager) itemView.getContext()
                .getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);
        // TODO: Save que ID for cancel button
        Toast toast = Toast.makeText(itemView.getContext(), "Starting download of " + title, Toast.LENGTH_LONG);
        toast.show();
    }
}

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

public void downloadFile(String appVersion, String token) {
    String url;// w ww.  jav a  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:org.apache.cordova.backgroundDownload.BackgroundDownload.java

private Boolean checkDownloadCompleted(long id) {
    DownloadManager mgr = (DownloadManager) this.cordova.getActivity()
            .getSystemService(Context.DOWNLOAD_SERVICE);
    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(id);/*w  ww  . j a va  2  s  . c o m*/
    Cursor cur = mgr.query(query);
    int idxStatus = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
    int idxURI = cur.getColumnIndex(DownloadManager.COLUMN_URI);

    if (cur.moveToFirst()) {
        int status = cur.getInt(idxStatus);
        String uri = cur.getString(idxURI);
        Download curDownload = activDownloads.get(uri);
        if (status == DownloadManager.STATUS_SUCCESSFUL) { // TODO review what else we can have here
            copyTempFileToActualFile(curDownload);
            CleanUp(curDownload);
            return true;
        }
    }
    cur.close();

    return false;
}

From source file:com.laquysoft.droidconnl.Hunt.java

public void reloadFromRemote(Context context) {
    downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Uri Download_Uri = Uri.parse("http://162.248.167.159:8080/zip/hunt.zip");
    DownloadManager.Request request = new DownloadManager.Request(Download_Uri);

    request.setAllowedNetworkTypes(// ww  w  . ja v a  2  s  . c  om
            DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false).setTitle("NFC/IO Hunt").setDescription("Downloading Hunt data");

    //Enqueue a new download and same the referenceId
    downloadReference = downloadManager.enqueue(request);

}

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);/*from   ww  w  .  j  a va2  s.c o  m*/

    // 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.mozilla.focus.fragment.BrowserFragment.java

/**
 * Use Android's Download Manager to queue this download.
 *///from   ww  w.  j av  a  2  s  . c o  m
private void queueDownload(Download download) {
    if (download == null) {
        return;
    }

    final Context context = getContext();
    if (context == null) {
        return;
    }

    final String cookie = CookieManager.getInstance().getCookie(download.getUrl());
    final String fileName = URLUtil.guessFileName(download.getUrl(), download.getContentDisposition(),
            download.getMimeType());

    final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(download.getUrl()))
            .addRequestHeader("User-Agent", download.getUserAgent()).addRequestHeader("Cookie", cookie)
            .addRequestHeader("Referer", getUrl())
            .setDestinationInExternalPublicDir(download.getDestinationDirectory(), fileName)
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setMimeType(download.getMimeType());

    request.allowScanningByMediaScanner();

    final DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
}

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   w w  w.  j a  v  a 2 s .  c  o  m*/
    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);
}