Example usage for android.app DownloadManager ACTION_DOWNLOAD_COMPLETE

List of usage examples for android.app DownloadManager ACTION_DOWNLOAD_COMPLETE

Introduction

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

Prototype

String ACTION_DOWNLOAD_COMPLETE

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

Click Source Link

Document

Broadcast intent action sent by the download manager when a download completes.

Usage

From source file:de.baumann.browser.Browser_left.java

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    final WebView.HitTestResult result = mWebView.getHitTestResult();
    final String url = result.getExtra();

    if (result.getType() == WebView.HitTestResult.IMAGE_TYPE) {

        final CharSequence[] options = { getString(R.string.context_saveImage),
                getString(R.string.context_shareImage), getString(R.string.context_readLater),
                getString(R.string.context_right) };
        new AlertDialog.Builder(Browser_left.this)
                .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }// w w w . j a va 2 s.com
                }).setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals(getString(R.string.context_saveImage))) {
                            if (url != null) {
                                try {
                                    Uri source = Uri.parse(url);
                                    DownloadManager.Request request = new DownloadManager.Request(source);
                                    request.addRequestHeader("Cookie",
                                            CookieManager.getInstance().getCookie(url));
                                    request.allowScanningByMediaScanner();
                                    request.setNotificationVisibility(
                                            DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                            helper_main.newFileName());
                                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                    dm.enqueue(request);
                                    Snackbar.make(mWebView, getString(R.string.context_saveImage_toast) + " "
                                            + helper_main.newFileName(), Snackbar.LENGTH_SHORT).show();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
                                }
                            }
                        }
                        if (options[item].equals(getString(R.string.context_shareImage))) {
                            if (url != null) {

                                shareString = helper_main.newFileName();
                                shareFile = helper_main.newFile(mWebView);

                                try {
                                    Uri source = Uri.parse(url);
                                    DownloadManager.Request request = new DownloadManager.Request(source);
                                    request.addRequestHeader("Cookie",
                                            CookieManager.getInstance().getCookie(url));
                                    request.allowScanningByMediaScanner();
                                    request.setNotificationVisibility(
                                            DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                            shareString);
                                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                    dm.enqueue(request);

                                    Snackbar.make(mWebView, getString(R.string.context_saveImage_toast) + " "
                                            + helper_main.newFileName(), Snackbar.LENGTH_SHORT).show();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
                                }
                                registerReceiver(onComplete2,
                                        new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                            }
                        }
                        if (options[item].equals(getString(R.string.context_readLater))) {
                            if (url != null) {

                                if (Uri.parse(url).getHost().length() == 0) {
                                    domain = getString(R.string.app_domain);
                                } else {
                                    domain = Uri.parse(url).getHost();
                                }

                                String domain2 = domain.substring(0, 1).toUpperCase() + domain.substring(1);

                                DbAdapter_ReadLater db = new DbAdapter_ReadLater(Browser_left.this);
                                db.open();
                                if (db.isExist(mWebView.getUrl())) {
                                    Snackbar.make(editText, getString(R.string.toast_newTitle),
                                            Snackbar.LENGTH_LONG).show();
                                } else {
                                    db.insert(domain2, url, "", "", helper_main.createDate());
                                    Snackbar.make(mWebView, R.string.bookmark_added, Snackbar.LENGTH_LONG)
                                            .show();
                                }
                            }
                        }
                        if (options[item].equals(getString(R.string.context_right))) {
                            if (url != null) {
                                helper_main.switchToActivity(Browser_left.this, Browser_right.class, url,
                                        false);
                            }
                        }
                    }
                }).show();

    } else if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {

        final CharSequence[] options = { getString(R.string.menu_share_link_copy),
                getString(R.string.menu_share_link), getString(R.string.context_readLater),
                getString(R.string.context_right) };
        new AlertDialog.Builder(Browser_left.this)
                .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                }).setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals(getString(R.string.menu_share_link_copy))) {
                            if (url != null) {
                                ClipboardManager clipboard = (ClipboardManager) Browser_left.this
                                        .getSystemService(Context.CLIPBOARD_SERVICE);
                                clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                                Snackbar.make(mWebView, R.string.context_linkCopy_toast, Snackbar.LENGTH_SHORT)
                                        .show();
                            }
                        }
                        if (options[item].equals(getString(R.string.menu_share_link))) {
                            if (url != null) {
                                Intent sendIntent = new Intent();
                                sendIntent.setAction(Intent.ACTION_SEND);
                                sendIntent.putExtra(Intent.EXTRA_TEXT, url);
                                sendIntent.setType("text/plain");
                                Browser_left.this.startActivity(Intent.createChooser(sendIntent,
                                        getResources().getString(R.string.app_share_link)));
                            }
                        }
                        if (options[item].equals(getString(R.string.context_readLater))) {
                            if (url != null) {

                                if (Uri.parse(url).getHost().length() == 0) {
                                    domain = getString(R.string.app_domain);
                                } else {
                                    domain = Uri.parse(url).getHost();
                                }

                                String domain2 = domain.substring(0, 1).toUpperCase() + domain.substring(1);

                                DbAdapter_ReadLater db = new DbAdapter_ReadLater(Browser_left.this);
                                db.open();
                                if (db.isExist(mWebView.getUrl())) {
                                    Snackbar.make(editText, getString(R.string.toast_newTitle),
                                            Snackbar.LENGTH_LONG).show();
                                } else {
                                    db.insert(domain2, url, "", "", helper_main.createDate());
                                    Snackbar.make(mWebView, R.string.bookmark_added, Snackbar.LENGTH_LONG)
                                            .show();
                                }
                            }
                        }
                        if (options[item].equals(getString(R.string.context_right))) {
                            if (url != null) {
                                helper_main.switchToActivity(Browser_left.this, Browser_right.class, url,
                                        false);
                            }
                        }
                    }
                }).show();
    }
}

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

