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:org.chromium.chrome.browser.download.DownloadManagerDelegate.java

/**
 * @see android.app.DownloadManager#addCompletedDownload(String, String, boolean, String,
 * String, long, boolean)/*from   w w w.  j  a v a2  s. co m*/
 */
protected long addCompletedDownload(String fileName, String description, String mimeType, String path,
        long length, String originalUrl, String referer, String downloadGuid) {
    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
    boolean useSystemNotification = !notificationManager.areNotificationsEnabled();
    long downloadId = -1;
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        Class<?> c = manager.getClass();
        try {
            Class[] args = { String.class, String.class, boolean.class, String.class, String.class, long.class,
                    boolean.class, Uri.class, Uri.class };
            Method method = c.getMethod("addCompletedDownload", args);
            Uri originalUri = Uri.parse(originalUrl);
            Uri refererUri = referer == null ? Uri.EMPTY : Uri.parse(referer);
            downloadId = (Long) method.invoke(manager, fileName, description, true, mimeType, path, length,
                    useSystemNotification, originalUri, refererUri);
        } catch (SecurityException e) {
            Log.e(TAG, "Cannot access the needed method.");
        } catch (NoSuchMethodException e) {
            Log.e(TAG, "Cannot find the needed method.");
        } catch (InvocationTargetException e) {
            Log.e(TAG, "Error calling the needed method.");
        } catch (IllegalAccessException e) {
            Log.e(TAG, "Error accessing the needed method.");
        }
    } else {
        downloadId = manager.addCompletedDownload(fileName, description, true, mimeType, path, length,
                useSystemNotification);
    }
    addDownloadIdMapping(downloadId, downloadGuid);
    return downloadId;
}

From source file:com.cypher.cota.helpers.DownloadHelper.java

public static void checkDownloadFinished(Context context, long downloadId) {
    sContext = context;//from  w  w  w .  j  av a2 s  .  com
    if (sDownloadManager == null) {
        sDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    }
    checkDownloadFinished(downloadId, true);
}

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);// w  ww.  ja  v  a 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.amahi.anywhere.util.Downloader.java

private DownloadManager getDownloadManager(Context context) {
    return (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
}

From source file:de.escoand.readdaily.DownloadHandler.java

public static void stopDownload(final Context context, final String name) {
    Database db = Database.getInstance(context);
    Cursor c = db.getDownloads();
    long id = 0;//from   w ww.j  ava  2 s  .c  om

    // get download id
    while (c.moveToNext())
        if (c.getString(c.getColumnIndex(Database.COLUMN_SUBSCRIPTION)).equals(name)) {
            id = c.getLong(c.getColumnIndex(Database.COLUMN_ID));
            break;
        }
    c.close();
    if (id <= 0)
        return;

    // stop download
    ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).remove(id);
    db.removeDownload(id);
}

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

@Override
protected String doInBackground(final String... strings) {
    try {/*from   ww  w .j  ava2s. com*/
        activeDownloads.put(contentId, new Download());
        int lastSlash = url.lastIndexOf('/');
        String fileName = url.substring(lastSlash + 1);

        File directory = Environment.getExternalStoragePublicDirectory(
                ApplicationLoader.applicationContext.getResources().getString(R.string.app_name));
        if (!directory.exists()) {
            directory.mkdirs();
        }

        final String encodedUrl = new URI("https", "elo.windesheim.nl", url, null).toString();

        downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(encodedUrl));
        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);

        currentDownloadId = downloadManager.enqueue(request);
        while (true) {
            if (isCancelled()) {
                return "cancelled";
            }
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(currentDownloadId);
            Cursor cursor = downloadManager.query(query);
            if (cursor.getCount() == 0) {
                return "cancelled";
            }
            cursor.moveToFirst();
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            if (status == DownloadManager.STATUS_SUCCESSFUL || status == DownloadManager.STATUS_FAILED) {
                break;
            }
            if (status == DownloadManager.STATUS_PAUSED || status == DownloadManager.STATUS_PENDING) {
                // paused, reset download state to pending
                activeDownloads.put(contentId, new Download());
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.downloadPending,
                        studyRouteId, adapterPosition, contentId);
                Thread.sleep(100);
                continue;
            }
            long downloaded = cursor
                    .getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            long total = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            cursor.close();
            if (total > 0 && downloaded > 0) {
                int progress = (int) (downloaded * 100 / total);
                String s = Formatter.formatFileSize(activity, downloaded) + "/"
                        + Formatter.formatFileSize(activity, total);
                activeDownloads.get(contentId).setProgress(progress);
                activeDownloads.get(contentId).setProgressString(s);
                publishProgress(progress, s);
            }
            Thread.sleep(100);
        }
        return new File(directory, fileName).getAbsolutePath();
    } catch (SecurityException e) {
        return "permission";
    } catch (Exception e) {
        return null;
    }
}

