Example usage for android.app DownloadManager STATUS_SUCCESSFUL

List of usage examples for android.app DownloadManager STATUS_SUCCESSFUL

Introduction

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

Prototype

int STATUS_SUCCESSFUL

To view the source code for android.app DownloadManager STATUS_SUCCESSFUL.

Click Source Link

Document

Value of #COLUMN_STATUS when the download has successfully completed.

Usage

From source file:org.crossconnect.bible.activity.main.ResourceFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    resourceService = ((MainActivity) getActivity()).getResourceService();

    // Prepare the loader.  Either re-connect with an existing one,
    // or start a new one.
    Bundle bundle = new Bundle();
    bundle.putParcelable("BibleText",
            Utils.loadBibleText(getActivity().getSharedPreferences("APP SETTINGS", Context.MODE_PRIVATE)));
    getLoaderManager().initLoader(0, bundle, this);

    // Create an empty adapter we will use to display the loaded data.
    mAdapter = new ResourceListAdapter(getActivity());
    setListAdapter(mAdapter);/*from  ww w  .  j a va 2s  .  c  o  m*/

    dm = ((DownloadManager) getActivity().getSystemService("download"));

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                Query query = new Query();
                query.setFilterById(enqueue);
                Cursor c = dm.query(query);
                if (c.moveToFirst()) {
                    int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {

                        String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    }
                }

                String ns = Context.NOTIFICATION_SERVICE;
                NotificationManager mNotificationManager = (NotificationManager) getActivity()
                        .getSystemService(ns);

                int icon = R.drawable.icon_book_rss;
                CharSequence tickerText = "Resource Download Complete";
                long when = System.currentTimeMillis();

                Notification notification = new Notification(icon, tickerText, when);

                CharSequence contentTitle = "Download Complete";
                CharSequence contentText = "Click to view downloaded resources";

                Intent notificationIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //uncomment when better
                //                    Intent notificationIntent = new Intent(getActivity(), MusicActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(getActivity(), 0, notificationIntent,
                        0);

                notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
                notification.flags |= Notification.FLAG_AUTO_CANCEL;

                int HELLO_ID = 1;

                mNotificationManager.notify(HELLO_ID, notification);
            }
        }
    };

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

}

From source file:com.renard.ocr.help.OCRLanguageActivity.java

private void updateLanguage(final OCRLanguage language, int status) {
    language.mDownloading = false;/*from  w w  w  .  j a  v a2s. com*/
    if (status == DownloadManager.STATUS_SUCCESSFUL) {
        language.mDownloaded = true;
    } else {
        language.mDownloaded = false;
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                String msg = getString(R.string.download_failed);
                msg = String.format(msg, language.mDisplayText);
                Toast.makeText(OCRLanguageActivity.this, msg, Toast.LENGTH_LONG).show();
            }
        });
    }
    mAdapter.notifyDataSetChanged();
}

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 av  a2  s.c  o  m

    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:scal.io.liger.LigerDownloadManager.java

