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:ru.gkpromtech.exhibition.organizations.OrganizationFilesDownloader.java

private static void download(Context context, String url, Organization organization) {
    String dir = SharedData.EXTERNAL_DIR + "army2016/";
    String file = url.substring(url.lastIndexOf('/') + 1);

    //noinspection ResultOfMethodCallIgnored
    new File(dir).mkdirs();

    DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url));
    req.setTitle(organization.fullname);
    req.setDescription(context.getString(R.string.materials));
    req.allowScanningByMediaScanner();//from  ww w . j a va  2s  . c  o m
    req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    req.setDestinationUri(Uri.parse("file://" + dir + file));

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

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

public static void init(Context context, DownloadCallback callback) {
    sContext = context;/*from  w w  w.java2 s.  c om*/
    if (sDownloadManager == null) {
        sDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    }
    registerCallback(callback);
    checkIfDownloading();
}

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

public static float downloadProgress(final Context context, final String name) {
    Cursor cursor = Database.getInstance(context).getDownloads();
    long id = 0;/*from   w ww .j ava  2 s  .  c o  m*/
    float progress;

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

    // get download
    cursor = ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE))
            .query(new DownloadManager.Query().setFilterById(id));
    if (!cursor.moveToFirst()) {
        Database.getInstance(context).removeDownload(id);
        return DOWNLOAD_ID_UNKNOWN;
    }

    // get progress
    progress = cursor.getFloat(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
            / cursor.getFloat(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

    cursor.close();
    return progress;
}

From source file:ru.appsm.inapphelp.service.AttachmentDownloadReceiver.java

private void downloadCompleted(Context context, Intent intent) {
    StringBuilder text = new StringBuilder();
    //Files are  ready
    String filename = context.getString(R.string.iah_attachment);
    String filepath = null;//from  ww w  .j  a  v a2 s .  c o m
    String mediaType = null;
    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
    Query query = new Query();
    query.setFilterById(downloadId);
    Cursor c = dm.query(query);
    if (c.moveToFirst()) {
        int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
        filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
        filepath = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
        mediaType = c.getString(c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            text.append(context.getString(R.string.iah_download_complete));

        } else {
            text.append(context.getString(R.string.iah_error_during_download));
        }
    }

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder notificationbuilder = new NotificationCompat.Builder(context);
    notificationbuilder.setAutoCancel(true);
    notificationbuilder.setContentText(text.toString());
    notificationbuilder.setContentTitle(filename);
    notificationbuilder.setSmallIcon(R.drawable.iah_notification_download_light_img);
    notificationbuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
    notificationbuilder.setContentIntent(getPendingIntent(context));

    notificationManager.notify(filename, NOTIFICATION_ID, notificationbuilder.build());
}

From source file:com.tenmiles.helpstack.service.AttachmentDownloadReceiver.java

private void downloadCompleted(Context context, Intent intent) {
    StringBuilder text = new StringBuilder();
    //Files are  ready
    String filename = context.getString(R.string.hs_attachment);
    String filepath = null;//from  w w w. j  a  v  a  2  s . c  o m
    String mediaType = null;
    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
    Query query = new Query();
    query.setFilterById(downloadId);
    Cursor c = dm.query(query);
    if (c.moveToFirst()) {
        int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
        filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
        filepath = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
        mediaType = c.getString(c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            text.append(context.getString(R.string.hs_download_complete));

        } else {
            text.append(context.getString(R.string.hs_error_during_download));
        }
    }

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder notificationbuilder = new NotificationCompat.Builder(context);
    notificationbuilder.setAutoCancel(true);
    notificationbuilder.setContentText(text.toString());
    notificationbuilder.setContentTitle(filename);
    notificationbuilder.setSmallIcon(R.drawable.hs_notification_download_img);
    notificationbuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
    notificationbuilder.setContentIntent(getPendingIntent(context));

    notificationManager.notify(filename, NOTIFICATION_ID, notificationbuilder.build());
}

From source file:com.ota.updates.receivers.AppReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Bundle extras = intent.getExtras();/*ww w .  ja  v a  2s  .  c o  m*/
    long mRomDownloadID = Preferences.getDownloadID(context);

    if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
        long id = extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
        boolean isAddonDownload = false;
        int keyForAddonDownload = 0;

        Set<Integer> set = OtaUpdates.getAddonDownloadKeySet();
        Iterator<Integer> iterator = set.iterator();

        while (iterator.hasNext() && isAddonDownload != true) {
            int nextValue = iterator.next();
            if (id == OtaUpdates.getAddonDownload(nextValue)) {
                isAddonDownload = true;
                keyForAddonDownload = nextValue;
                if (DEBUGGING) {
                    Log.d(TAG, "Checking ID " + nextValue);
                }
            }
        }

        if (isAddonDownload) {
            DownloadManager downloadManager = (DownloadManager) context
                    .getSystemService(Context.DOWNLOAD_SERVICE);
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(id);
            Cursor cursor = downloadManager.query(query);

            // it shouldn't be empty, but just in case
            if (!cursor.moveToFirst()) {
                if (DEBUGGING)
                    Log.e(TAG, "Addon Download Empty row");
                return;
            }

            int statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            if (DownloadManager.STATUS_SUCCESSFUL != cursor.getInt(statusIndex)) {
                if (DEBUGGING)
                    Log.w(TAG, "Download Failed");
                Log.d(TAG, "Removing Addon download with id " + keyForAddonDownload);
                OtaUpdates.removeAddonDownload(keyForAddonDownload);
                AddonActivity.AddonsArrayAdapter.updateProgress(keyForAddonDownload, 0, true);
                AddonActivity.AddonsArrayAdapter.updateButtons(keyForAddonDownload, false);
                return;
            } else {
                if (DEBUGGING)
                    Log.v(TAG, "Download Succeeded");
                Log.d(TAG, "Removing Addon download with id " + keyForAddonDownload);
                OtaUpdates.removeAddonDownload(keyForAddonDownload);
                AddonActivity.AddonsArrayAdapter.updateButtons(keyForAddonDownload, true);
                return;
            }
        } else {
            if (DEBUGGING)
                Log.v(TAG, "Receiving " + mRomDownloadID);

            if (id != mRomDownloadID) {
                if (DEBUGGING)
                    Log.v(TAG, "Ignoring unrelated non-ROM download " + id);
                return;
            }

            DownloadManager downloadManager = (DownloadManager) context
                    .getSystemService(Context.DOWNLOAD_SERVICE);
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(id);
            Cursor cursor = downloadManager.query(query);

            // it shouldn't be empty, but just in case
            if (!cursor.moveToFirst()) {
                if (DEBUGGING)
                    Log.e(TAG, "Rom download Empty row");
                return;
            }

            int statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            if (DownloadManager.STATUS_SUCCESSFUL != cursor.getInt(statusIndex)) {
                if (DEBUGGING)
                    Log.w(TAG, "Download Failed");
                Preferences.setDownloadFinished(context, false);
                if (Utils.isLollipop()) {
                    AvailableActivity.setupMenuToolbar(context); // Reset options menu
                } else {
                    AvailableActivity.invalidateMenu();
                }
                return;
            } else {
                if (DEBUGGING)
                    Log.v(TAG, "Download Succeeded");
                Preferences.setDownloadFinished(context, true);
                AvailableActivity.setupProgress(context);
                if (Utils.isLollipop()) {
                    AvailableActivity.setupMenuToolbar(context); // Reset options menu
                } else {
                    AvailableActivity.invalidateMenu();
                }
                return;
            }
        }
    }

    if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {

        long[] ids = extras.getLongArray(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);

        for (long id : ids) {
            if (id != mRomDownloadID) {
                if (DEBUGGING)
                    Log.v(TAG, "mDownloadID is " + mRomDownloadID + " and ID is " + id);
                return;
            } else {
                Intent i = new Intent(context, AvailableActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
            }
        }
    }

    if (action.equals(MANIFEST_CHECK_BACKGROUND)) {
        if (DEBUGGING)
            Log.d(TAG, "Receiving background check confirmation");

        boolean updateAvailable = RomUpdate.getUpdateAvailability(context);
        String filename = RomUpdate.getFilename(context);

        if (updateAvailable) {
            Utils.setupNotification(context, filename);
            Utils.scheduleNotification(context, !Preferences.getBackgroundService(context));
        }
    }

    if (action.equals(START_UPDATE_CHECK)) {
        if (DEBUGGING)
            Log.d(TAG, "Update check started");
        new LoadUpdateManifest(context, false).execute();
    }

    if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
        if (DEBUGGING) {
            Log.d(TAG, "Boot received");
        }
        boolean backgroundCheck = Preferences.getBackgroundService(context);
        if (backgroundCheck) {
            if (DEBUGGING)
                Log.d(TAG, "Starting background check alarm");
            Utils.scheduleNotification(context, !Preferences.getBackgroundService(context));
        }
    }

    if (action.equals(IGNORE_RELEASE)) {
        if (DEBUGGING) {
            Log.d(TAG, "Ignore release");
        }
        Preferences.setIgnoredRelease(context, Integer.toString(RomUpdate.getVersionNumber(context)));
        final NotificationManager mNotifyManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Builder mBuilder = new NotificationCompat.Builder(context);
        mBuilder.setContentTitle(context.getString(R.string.main_release_ignored))
                .setSmallIcon(R.drawable.ic_notif)
                .setContentIntent(PendingIntent.getActivity(context, 0, new Intent(), 0));
        mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());

        Handler h = new Handler();
        long delayInMilliseconds = 1500;
        h.postDelayed(new Runnable() {

            public void run() {
                mNotifyManager.cancel(NOTIFICATION_ID);
            }
        }, delayInMilliseconds);
    }
}