From source file:org.openbmap.activities.DialogPreferenceCatalogs.java

/**
 * Initialises download manager for GINGERBREAD and newer
 *///from  w w  w  .  jav  a2s .  c  o  m
@SuppressLint("NewApi")
private void initDownloadManager() {
    mDownloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);

    mReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        @Override
        public void onReceive(final Context context, final Intent intent) {
            final String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                final DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                final Cursor c = mDownloadManager.query(query);
                if (c.moveToFirst()) {
                    final int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                        // we're not checking download id here, that is done in handleDownloads
                        final String uriString = c
                                .getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        handleDownloads(uriString);
                    } else {
                        final int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
                        Log.e(TAG, "Download failed: " + reason);
                    }
                }
            }
        }
    };

    getContext().registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

From source file:org.openbmap.activities.DialogPreferenceMaps.java

/**
 * Initialises download manager for GINGERBREAD and newer
 *//*  w  ww . ja va  2s.c  o  m*/
@SuppressLint("NewApi")
private void initDownloadManager() {

    mDownloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);

    mReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        @Override
        public void onReceive(final Context context, final Intent intent) {
            final String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                final DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                final Cursor c = mDownloadManager.query(query);
                if (c.moveToFirst()) {
                    final int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                        // we're not checking download id here, that is done in handleDownloads
                        final String uriString = c
                                .getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        handleDownloads(uriString);
                    } else {
                        final int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
                        Log.e(TAG, "Download failed: " + reason);
                    }
                }
            }
        }
    };

    getContext().registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

From source file:com.android.xbrowser.FetchUrlMimeType.java

@Override
public void run() {
    // User agent is likely to be null, though the AndroidHttpClient
    // seems ok with that.
    AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
    HttpHost httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
    if (httpHost != null) {
        ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
    }//from   w ww. j  a  v a  2s .  c o  m
    HttpHead request = new HttpHead(mUri);

    if (mCookies != null && mCookies.length() > 0) {
        request.addHeader("Cookie", mCookies);
    }

    HttpResponse response;
    String mimeType = null;
    String contentDisposition = null;
    try {
        response = client.execute(request);
        // We could get a redirect here, but if we do lets let
        // the download manager take care of it, and thus trust that
        // the server sends the right mimetype
        if (response.getStatusLine().getStatusCode() == 200) {
            Header header = response.getFirstHeader("Content-Type");
            if (header != null) {
                mimeType = header.getValue();
                final int semicolonIndex = mimeType.indexOf(';');
                if (semicolonIndex != -1) {
                    mimeType = mimeType.substring(0, semicolonIndex);
                }
            }
            Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
            if (contentDispositionHeader != null) {
                contentDisposition = contentDispositionHeader.getValue();
            }
        }
    } catch (IllegalArgumentException ex) {
        request.abort();
    } catch (IOException ex) {
        request.abort();
    } finally {
        client.close();
    }

    if (mimeType != null) {
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mUri));
            if (newMimeType != null) {
                mRequest.setMimeType(newMimeType);
            }
        }
        String filename = URLUtil.guessFileName(mUri, contentDisposition, mimeType);
        mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    }

    // Start the download
    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(mRequest);
}

From source file:no.digipost.android.utilities.FileUtilities.java

public static void makeFileVisible(Context context, File file) {
    JodaTimeAndroid.init(context);/*from  ww w. j av  a 2  s .  c  o m*/
    Long contentLength = Long.parseLong(DocumentContentStore.getDocumentAttachment().getFileSize());
    DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    String mimeType = getMimeType(file);
    String validMimeType = mimeType != null ? mimeType : "application/binary";
    manager.addCompletedDownload(getAttachmentFullFilename(), " ", true, validMimeType, file.getAbsolutePath(),
            contentLength, true);
}