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:net.momodalo.app.vimtouch.VimTouch.java

private void downloadFullRuntime() {

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override//from   w  w w  .  j a v a 2s. 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// w  w  w.  j  a v a 2s .c  o 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.anoopam.main.anoopamaudio.AudioListActivity.java

public void updateList() {

    try {//from  www.  j  a va  2  s  . co m
        if (audioDownloadListeners != null && audioDownloadListeners.size() > 0) {

            try {
                for (Map.Entry<Long, AudioDownloadListener> entry : audioDownloadListeners.entrySet()) {

                    try {
                        final long downloadID = entry.getKey();
                        final AudioDownloadListener value = entry.getValue();

                        if (downloadID != 0 && value != null
                                && (!completeDownloadIds.containsKey(downloadID))) {
                            final int[] bytesAndStatus = downloadManagerPro.getBytesAndStatus(downloadID);

                            if (isDownloading(bytesAndStatus[2])) {
                                if (bytesAndStatus[1] < 0) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            value.onProgressUpdate(downloadID, 0);
                                        }
                                    });

                                } else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            value.onProgressUpdate(downloadID,
                                                    getNotiPercent(bytesAndStatus[0], bytesAndStatus[1]));
                                        }
                                    });

                                }
                            } else {
                                if (bytesAndStatus[2] == DownloadManager.STATUS_SUCCESSFUL) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            value.onDownloadComplete();
                                        }
                                    });

                                } else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            value.onFail();
                                        }
                                    });

                                }
                            }

                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }

                }
            } catch (Throwable e) {
                e.printStackTrace();
            }

        }
    } catch (Throwable e) {
        e.printStackTrace();
    }

}

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

/**
 * Initiate downloading via DownloadManager API.
 *
 * @param url     - File URL.//from  w ww .j  av a2  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.mobicage.rogerthat.plugins.messaging.BrandingMgr.java

@SuppressLint("InlinedApi")
private File getDownloadedFile(final Long downloadId) throws DownloadNotCompletedException {
    final DownloadManager dwnlMgr = getDownloadManager();
    final Cursor cursor = dwnlMgr.query(new Query().setFilterById(downloadId));
    try {/*ww  w .j a v a2 s  . c o m*/
        if (!cursor.moveToFirst()) {
            L.w("Download with id " + downloadId + " not found!");
            return null;
        }

        final int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
        switch (status) {
        case DownloadManager.STATUS_SUCCESSFUL:
            final String filePath = cursor
                    .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
            return new File(filePath);
        case DownloadManager.STATUS_FAILED:
            return null;
        default: // Not completed
            L.w("Unexpected DownloadManager.STATUS: " + status);
            throw new BrandingMgr.DownloadNotCompletedException();
        }
    } finally {
        cursor.close();
    }
}

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

/**
 * Downloads and updates the SQLite database and the error report file
 */// ww  w . ja v  a 2  s  .c  o m
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
    }
}