From source file:br.ufrn.dimap.pubshare.download.service.DownloaderService.java

/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.// w ww. j  a va  2 s  .c o  m
*/
@Override
protected void onHandleIntent(Intent intent) {
    Log.d(TAG, "onHandleIntent on DownloadService");

    Article selectedArticle = (Article) intent.getSerializableExtra(Article.KEY_INSTANCE);

    if (!AndroidUtils.isExternalStorageAvailable()) {
        // Generate Menssages
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_menu_notifications)
                .setContentTitle(getResources().getString(R.string.external_storage_unavailable))
                .setContentText(getResources().getString(R.string.check_media_availability));
        Notification notification = mBuilder.build();
        // Set the Notification as ongoing
        notification.flags = notification.flags | Notification.FLAG_AUTO_CANCEL;

        NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        nManager.notify(0, notification);
        return;
    }

    DownloadManager dowloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); // since API level 9

    Request request = new Request(Uri.parse(selectedArticle.getRemoteLocation()));
    request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
    request.setTitle(selectedArticle.getTitle());
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
            selectedArticle.generateFileName());
    request.setVisibleInDownloadsUi(true);

    long enqueue = dowloadManager.enqueue(request);

    Log.d(TAG, "Download enqueue..." + enqueue);

    ArticleDownloaded articleDownloaded = new ArticleDownloaded();
    articleDownloaded.setDownloadKey(enqueue);

    DownloadDao downloadDao = new DownloadDao(this);
    downloadDao.insert(articleDownloaded);

    Log.d(TAG, "Insert " + articleDownloaded + " in SqLite: OK");
}

