Example usage for android.app DownloadManager COLUMN_STATUS

List of usage examples for android.app DownloadManager COLUMN_STATUS

Introduction

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

Prototype

String COLUMN_STATUS

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

Click Source Link

Document

Current status of the download, as one of the STATUS_* constants.

Usage

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

private void StartProgressTracking(final Download curDownload) {
    // already started
    if (curDownload.getTimerProgressUpdate() != null) {
        return;//from w w  w  .  ja v  a2 s.  c  om
    }
    final DownloadManager mgr = (DownloadManager) this.cordova.getActivity()
            .getSystemService(Context.DOWNLOAD_SERVICE);

    curDownload.setTimerProgressUpdate(new Timer());
    curDownload.getTimerProgressUpdate().schedule(new TimerTask() {
        @Override
        public void run() {
            DownloadManager.Query q = new DownloadManager.Query();
            q.setFilterById(curDownload.getDownloadId());
            Cursor cursor = mgr.query(q);
            if (cursor.moveToFirst()) {
                long bytesDownloaded = cursor
                        .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                long bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                if (bytesTotal != -1) {
                    Log.d("BackgroundDownload", "DOWNLOAD STARTED for " + curDownload.getDownloadId());
                    try {
                        JSONObject jsonProgress = new JSONObject();
                        jsonProgress.put("bytesReceived", bytesDownloaded);
                        jsonProgress.put("totalBytesToReceive", bytesTotal);
                        JSONObject obj = new JSONObject();
                        obj.put("progress", jsonProgress);
                        PluginResult progressUpdate = new PluginResult(PluginResult.Status.OK, obj);
                        progressUpdate.setKeepCallback(true);
                        curDownload.getCallbackContextDownloadStart().sendPluginResult(progressUpdate);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    long status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    long reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
                    Log.d("BackgroundDownload", "download not started for " + curDownload.getTempFilePath()
                            + " (status " + status + ") (reason " + reason + ")");
                }
            }
            cursor.close();
        }
    }, DOWNLOAD_PROGRESS_UPDATE_TIMEOUT, DOWNLOAD_PROGRESS_UPDATE_TIMEOUT);
}

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  w  ww.  j ava2  s  .  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: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;/*from w w w.  ja  va2s  .  com*/

    } 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: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  .ja  va 2  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: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  om
    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 av  a2s  .c om*/

    // 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;//from w w w. jav  a2 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:net.momodalo.app.vimtouch.VimTouch.java

private void downloadFullRuntime() {

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override/*w  w w .  ja v  a2s. co m*/
        public void onReceive(Context context, Intent intent) {
            context.unregisterReceiver(this);
            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(mEnqueue);
                Cursor c = mDM.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));
                        Intent newintent = new Intent(getApplicationContext(), InstallProgress.class);
                        newintent.setData(Uri.parse(uriString));
                        startActivity(newintent);
                    }
                }
            }
        }
    };

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

    mDM = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    Request request = new Request(Uri.parse("https://github.com/downloads/momodalo/vimtouch/vim.vrz"));
    mEnqueue = mDM.enqueue(request);
}

From source file:com.ywesee.amiko.MainActivity.java

