Example usage for android.content Context DOWNLOAD_SERVICE

List of usage examples for android.content Context DOWNLOAD_SERVICE

Introduction

In this page you can find the example usage for android.content Context DOWNLOAD_SERVICE.

Prototype

String DOWNLOAD_SERVICE

To view the source code for android.content Context DOWNLOAD_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.app.DownloadManager for requesting HTTP downloads.

Usage

From source file:com.android.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *///  ww  w. j ava  2 s  .c o  m
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri;
    long size;
    try {
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            File saveIn = getAttachmentDirectory(context, accountId);
            if (!saveIn.exists()) {
                saveIn.mkdirs();
            }
            File file = getAttachmentFilename(context, accountId, attachmentId);
            file.createNewFile();
            size = copyFile(in, file);
            contentUri = getAttachmentUri(accountId, attachmentId).toString();
        } else if (Utility.isExternalStorageMounted()) {
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, file);
            String absolutePath = file.getAbsolutePath();

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            Log.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

}

From source file:com.chen.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 */// w ww  .j a  v  a  2  s.  c  o m
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri = null;
    long size;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            String srcContentUri = " src=\"" + contentUri + "\"";
            html = html.replaceAll(contentIdRe, srcContentUri);
            cv.put(BodyColumns.HTML_CONTENT, html);
            context.getContentResolver().update(ContentUris.withAppendedId(Body.CONTENT_URI, body.mId), cv,
                    null, null);
        }
    }
}

From source file:com.indeema.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *///w ww.j ava2 s  . c o  m
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri = null;
    long size;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            if (attachment.mFileName == null) {
                // TODO: This will prevent a crash but does not surface the underlying problem
                // to the user correctly.
                LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId);
                throw new IOException("Can't save an attachment with no name");
            }
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            String srcContentUri = " src=\"" + contentUri + "\"";
            html = html.replaceAll(contentIdRe, srcContentUri);
            cv.put(BodyColumns.HTML_CONTENT, html);
            context.getContentResolver().update(ContentUris.withAppendedId(Body.CONTENT_URI, body.mId), cv,
                    null, null);
        }
    }
}

From source file:com.p3authentication.preferences.Prefs.java

public void downloadFile(String BASEURL, String imagename) {
    // TODO Auto-generated method stub
    String DownloadUrl = BASEURL + "images/" + imagename;
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
    request.setDescription("P3 Resources"); // appears the same
    // in Notification
    // bar while/*from www .ja  v a2  s.c om*/
    // downloading
    request.setTitle("P3 Resources");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
    }
    String fileName = DownloadUrl.substring(DownloadUrl.lastIndexOf('/') + 1, DownloadUrl.length());
    request.setDestinationInExternalFilesDir(getApplicationContext(), null, fileName);

    // get download service and enqueue file
    DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    enqueue.offer(dm.enqueue(request));

}

From source file:com.viktorrudometkin.burramys.fragment.EntryFragment.java

@Override
public void onClickEnclosure() {
    getActivity().runOnUiThread(new Runnable() {
        @Override//from  w w  w .j  a  v a  2s .  c  o  m
        public void run() {
            final String enclosure = mEntryPagerAdapter.getCursor(mCurrentPagerPos).getString(mEnclosurePos);

            final int position1 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR);
            final int position2 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR, position1 + 3);

            final Uri uri = Uri.parse(enclosure.substring(0, position1));
            final String filename = uri.getLastPathSegment();

            new AlertDialog.Builder(getActivity()).setTitle(R.string.open_enclosure)
                    .setMessage(getString(R.string.file) + ": " + filename)
                    .setPositiveButton(R.string.open_link, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showEnclosure(uri, enclosure, position1, position2);
                        }
                    }).setNegativeButton(R.string.download_and_save, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                DownloadManager.Request r = new DownloadManager.Request(uri);
                                r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
                                r.allowScanningByMediaScanner();
                                r.setNotificationVisibility(
                                        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager dm = (DownloadManager) MainApplication.getContext()
                                        .getSystemService(Context.DOWNLOAD_SERVICE);
                                dm.enqueue(r);
                            } catch (Exception e) {
                                UiUtils.showMessage(getActivity(), R.string.error);
                            }
                        }
                    }).show();
        }
    });
}

From source file:com.carlrice.reader.fragment.EntryFragment.java