public boolean checkQueue() {

    String fileName = ZipHelper.getExpansionZipFilename(context, mainOrPatch, version);
    String filePath = ZipHelper.getExpansionZipDirectory(context, mainOrPatch, version);

    File checkFile = new File(filePath, fileName + ".tmp");
    boolean foundInQueue = false;

    // need to check if a download has already been queued for this file
    //HashMap<Long, QueueItem> queueMap = QueueManager.loadQueue(context);

    //for (Long queueId : queueMap.keySet()) {

    //Timber.d("QUEUE ITEM IS " + queueMap.get(queueId).getQueueFile() + " LOOKING FOR " + checkFile.getName());

    //if (checkFile.getName().equals(queueMap.get(queueId).getQueueFile())) {

    Long queueId = QueueManager.checkQueue(context, checkFile);

    if (queueId == null) {

        // not found
        foundInQueue = false;/*  ww  w  .jav  a 2  s. c  om*/

    } else if (queueId.equals(QueueManager.DUPLICATE_QUERY)) {

        // not exactly in queue, but someone is already looking for this item, so avoid collision
        foundInQueue = true;

    } else if (queueId < 0) {
        // use negative numbers to flag non-manager downloads

        if (checkFileProgress()) {

            Timber.d("QUEUE ITEM FOUND FOR " + checkFile.getName() + " AND DOWNLOAD PROGRESS OBSERVED, LEAVING "
                    + queueId.toString() + " IN QUEUE ");
            foundInQueue = true;

        } else {

            Timber.d("QUEUE ITEM FOUND FOR " + checkFile.getName()
                    + " BUT NO DOWNLOAD PROGRESS OBSERVED, REMOVING " + queueId.toString() + " FROM QUEUE ");
            QueueManager.removeFromQueue(context, Long.valueOf(queueId));

        }

    } else {
        // use download manager ids to flag manager downloads

        // need to init download manager to check queue
        initDownloadManager();

        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(queueId.longValue());
        Cursor c = dManager.query(query);
        try {
            if (c.moveToFirst()) {

                int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                if (DownloadManager.STATUS_FAILED == c.getInt(columnIndex)) {

                    Timber.d("QUEUE ITEM FOUND FOR " + checkFile.getName()
                            + " BUT DOWNLOAD STATUS IS FAILED, REMOVING " + queueId.toString()
                            + " FROM QUEUE ");
                    QueueManager.removeFromQueue(context, Long.valueOf(queueId));

                } else if (DownloadManager.STATUS_PAUSED == c.getInt(columnIndex)) {

                    Timber.d("QUEUE ITEM FOUND FOR " + checkFile.getName()
                            + " AND DOWNLOAD STATUS IS PAUSED, LEAVING " + queueId.toString() + " IN QUEUE ");
                    foundInQueue = true;

                } else if (DownloadManager.STATUS_PENDING == c.getInt(columnIndex)) {

                    Timber.d("QUEUE ITEM FOUND FOR " + checkFile.getName()
                            + " AND DOWNLOAD STATUS IS PENDING, LEAVING " + queueId.toString() + " IN QUEUE ");
                    foundInQueue = true;

                } else if (DownloadManager.STATUS_RUNNING == c.getInt(columnIndex)) {

                    Timber.d("QUEUE ITEM FOUND FOR " + checkFile.getName()
                            + " AND DOWNLOAD STATUS IS RUNNING, LEAVING " + queueId.toString() + " IN QUEUE ");
                    foundInQueue = true;

                } else if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {

                    Timber.d("QUEUE ITEM FOUND FOR " + checkFile.getName()
                            + " BUT DOWNLOAD STATUS IS SUCCESSFUL, REMOVING " + queueId.toString()
                            + " FROM QUEUE ");
                    QueueManager.removeFromQueue(context, Long.valueOf(queueId));

                } else {

                    Timber.d("QUEUE ITEM FOUND FOR " + checkFile.getName()
                            + " BUT DOWNLOAD STATUS IS UNKNOWN, REMOVING " + queueId.toString()
                            + " FROM QUEUE ");
                    QueueManager.removeFromQueue(context, Long.valueOf(queueId));

                }
            } else {

                Timber.d("QUEUE ITEM FOUND FOR " + checkFile.getName()
                        + " BUT NOTHING FOUND IN DOWNLOAD MANAGER, REMOVING " + queueId.toString()
                        + " FROM QUEUE ");
                QueueManager.removeFromQueue(context, Long.valueOf(queueId));

            }
        } finally {
            if (c != null) {
                c.close();
            }
        }

        // cleanup
        c.close();
    }
    //}

    // skipping timeout check for now, timeout duration undecided

    /*
    if (foundInQueue) {
        Date currentTime = new Date();
        long queuedTime = queueMap.get(queueId).getQueueTime();
        if ((currentTime.getTime() - queueMap.get(queueId).getQueueTime()) > QueueManager.queueTimeout) {
            
            Timber.d("TIMEOUT EXCEEDED, REMOVING " + queueId.toString() + " FROM DOWNLOAD MANAGER.");
            int numberRemoved = manager.remove(queueId);
            
            if (numberRemoved == 1) {
                Timber.d("REMOVED FROM DOWNLOAD MANAGER, RE-QUEUEING: " + queueId.toString() + " -> " + uriFile.toString());
                QueueManager.removeFromQueue(context, Long.valueOf(queueId));
                foundInQueue = false;
            } else {
                Timber.d("FAILED TO REMOVE FROM DOWNLOAD MANAGER, NOT QUEUEING: " + queueId.toString() + " -> " + uriFile.toString());
            }
        }
    }
    */
    //}

    return foundInQueue;
}

From source file:fr.kwiatkowski.apktrack.ui.AppViewHolder.java

/**
 * Sets the right status icon when the app is currently downloading or has downloaded an APK.
 * @param info The object containing the information about the download.
 * @param ctx The context of the application.
 * @return Whether an icon was set.// w  w  w  . j a  va  2s.  c  o m
 */
private boolean _set_action_icon_download(final DownloadInfo info, final Context ctx) {
    switch (info.get_status()) {
    case DownloadManager.STATUS_SUCCESSFUL: // APK was downloaded. Install on click.
        File apk = new File(info.get_local_path());
        if (apk.exists()) {
            _action_icon.setImageDrawable(ContextCompat.getDrawable(ctx, R.drawable.install));
            _action_icon.setVisibility(View.VISIBLE);
            _action_icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setDataAndType(Uri.parse(info.get_local_uri()),
                            "application/vnd.android.package-archive");
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if (i.resolveActivity(ctx.getPackageManager()) != null) {
                        ctx.startActivity(i);
                    } else {
                        Log.v(MainActivity.TAG, "Could not find anyone to receive ACTION_VIEW for "
                                + "the downloaded APK. (" + info.get_local_uri() + ")");
                    }
                }
            });
            return true;
        } else { // For some reason the APK is not present anymore. Remove the download information.
            return false;
        }
    case DownloadManager.STATUS_PENDING:
    case DownloadManager.STATUS_RUNNING:
        _action_icon.setImageDrawable(ContextCompat.getDrawable(ctx, android.R.drawable.stat_sys_download));
        ((Animatable) _action_icon.getDrawable()).start();
        _action_icon.setVisibility(View.VISIBLE);
        return true;
    default:
        return false;
    }
}

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

    return downloadId;
}

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);/*  ww w. j  a v a 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: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  w w  w . j  a v a  2 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.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;/*w  w w .  jav  a 2  s . c  om*/
    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:com.concentricsky.android.khanacademy.util.OfflineVideoManager.java

/**
 * Get whether a {@link Video} has begun downloading.
 * /*from w  ww  . j a v a  2 s .  c om*/
 * @param video The {@link Video} to check.
 * @return True if the download has begun, false otherwise.  This means true if a download is complete, and false if the download is enqueued but not yet begun.
 */
public boolean hasDownloadBegun(Video video) {
    Log.d(LOG_TAG, "hasDownloadBegun");
    DownloadManager.Query q = new DownloadManager.Query();
    long dlm_id = video.getDlm_id();
    if (dlm_id <= 0) {
        return false;
    }
    q.setFilterById(dlm_id);
    q.setFilterByStatus(
            DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_SUCCESSFUL);
    Cursor c = getDownloadManager().query(q);
    boolean result = c.getCount() > 0;
    c.close();
    return result;
}