/**
 * Overrides onCreate method//from w  w w  .  j a v a 2 s  .co  m
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {
        AsyncLoadDBTask loadDBTask = new AsyncLoadDBTask(this);
        loadDBTask.execute();
    } catch (Exception e) {
        Log.e(TAG, "AsyncLoadDBTask exception caught!");
    }

    // Load CSS from asset folder
    if (Utilities.isTablet(this))
        mCSS_str = Utilities.loadFromAssetsFolder(this, "amiko_stylesheet.css", "UTF-8");
    else
        mCSS_str = Utilities.loadFromAssetsFolder(this, "amiko_stylesheet_phone.css", "UTF-8");

    // Flag for enabling the Action Bar on top
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    // Enable overlay mode for action bar (no good, search results disappear behind it...)
    // getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);

    // Create action bar
    int mode = ActionBar.NAVIGATION_MODE_TABS;
    if (savedInstanceState != null) {
        mode = savedInstanceState.getInt("mode", ActionBar.NAVIGATION_MODE_TABS);
    }

    // Sets tab bar items
    addTabNavigation();

    // Reset action name
    Log.d(TAG, "OnCreate -> " + mActionName);
    mActionName = getString(R.string.tab_name_1);

    /*
    'getFilesDir' returns a java.io.File object representing the root directory
    of the INTERNAL storage four the application from the current context.
    */
    mFavoriteData = new DataStore(this.getFilesDir().toString());
    // Load hashset containing registration numbers from persistent data store
    mFavoriteMedsSet = new HashSet<String>();
    mFavoriteMedsSet = mFavoriteData.load();

    // Initialize preferences
    SharedPreferences settings = getSharedPreferences(AMIKO_PREFS_FILE, 0);

    long timeMillisSince1970 = 0;
    if (Constants.appLanguage().equals("de")) {
        timeMillisSince1970 = settings.getLong(PREF_DB_UPDATE_DATE_DE, 0);
        if (timeMillisSince1970 == 0) {
            SharedPreferences.Editor editor = settings.edit();
            editor.putLong(PREF_DB_UPDATE_DATE_DE, System.currentTimeMillis());
            // Commit the edits!
            editor.commit();
        }
    } else if (Constants.appLanguage().equals("fr")) {
        timeMillisSince1970 = settings.getLong(PREF_DB_UPDATE_DATE_FR, 0);
        if (timeMillisSince1970 == 0) {
            SharedPreferences.Editor editor = settings.edit();
            editor.putLong(PREF_DB_UPDATE_DATE_DE, System.currentTimeMillis());
            // Commit the edits!
            editor.commit();
        }
    }

    checkTimeSinceLastUpdate();

    // Init toast object
    mToastObject = new CustomToast(this);

    // Initialize download manager
    mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

    mBroadcastReceiver = 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);
                if (downloadId == mDatabaseId || downloadId == mReportId || downloadId == mInteractionsId)
                    mDownloadedFileCount++;
                // Before proceeding make sure all files have been downloaded before proceeding
                if (mDownloadedFileCount == 3) {
                    Query query = new Query();
                    query.setFilterById(downloadId);
                    Cursor c = mDownloadManager.query(query);
                    if (c.moveToFirst()) {
                        int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                        // Check if download was successful
                        if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                            try {
                                // Update database
                                AsyncUpdateDBTask updateDBTask = new AsyncUpdateDBTask(MainActivity.this);
                                updateDBTask.execute();
                            } catch (Exception e) {
                                Log.e(TAG, "AsyncUpdateDBTask: exception caught!");
                            }
                            // Toast
                            mToastObject.show("Databases downloaded successfully. Installing...",
                                    Toast.LENGTH_SHORT);
                            if (mProgressBar.isShowing())
                                mProgressBar.dismiss();
                            mUpdateInProgress = false;
                            // Store time stamp
                            SharedPreferences settings = getSharedPreferences(AMIKO_PREFS_FILE, 0);
                            SharedPreferences.Editor editor = settings.edit();
                            editor.putLong(PREF_DB_UPDATE_DATE_DE, System.currentTimeMillis());
                            // Commit the edits!
                            editor.commit();
                        } else {
                            mToastObject.show("Error while downloading database...", Toast.LENGTH_SHORT);
                        }
                    }
                    c.close();
                }
            }
        }
    };
    registerReceiver(mBroadcastReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

From source file:org.wso2.iot.agent.api.ApplicationManager.java

/**
 * Initiate downloading via DownloadManager API.
 *
 * @param url     - File URL./*w  ww. ja  v a  2 s  .  c  om*/
 * @param appName - Name of the application to be downloaded.
 */
private void downloadViaDownloadManager(String url, String appName) {
    final DownloadManager downloadManager = (DownloadManager) context
            .getSystemService(Context.DOWNLOAD_SERVICE);
    Uri downloadUri = Uri.parse(url);
    DownloadManager.Request request = new DownloadManager.Request(downloadUri);

    // Restrict the types of networks over which this download may
    // proceed.
    request.setAllowedNetworkTypes(
            DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
    // Set whether this download may proceed over a roaming connection.
    request.setAllowedOverRoaming(true);
    // Set the title of this download, to be displayed in notifications
    // (if enabled).
    request.setTitle(resources.getString(R.string.downloader_message_title));
    request.setVisibleInDownloadsUi(false);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
    // Set the local destination for the downloaded file to a path
    // within the application's external files directory
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, appName);
    // Enqueue a new download and same the referenceId
    downloadReference = downloadManager.enqueue(request);
    new Thread(new Runnable() {
        @Override
        public void run() {
            boolean downloading = true;
            int progress = 0;
            while (downloading) {
                downloadOngoing = true;
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadReference);
                Cursor cursor = downloadManager.query(query);
                cursor.moveToFirst();
                int bytesDownloaded = cursor
                        .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                int bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                if (cursor.getInt(cursor
                        .getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                    downloading = false;
                }
                if (cursor.getInt(cursor
                        .getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_FAILED) {
                    downloading = false;
                    Preference.putString(context, context.getResources().getString(R.string.app_install_status),
                            context.getResources().getString(R.string.app_status_value_download_failed));
                    Preference.putString(context,
                            context.getResources().getString(R.string.app_install_failed_message),
                            "App download failed due to a connection issue.");
                }
                int downloadProgress = 0;
                if (bytesTotal > 0) {
                    downloadProgress = (int) ((bytesDownloaded * 100l) / bytesTotal);
                }
                if (downloadProgress != DOWNLOAD_PERCENTAGE_TOTAL) {
                    progress += DOWNLOADER_INCREMENT;
                } else {
                    progress = DOWNLOAD_PERCENTAGE_TOTAL;
                    Preference.putString(context, context.getResources().getString(R.string.app_install_status),
                            context.getResources().getString(R.string.app_status_value_download_completed));
                }

                Preference.putString(context, resources.getString(R.string.app_download_progress),
                        String.valueOf(progress));
                cursor.close();
            }
            downloadOngoing = false;
        }
    }).start();
}