@Override
public void onClickEnclosure() {
    getActivity().runOnUiThread(new Runnable() {
        @Override//from w  w w . ja va2  s  .com
        public void run() {
            final String enclosure = mEntryPagerAdapter.getCursor(mCurrentPagerPos).getString(mEnclosurePos);

            final int position1 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR);
            final int position2 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR, position1 + 3);

            final Uri uri = Uri.parse(enclosure.substring(0, position1));
            final String filename = uri.getLastPathSegment();

            new AlertDialog.Builder(getActivity()).setTitle(R.string.open_enclosure)
                    .setMessage(getString(R.string.file) + ": " + filename)
                    .setPositiveButton(R.string.open_link, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showEnclosure(uri, enclosure, position1, position2);
                        }
                    }).setNegativeButton(R.string.download_and_save, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                DownloadManager.Request r = new DownloadManager.Request(uri);
                                r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
                                r.allowScanningByMediaScanner();
                                r.setNotificationVisibility(
                                        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager dm = (DownloadManager) Application.context()
                                        .getSystemService(Context.DOWNLOAD_SERVICE);
                                dm.enqueue(r);
                            } catch (Exception e) {
                                Toast.makeText(getActivity(), R.string.error, Toast.LENGTH_LONG).show();
                            }
                        }
                    }).show();
        }
    });
}

From source file:com.flym.dennikn.fragment.EntryFragment.java

@Override
public void onClickEnclosure() {
    getActivity().runOnUiThread(new Runnable() {
        @Override//from   w w w .  jav  a  2  s. c  om
        public void run() {
            final String enclosure = mEntryPagerAdapter.getCursor(mCurrentPagerPos).getString(mEnclosurePos);

            final int position1 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR);
            final int position2 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR, position1 + 3);

            final Uri uri = Uri.parse(enclosure.substring(0, position1));
            final String filename = uri.getLastPathSegment();

            new AlertDialog.Builder(getActivity()).setTitle(R.string.open_enclosure)
                    .setMessage(getString(R.string.file) + ": " + filename)
                    .setPositiveButton(R.string.open_link, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showEnclosure(uri, enclosure, position1, position2);
                        }
                    }).setNegativeButton(R.string.download_and_save, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                DownloadManager.Request r = new DownloadManager.Request(uri);
                                r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
                                r.allowScanningByMediaScanner();
                                r.setNotificationVisibility(
                                        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager dm = (DownloadManager) MainApplication.getContext()
                                        .getSystemService(Context.DOWNLOAD_SERVICE);
                                dm.enqueue(r);
                            } catch (Exception e) {
                                Toast.makeText(getActivity(), R.string.error, Toast.LENGTH_LONG).show();
                            }
                        }
                    }).show();
        }
    });
}

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 ww .  ja v  a2s. c o m*/
    final DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);

    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
    if (downloadId == -1)
        return;
    boolean isPendingOMADownload = mOMADownloadHandler.isPendingOMADownload(downloadId);
    boolean isInOMASharedPrefs = isDownloadIdInOMASharedPrefs(downloadId);
    if (isPendingOMADownload || isInOMASharedPrefs) {
        clearPendingOMADownload(downloadId, null);
        mPendingAutoOpenDownloads.remove(downloadId);
    } else if (mPendingAutoOpenDownloads.get(downloadId) != null) {
        Cursor c = manager.query(new DownloadManager.Query().setFilterById(downloadId));
        int statusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
        while (c.moveToNext()) {
            int status = c.getInt(statusIndex);
            DownloadInfo info = mPendingAutoOpenDownloads.get(downloadId);
            switch (status) {
            case DownloadManager.STATUS_SUCCESSFUL:
                try {
                    mPendingAutoOpenDownloads.remove(downloadId);
                    if (OMADownloadHandler.OMA_DOWNLOAD_DESCRIPTOR_MIME.equalsIgnoreCase(info.getMimeType())) {
                        mOMADownloadHandler.handleOMADownload(info, downloadId);
                        manager.remove(downloadId);
                        break;
                    }
                    Uri uri = manager.getUriForDownloadedFile(downloadId);
                    Intent launchIntent = new Intent(Intent.ACTION_VIEW);

                    launchIntent.setDataAndType(uri, manager.getMimeTypeForDownloadedFile(downloadId));
                    launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    mContext.startActivity(launchIntent);
                } catch (ActivityNotFoundException e) {
                    Log.w(TAG, "Activity not found.");
                }
                break;
            case DownloadManager.STATUS_FAILED:
                mPendingAutoOpenDownloads.remove(downloadId);
                break;
            default:
                break;
            }
        }
    }

    if (mPendingAutoOpenDownloads.size() == 0) {
        mContext.unregisterReceiver(this);
    }
}