/**
 * Start app download for install on device.
 *
 * @param url           - APK Url should be passed in as a String.
 * @param operationId   - Id of the operation.
 * @param operationCode - Requested operation code.
 *///from w w  w  . j  a  v  a2s. co m
public void setupAppDownload(String url, int operationId, String operationCode) {
    Preference.putInt(context, context.getResources().getString(R.string.app_install_id), operationId);
    Preference.putString(context, context.getResources().getString(R.string.app_install_code), operationCode);

    if (url.contains(Constants.APP_DOWNLOAD_ENDPOINT) && Constants.APP_MANAGER_HOST != null) {
        url = url.substring(url.lastIndexOf("/"), url.length());
        this.appUrl = Constants.APP_MANAGER_HOST + Constants.APP_DOWNLOAD_ENDPOINT + url;
    } else {
        this.appUrl = url;
    }

    Preference.putString(context, context.getResources().getString(R.string.app_install_status),
            context.getResources().getString(R.string.app_status_value_download_started));

    if (Constants.DEFAULT_OWNERSHIP == Constants.OWNERSHIP_COSU) {
        downloadApp(this.appUrl);
    } else if (isDownloadManagerAvailable(context) && !url.contains(Constants.HTTPS_PROTOCOL)) {
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        context.registerReceiver(downloadReceiver, filter);
        removeExistingFile();
        downloadViaDownloadManager(this.appUrl, resources.getString(R.string.download_mgr_download_file_name));
    } else {
        downloadApp(this.appUrl);
    }
}

From source file:com.zertinteractive.wallpaper.MainActivity.java

public void initDownloadComponents() {

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override//  w w  w. j av  a2 s.co m
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                //
            }
        }
    };

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

From source file:scal.io.liger.LigerDownloadManager.java