From source file:com.haw3d.jadvalKalemat.versions.GingerbreadUtil.java

@Override
@SuppressWarnings("unused") // Ignore dead code warning
public void downloadFile(URL url, Map<String, String> headers, File destination, boolean notification,
        String title, HttpContext httpContext) throws IOException {
    // The DownloadManager can sometimes be buggy and can cause spurious
    // errors, see
    // http://code.google.com/p/android/issues/detail?id=18462
    // Since puzzle files are very small (a few KB), we don't need to use
    // any of the useful features the DownloadManager provides, such as
    // resuming interrupted downloads and resuming downloads across
    // system reboots.  So for now, just use the ordinary
    // DefaultHttpClient.
    ////from   ww  w  . ja  v  a 2 s  .  co m
    // Also, pre-ICS download managers don't support HTTPS.
    if (!USE_DOWNLOAD_MANAGER || "https".equals(url.getProtocol()) && android.os.Build.VERSION.SDK_INT < 15) {
        super.downloadFile(url, headers, destination, notification, title, httpContext);
        return;
    }

    DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

    Request request = new Request(Uri.parse(url.toString()));
    File tempFile = new File(jadvalKalematApplication.TEMP_DIR, destination.getName());

    request.setDestinationUri(Uri.fromFile(tempFile));

    for (Entry<String, String> entry : headers.entrySet()) {
        request.addRequestHeader(entry.getKey(), entry.getValue());
    }

    request.setMimeType("application/x-crossword");

    setNotificationVisibility(request, notification);

    request.setTitle(title);
    long id = mgr.enqueue(request);
    Long idObj = id;

    String scrubbedUrl = AbstractDownloader.scrubUrl(url);
    LOG.info("Downloading " + scrubbedUrl + " ==> " + tempFile + " (id=" + id + ")");

    // If the request completed really fast, we're done
    DownloadingFile downloadingFile;
    boolean completed = false;
    boolean succeeded = false;
    int status = -1;
    synchronized (completedDownloads) {
        downloadingFile = completedDownloads.remove(idObj);
        if (downloadingFile != null) {
            completed = true;
            succeeded = downloadingFile.succeeded;
            status = downloadingFile.status;
        } else {
            downloadingFile = new DownloadingFile();
            waitingDownloads.put(idObj, downloadingFile);
        }
    }

    // Wait for the request to complete, if it hasn't completed already
    if (!completed) {
        try {
            synchronized (downloadingFile) {
                if (!downloadingFile.completed) {
                    downloadingFile.wait();
                }
                succeeded = downloadingFile.succeeded;
                status = downloadingFile.status;
            }
        } catch (InterruptedException e) {
            LOG.warning("Download interrupted: " + scrubbedUrl);
            throw new IOException("Download interrupted");
        }
    }

    LOG.info("Download " + (succeeded ? "succeeded" : "failed") + ": " + scrubbedUrl);

    if (succeeded) {
        if (!destination.equals(tempFile) && !tempFile.renameTo(destination)) {
            LOG.warning("Failed to rename " + tempFile + " to " + destination);
            throw new IOException("Failed to rename " + tempFile + " to " + destination);
        }
    } else {
        throw new HTTPException(status);
    }
}

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

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    arguments = getArguments();//from w  w  w. j a  v a  2s. 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();
}

