Example usage for android.app DownloadManager remove

List of usage examples for android.app DownloadManager remove

Introduction

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

Prototype

public int remove(long... ids) 

Source Link

Document

Cancel downloads and remove them from the download manager.

Usage

From source file:com.hughes.android.dictionary.DictionaryManagerActivity.java

private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
    String destFile;/*from  ww  w.j a  va  2  s.  c  o m*/
    try {
        destFile = new File(new URL(downloadUrl).getPath()).getName();
    } catch (MalformedURLException e) {
        throw new RuntimeException("Invalid download URL!", e);
    }
    DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    final DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterByStatus(
            DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
    final Cursor cursor = downloadManager.query(query);

    // Due to a bug, cursor is null instead of empty when
    // the download manager is disabled.
    if (cursor == null) {
        new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
                .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
                .setNeutralButton("Close", null).show();
        return;
    }

    while (cursor.moveToNext()) {
        if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
            break;
        if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE))))
            break;
    }
    if (!cursor.isAfterLast()) {
        downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
        downloadButton.setText(getString(R.string.downloadButton, bytes / 1024.0 / 1024.0));
        cursor.close();
        return;
    }
    cursor.close();
    Request request = new Request(Uri.parse(downloadUrl));

    Log.d(LOG, "Downloading to: " + destFile);
    request.setTitle(destFile);

    File destFilePath = new File(application.getDictDir(), destFile);
    destFilePath.delete();
    try {
        request.setDestinationUri(Uri.fromFile(destFilePath));
    } catch (Exception e) {
    }

    try {
        downloadManager.enqueue(request);
    } catch (SecurityException e) {
        request = new Request(Uri.parse(downloadUrl));
        request.setTitle(destFile);
        downloadManager.enqueue(request);
    }
    Log.w(LOG, "Download started: " + destFile);
    downloadButton.setText("X");
}

From source file:com.concentricsky.android.khanacademy.util.OfflineVideoManager.java

/**
 * Cancel ongoing and enqueued video downloads.
 *///from w  ww .java  2 s . c o  m
public void cancelAllVideoDownloads() {
    final DownloadManager dlm = getDownloadManager();
    final DownloadManager.Query q = new DownloadManager.Query();
    q.setFilterByStatus(DownloadManager.STATUS_FAILED | DownloadManager.STATUS_PAUSED
            | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);

    // Cancel all tasks - we don't want any more downloads enqueued, and we are
    // beginning a cancel task so we don't need any previous one.
    queueExecutor.shutdownNow();
    queueExecutor = Executors.newSingleThreadExecutor();

    new AsyncTask<Void, Void, Integer>() {
        @Override
        protected void onPreExecute() {
            doToast("Stopping downloads...");
        }

        @Override
        protected Integer doInBackground(Void... arg) {
            int result = 0;
            if (isCancelled())
                return result;

            Cursor c = dlm.query(q);
            Long[] removed = new Long[c.getCount()];
            int i = 0;
            while (c.moveToNext()) {
                if (isCancelled())
                    break;

                long id = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID));
                removed[i++] = id;
                dlm.remove(id);
                result++;
            }
            c.close();

            UpdateBuilder<Video, String> u = videoDao.updateBuilder();
            try {
                u.where().in("dlm_id", (Object[]) removed);
                u.updateColumnValue("download_status", Video.DL_STATUS_NOT_STARTED);
                u.update();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            return result;
        }

        @Override
        protected void onPostExecute(Integer result) {
            if (result > 0) {
                doToast(result + " downloads cancelled.");
            } else {
                doToast("No downloads in queue.");
            }
            doOfflineVideoSetChanged();
        }

        @Override
        protected void onCancelled(Integer result) {
            if (result > 0) {
                doToast(result + " downloads cancelled.");
            }
            doOfflineVideoSetChanged();
        }
    }.executeOnExecutor(queueExecutor);
}

From source file:org.chromium.chrome.browser.download.DownloadManagerService.java

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (!DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action))
        return;/*from  ww w  .jav a 2  s .c  o m*/
    final DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);

    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
    if (downloadId == -1)
        return;
    boolean isPendingOMADownload = mOMADownloadHandler.isPendingOMADownload(downloadId);
    boolean isInOMASharedPrefs = isDownloadIdInOMASharedPrefs(downloadId);
    if (isPendingOMADownload || isInOMASharedPrefs) {
        clearPendingOMADownload(downloadId, null);
        mPendingAutoOpenDownloads.remove(downloadId);
    } else if (mPendingAutoOpenDownloads.get(downloadId) != null) {
        Cursor c = manager.query(new DownloadManager.Query().setFilterById(downloadId));
        int statusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
        while (c.moveToNext()) {
            int status = c.getInt(statusIndex);
            DownloadInfo info = mPendingAutoOpenDownloads.get(downloadId);
            switch (status) {
            case DownloadManager.STATUS_SUCCESSFUL:
                try {
                    mPendingAutoOpenDownloads.remove(downloadId);
                    if (OMADownloadHandler.OMA_DOWNLOAD_DESCRIPTOR_MIME.equalsIgnoreCase(info.getMimeType())) {
                        mOMADownloadHandler.handleOMADownload(info, downloadId);
                        manager.remove(downloadId);
                        break;
                    }
                    Uri uri = manager.getUriForDownloadedFile(downloadId);
                    Intent launchIntent = new Intent(Intent.ACTION_VIEW);

                    launchIntent.setDataAndType(uri, manager.getMimeTypeForDownloadedFile(downloadId));
                    launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    mContext.startActivity(launchIntent);
                } catch (ActivityNotFoundException e) {
                    Log.w(TAG, "Activity not found.");
                }
                break;
            case DownloadManager.STATUS_FAILED:
                mPendingAutoOpenDownloads.remove(downloadId);
                break;
            default:
                break;
            }
        }
    }

    if (mPendingAutoOpenDownloads.size() == 0) {
        mContext.unregisterReceiver(this);
    }
}