private synchronized void initReceivers() {

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

    FilteredBroadcastReceiver onComplete = new FilteredBroadcastReceiver(fileName);
    BroadcastReceiver onNotificationClick = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            // ???
        }//from   w ww.j a  v  a  2s .c  o m
    };

    context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    context.registerReceiver(onNotificationClick,
            new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
}

From source file:net.momodalo.app.vimtouch.VimTouch.java

private void downloadFullRuntime() {

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override//from  ww w  .  java  2s .c  o 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

@Override
public void onResume() {
    super.onResume();
    if (mProgressBar != null && mProgressBar.isShowing())
        mProgressBar.dismiss();// w  ww  . jav a 2 s .c om
    registerReceiver(mBroadcastReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    // Check time since last update
    checkTimeSinceLastUpdate();
}

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

/**
 * Overrides onCreate method//  w ww .j  a  va 2s.com
 */
@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:com.nest5.businessClient.Initialactivity.java

@Override
public synchronized void onResume() {
    super.onResume();
    receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
    registerReceiver(receiver, intentFilter);
    registerReceiver(onSyncDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    SharedPreferences prefs = Util.getSharedPreferences(mContext);
    String connectionStatus = prefs.getString(Util.CONNECTION_STATUS, Util.DISCONNECTED);
    prefs.edit().putBoolean(Setup.IS_UPDATING, false);
    //mReader.start();
    // Performing this check in onResume() covers the case in which BT was onResume() 
    // not enabled during onStart(), so we were paused to enable it... onStart() 
    // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.ACTION_REQUEST_ENABLE
    if (mChatService != null) {
        // Only if the state is STATE_NONE, do we know that we haven't started already

        if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
            // Start the Bluetooth chat services
            mChatService.start();/*  w w w. j a  v  a2 s  . c  om*/
        }
    }
    lay = R.layout.home;
    setScreenContent();
    syncRows = syncRowDataSource.getAllSyncRows();
    //////Log.i("SYNC", "syncrows en db: "+String.valueOf(syncRows.size()));
    if (isConnectedToInternet())
        updateMaxSales();
    if (deviceText != null) {
        /**
         * Print over TCP / IP
         * 
         * ***/
        new connectTask().execute("");
    }

    //Toast.makeText(mContext, String.valueOf(productos.size()) ,Toast.LENGTH_LONG).show();

    if (openOtherWindow) {
        openOtherWindow = false;
        switch (openOtherWindowAction) {
        case OPEN_TABLE_ACTION:
            showCloseTableDialog();
            break;

        default:
            break;
        }
    }
}

From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java

public void initialize(ConfigurationProvider cfgProvider, MainService mainService) {
    T.UI();/* w ww . j  a va  2s  .  c o m*/
    mCfgProvider = cfgProvider;
    mMainService = mainService;
    mContext = mainService;

    List<BrandedItem> copy = new ArrayList<BrandingMgr.BrandedItem>();
    Collections.copy(mQueue, copy);
    for (BrandedItem item : copy)
        if (item.status != BrandedItem.STATUS_TODO)
            dequeue(item, false);

    mDownloaderThread = new HandlerThread("rogerthat_branding_worker");
    mDownloaderThread.start();
    Looper looper = mDownloaderThread.getLooper();
    mDownloaderHandler = new Handler(looper);

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_REMOVED);
    filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    mContext.registerReceiver(mBroadcastReceiver, filter);
    initStorageSettings();

    mInitialized = true;

    mMainService.postOnBIZZHandler(new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            if (mMainService.getPluginDBUpdates(BrandingMgr.class).contains(MUST_DELETE_ATTACHMENTS_INTENT)) {
                synchronized (mLock) {
                    IOUtils.deleteRecursive(getAttachmentsRootDirectory());
                }
                mMainService.clearPluginDBUpdate(BrandingMgr.class, MUST_DELETE_ATTACHMENTS_INTENT);
            }
        }
    });
}