From source file:com.adamrosenfield.wordswithcrosses.versions.GingerbreadUtil.java

@Override
@SuppressWarnings("unused") // Ignore dead code warning
public void downloadFile(URL url, Map<String, String> headers, File destination, boolean notification,
        String title, HttpContext httpContext) throws IOException {
    // The DownloadManager can sometimes be buggy and can cause spurious
    // errors, see
    // http://code.google.com/p/android/issues/detail?id=18462
    // Since puzzle files are very small (a few KB), we don't need to use
    // any of the useful features the DownloadManager provides, such as
    // resuming interrupted downloads and resuming downloads across
    // system reboots.  So for now, just use the ordinary
    // DefaultHttpClient.
    ///*from ww w.j a  v a 2 s. c o m*/
    // Also, pre-ICS download managers don't support HTTPS.
    if (!USE_DOWNLOAD_MANAGER || "https".equals(url.getProtocol()) && android.os.Build.VERSION.SDK_INT < 15) {
        super.downloadFile(url, headers, destination, notification, title, httpContext);
        return;
    }

    DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

    Request request = new Request(Uri.parse(url.toString()));
    File tempFile = new File(WordsWithCrossesApplication.TEMP_DIR, destination.getName());

    request.setDestinationUri(Uri.fromFile(tempFile));

    for (Entry<String, String> entry : headers.entrySet()) {
        request.addRequestHeader(entry.getKey(), entry.getValue());
    }

    request.setMimeType("application/x-crossword");

    setNotificationVisibility(request, notification);

    request.setTitle(title);
    long id = mgr.enqueue(request);
    Long idObj = id;

    String scrubbedUrl = AbstractDownloader.scrubUrl(url);
    LOG.info("Downloading " + scrubbedUrl + " ==> " + tempFile + " (id=" + id + ")");

    // If the request completed really fast, we're done
    DownloadingFile downloadingFile;
    boolean completed = false;
    boolean succeeded = false;
    int status = -1;
    synchronized (completedDownloads) {
        downloadingFile = completedDownloads.remove(idObj);
        if (downloadingFile != null) {
            completed = true;
            succeeded = downloadingFile.succeeded;
            status = downloadingFile.status;
        } else {
            downloadingFile = new DownloadingFile();
            waitingDownloads.put(idObj, downloadingFile);
        }
    }

    // Wait for the request to complete, if it hasn't completed already
    if (!completed) {
        try {
            synchronized (downloadingFile) {
                if (!downloadingFile.completed) {
                    downloadingFile.wait();
                }
                succeeded = downloadingFile.succeeded;
                status = downloadingFile.status;
            }
        } catch (InterruptedException e) {
            LOG.warning("Download interrupted: " + scrubbedUrl);
            throw new IOException("Download interrupted");
        }
    }

    LOG.info("Download " + (succeeded ? "succeeded" : "failed") + ": " + scrubbedUrl);

    if (succeeded) {
        if (!destination.equals(tempFile) && !tempFile.renameTo(destination)) {
            LOG.warning("Failed to rename " + tempFile + " to " + destination);
            throw new IOException("Failed to rename " + tempFile + " to " + destination);
        }
    } else {
        throw new HTTPException(status);
    }
}