From source file:uk.org.ngo.squeezer.service.SqueezeService.java

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void downloadSong(@NonNull Uri url, String title, @NonNull Uri serverUrl) {
    if (url.equals(Uri.EMPTY)) {
        return;// ww  w. j  a  va 2  s . c o  m
    }

    // If running on Gingerbread or greater use the Download Manager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadDatabase downloadDatabase = new DownloadDatabase(this);
        String localPath = getLocalFile(serverUrl);
        String tempFile = UUID.randomUUID().toString();
        String credentials = mUsername + ":" + mPassword;
        String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
        DownloadManager.Request request = new DownloadManager.Request(url).setTitle(title)
                .setDestinationInExternalFilesDir(this, Environment.DIRECTORY_MUSIC, tempFile)
                .setVisibleInDownloadsUi(false)
                .addRequestHeader("Authorization", "Basic " + base64EncodedCredentials);
        long downloadId = downloadManager.enqueue(request);

        Crashlytics.log("Registering new download");
        Crashlytics.log("downloadId: " + downloadId);
        Crashlytics.log("tempFile: " + tempFile);
        Crashlytics.log("localPath: " + localPath);

        if (!downloadDatabase.registerDownload(downloadId, tempFile, localPath)) {
            Crashlytics.log(Log.WARN, TAG, "Could not register download entry for: " + downloadId);
            downloadManager.remove(downloadId);
        }
    }
}

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

@Override
public void onReceive(final Context context, final Intent intent) {
    final DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    final Database db = Database.getInstance(context);
    final Cursor downloads = db.getDownloads();

    LogHandler.log(Log.WARN, "receive starting");

    while (downloads.moveToNext()) {
        final long id = downloads.getLong(downloads.getColumnIndex(Database.COLUMN_ID));
        final String name = downloads.getString(downloads.getColumnIndex(Database.COLUMN_SUBSCRIPTION));
        final String mime = downloads.getString(downloads.getColumnIndex(Database.COLUMN_TYPE));
        final Cursor download = manager.query(new DownloadManager.Query().setFilterById(id));

        // download exists
        if (!download.moveToFirst())
            continue;

        // download finished
        if (download.getInt(
                download.getColumnIndex(DownloadManager.COLUMN_STATUS)) != DownloadManager.STATUS_SUCCESSFUL)
            continue;

        // import file in background
        new Thread(new Runnable() {
            @Override//from   w w w .j  a  v a2s.co  m
            public void run() {
                try {
                    LogHandler.log(Log.WARN, "import starting of " + name);

                    final FileInputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(
                            manager.openDownloadedFile(id));
                    final String mimeServer = manager.getMimeTypeForDownloadedFile(id);

                    LogHandler.log(Log.INFO, "id: " + String.valueOf(id));
                    LogHandler.log(Log.INFO, "manager: " + manager.toString());
                    LogHandler.log(Log.INFO, "stream: " + stream.toString());
                    LogHandler.log(Log.INFO, "mime: " + mime);
                    LogHandler.log(Log.INFO, "mimeServer: " + mimeServer);

                    switch (mime != null ? mime : (mimeServer != null ? mimeServer : "")) {

                    // register feedback
                    case "application/json":
                        final byte[] buf = new byte[256];
                        final int len = stream.read(buf);
                        LogHandler.log(Log.WARN, "register feedback: " + new String(buf, 0, len));
                        break;

                    // csv data
                    case "text/plain":
                        db.importCSV(name, stream);
                        break;

                    // xml data
                    case "application/xml":
                    case "text/xml":
                        db.importXML(name, stream);
                        break;

                    // zipped data
                    case "application/zip":
                        db.importZIP(name, stream);
                        break;

                    // do nothing
                    default:
                        LogHandler.log(new IntentFilter.MalformedMimeTypeException());
                        break;
                    }

                    stream.close();
                    LogHandler.log(Log.WARN, "import finished (" + name + ")");
                }

                // file error
                catch (FileNotFoundException e) {
                    LogHandler.logAndShow(e, context, R.string.message_download_open);
                }

                // stream error
                catch (IOException e) {
                    LogHandler.logAndShow(e, context, R.string.message_download_read);
                }

                // xml error
                catch (XmlPullParserException e) {
                    LogHandler.logAndShow(e, context, R.string.message_download_xml);
                }

                // clean
                finally {
                    manager.remove(id);
                    db.removeDownload(id);
                    LogHandler.log(Log.WARN, "clean finished");
                }
            }
        }).start();
    }

    downloads.close();
    LogHandler.log(Log.WARN, "receiving done");
}