From source file:com.tct.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *///from   www .j a v a2s  .  c o  m
public static long saveAttachment(Context context, InputStream in, Attachment attachment) {
    final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    final ContentValues cv = new ContentValues();
    final long attachmentId = attachment.mId;
    final long accountId = attachment.mAccountKey;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    String contentUri = null;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    String realUri = null; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD
    long size = 0;

    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.UIPROVIDER_ATTACHMENTDESTINATION_CACHE) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment when attachment destination is cache",
                    "attachment.size:" + attachment.mSize);
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment to storage",
                    "attachment.size:" + attachment.mSize);
            if (TextUtils.isEmpty(attachment.mFileName)) {
                // TODO: This will prevent a crash but does not surface the underlying problem
                // to the user correctly.
                LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId);
                throw new IOException("Can't save an attachment with no name");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
            String exchange = "com.tct.exchange";
            if (exchange.equals(context.getPackageName()) && !PermissionUtil
                    .checkPermissionAndLaunchExplain(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                throw new IOException("Can't save an attachment due to no Storage permission");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();
            realUri = "file://" + absolutePath; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            final String mimeType = TextUtils.isEmpty(attachment.mMimeType) ? "application/octet-stream"
                    : attachment.mMimeType;

            try {
                DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_S
                //Note: should use media scanner, it will allow update the
                //media provider uri column in download manager's database.
                long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                        true /* use media scanner */, mimeType, absolutePath, size,
                        true /* show notification */);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_E
                contentUri = dm.getUriForDownloadedFile(id).toString();
            } catch (final IllegalArgumentException e) {
                LogUtils.d(LogUtils.TAG, e, "IAE from DownloadManager while saving attachment");
                throw new IOException(e);
            }
        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_SAVED);
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
        if (realUri != null) {
            cv.put(AttachmentColumns.REAL_URI, realUri);
        }
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
    } catch (IOException e) {
        LogUtils.e(Logging.LOG_TAG, e, "Fail to save attachment to storage!");
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null && attachment.mContentId.length() > 0) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_S
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_S
            String srcContentUri = " src=\"" + contentUri + "\"";
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_E
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_E
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S
            try {
                html = html.replaceAll(contentIdRe, srcContentUri);
            } catch (PatternSyntaxException e) {
                LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern");
            }
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E
            cv.put(BodyColumns.HTML_CONTENT, html);
            Body.updateBodyWithMessageId(context, attachment.mMessageKey, cv);
            Body.restoreBodyHtmlWithMessageId(context, attachment.mMessageKey);
        }
    }
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    return size;
}

From source file:fr.kwiatkowski.apktrack.service.WebService.java

/**
 * Downloads the APK for a given app if a download URL is available.
 * APK downloads take place through the Download Service. Files are stored on a dedicated
 * folder on the external storage of the device.
 * @param app The app whose APK is to be downloaded.
 *///from  www  .  j  av  a 2s. com
private void _download_apk(InstalledApp app, String request_source) {
    if (app.get_download_url() == null) {
        return;
    }

    Uri uri = Uri
            .parse(String.format(app.get_download_url(), app.get_display_name(), app.get_latest_version()));

    DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(uri);

    // Indicate whether the download may take place over mobile data.
    // Download over data is okay on user click, but respect the preference for background checks.
    if (ScheduledCheckService.SERVICE_SOURCE.equals(request_source) && PreferenceManager
            .getDefaultSharedPreferences(this).getBoolean(SettingsFragment.KEY_PREF_WIFI_ONLY, true)) {
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
    } else {
        request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
    }

    // Don't download APKs when roaming.
    request.setAllowedOverRoaming(false).setTitle(getString(getApplicationInfo().labelRes))
            .setDescription(app.get_display_name() + " " + app.get_latest_version() + ".apk")
            .setVisibleInDownloadsUi(false).setDestinationInExternalFilesDir(this,
                    Environment.DIRECTORY_DOWNLOADS,
                    app.get_package_name() + "-" + app.get_latest_version() + ".apk");
    long id = dm.enqueue(request);
    app.set_download_id(id);
    app.save();
    EventBusHelper.post_sticky(ModelModifiedMessage.event_type.APP_UPDATED, app.get_package_name());
}