Example usage for android.app DownloadManager COLUMN_BYTES_DOWNLOADED_SO_FAR

List of usage examples for android.app DownloadManager COLUMN_BYTES_DOWNLOADED_SO_FAR

Introduction

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

Prototype

String COLUMN_BYTES_DOWNLOADED_SO_FAR

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

Click Source Link

Document

Number of bytes download so far.

Usage

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 w  w .j av  a  2s  . c om
    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:com.commonsware.android.downmgr.DownloadFragment.java

private void queryStatus(View v) {
    Cursor c = mgr.query(new DownloadManager.Query().setFilterById(lastDownload));

    if (c == null) {
        Toast.makeText(getActivity(), R.string.download_not_found, Toast.LENGTH_LONG).show();
    } else {//  w  w  w.  ja  v  a  2 s  . c  om
        c.moveToFirst();

        Log.d(getClass().getName(), "COLUMN_ID: " + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)));
        Log.d(getClass().getName(), "COLUMN_BYTES_DOWNLOADED_SO_FAR: "
                + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)));
        Log.d(getClass().getName(), "COLUMN_LAST_MODIFIED_TIMESTAMP: "
                + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)));
        Log.d(getClass().getName(),
                "COLUMN_LOCAL_URI: " + c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
        Log.d(getClass().getName(),
                "COLUMN_STATUS: " + c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)));
        Log.d(getClass().getName(),
                "COLUMN_REASON: " + c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON)));

        Toast.makeText(getActivity(), statusMessage(c), Toast.LENGTH_LONG).show();

        c.close();
    }
}

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

@Override
protected String doInBackground(final String... strings) {
    try {/*  ww  w  . j a v a  2  s .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:com.cypher.cota.helpers.DownloadHelper.java

private static long[] getDownloadProgress(long id) {
    DownloadManager.Query q = new DownloadManager.Query();
    q.setFilterById(id);/*  ww  w. jav a  2 s  .  c om*/

    Cursor cursor = sDownloadManager.query(q);
    int status;

    if (cursor == null || !cursor.moveToFirst()) {
        status = DownloadManager.STATUS_FAILED;
    } else {
        status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
    }

    long error = -1;
    long totalBytes = -1;
    long downloadedBytes = -1;

    switch (status) {
    case DownloadManager.STATUS_PAUSED:
    case DownloadManager.STATUS_RUNNING:
        downloadedBytes = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
        totalBytes = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
        break;
    case DownloadManager.STATUS_FAILED:
        sDownloadingRom = false;
        error = getDownloadError(cursor);
        break;
    }

    if (cursor != null) {
        cursor.close();
    }

    return new long[] { status, totalBytes, downloadedBytes, error };
}

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

private void StartProgressTracking(final Download curDownload) {
    // already started
    if (curDownload.getTimerProgressUpdate() != null) {
        return;//  w  w  w  . j  a  v  a 2s .c o  m
    }
    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.wso2.iot.agent.api.ApplicationManager.java

/**
 * Initiate downloading via DownloadManager API.
 *
 * @param url     - File URL./*from ww  w.ja va 2  s  .c o m*/
 * @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();
}

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

/**
 * Downloads and updates the SQLite database and the error report file
 *///from w  ww . ja v a  2  s .  c om
public void downloadUpdates() {
    // Signal that update is in progress
    mUpdateInProgress = true;
    mDownloadedFileCount = 0;

    // First check network connection
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    // Fetch data...
    if (networkInfo != null && networkInfo.isConnected()) {
        // File URIs
        Uri databaseUri = Uri.parse("http://pillbox.oddb.org/" + Constants.appZippedDatabase());
        Uri reportUri = Uri.parse("http://pillbox.oddb.org/" + Constants.appReportFile());
        Uri interactionsUri = Uri.parse("http://pillbox.oddb.org/" + Constants.appZippedInteractionsFile());
        // NOTE: the default download destination is a shared volume where the system might delete your file if
        // it needs to reclaim space for system use
        DownloadManager.Request requestDatabase = new DownloadManager.Request(databaseUri);
        DownloadManager.Request requestReport = new DownloadManager.Request(reportUri);
        DownloadManager.Request requestInteractions = new DownloadManager.Request(interactionsUri);
        // Allow download only over WIFI and Mobile network
        requestDatabase.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
        requestReport.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
        requestInteractions.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
        // Download visible and shows in notifications while in progress and after completion
        requestDatabase.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        requestReport.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        requestInteractions
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // Set the title of this download, to be displayed in notifications (if enabled).
        requestDatabase.setTitle("AmiKo SQLite database update");
        requestReport.setTitle("AmiKo report update");
        requestInteractions.setTitle("AmiKo drug interactions update");
        // Set a description of this download, to be displayed in notifications (if enabled)
        requestDatabase.setDescription("Updating the AmiKo database.");
        requestReport.setDescription("Updating the AmiKo error report.");
        requestInteractions.setDescription("Updating the AmiKo drug interactions.");
        // Set local destination to standard directory (place where files downloaded by the user are placed)
        /*
        String main_expansion_file_path = Utilities.expansionFileDir(getPackageName());
        requestDatabase.setDestinationInExternalPublicDir(main_expansion_file_path, Constants.appZippedDatabase());
        */
        requestDatabase.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                Constants.appZippedDatabase());
        requestReport.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                Constants.appReportFile());
        requestInteractions.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                Constants.appZippedInteractionsFile());
        // Check if file exist on non persistent store. If yes, delete it.
        if (Utilities.isExternalStorageReadable() && Utilities.isExternalStorageWritable()) {
            Utilities.deleteFile(Constants.appZippedDatabase(),
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
            Utilities.deleteFile(Constants.appReportFile(),
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
            Utilities.deleteFile(Constants.appZippedInteractionsFile(),
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
        }
        // The downloadId is unique across the system. It is used to make future calls related to this download.
        mDatabaseId = mDownloadManager.enqueue(requestDatabase);
        mReportId = mDownloadManager.enqueue(requestReport);
        mInteractionsId = mDownloadManager.enqueue(requestInteractions);

        mProgressBar = new ProgressDialog(MainActivity.this);
        mProgressBar.setMessage("Downloading SQLite database...");
        mProgressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressBar.setProgress(0);
        mProgressBar.setMax(100);
        mProgressBar.setCancelable(false);
        mProgressBar.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean downloading = true;
                while (downloading) {
                    DownloadManager.Query q = new DownloadManager.Query();
                    q.setFilterById(mDatabaseId);
                    Cursor cursor = mDownloadManager.query(q);
                    cursor.moveToFirst();
                    int bytes_downloaded = cursor
                            .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    int bytes_total = cursor
                            .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                    if (cursor.getInt(cursor.getColumnIndex(
                            DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                        downloading = false;
                        if (mProgressBar.isShowing())
                            mProgressBar.dismiss();
                    }
                    final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressBar.setProgress((int) dl_progress);
                        }
                    });
                    cursor.close();
                }
            }
        }).start();
    } else {
        // Display error report
    }
}