Example usage for android.media MediaScannerConnection scanFile

List of usage examples for android.media MediaScannerConnection scanFile

Introduction

In this page you can find the example usage for android.media MediaScannerConnection scanFile.

Prototype

public static void scanFile(Context context, String[] paths, String[] mimeTypes,
        OnScanCompletedListener callback) 

Source Link

Document

Convenience for constructing a MediaScannerConnection , calling #connect on it, and calling #scanFile with the given path and mimeType when the connection is established.

Usage

From source file:org.neotree.ui.fragment.DataExportFragment.java

private boolean exportAsExcelSpreadsheet(ExportData exportData) {
    if (exportData.getEntries() == null || exportData.getEntries().size() == 0) {
        Log.d(TAG, "Nothing to export for script");
        return false;
    }//from   w ww.ja  v a 2  s  .  c o m

    final ArrayList<String> headers = new ArrayList<>();
    final HashMap<String, Integer> columnMap = new HashMap<>();
    final List<Screen> screens = exportData.getScreens();

    int columnIndex = 0;

    for (int screenIndex = 0; screens != null && screenIndex < screens.size(); screenIndex++) {
        final Screen screen = screens.get(screenIndex);
        final ScreenType screenType = ScreenType.fromString(screen.type);
        final Metadata metadata = screen.metadata;

        // Map screen keys
        String screenKey = (TextUtils.isEmpty(metadata.key)) ? null : metadata.key.trim();
        if (screenKey != null && !metadata.confidential) {
            if (screenType == ScreenType.MULTI_SELECT) {
                String itemKey;
                for (int itemIndex = 0; itemIndex < metadata.items.size(); itemIndex++) {
                    final Item item = metadata.items.get(itemIndex);
                    itemKey = String.format("%s_%s", screenKey, item.id);
                    Log.d(TAG, String.format("Mapping item key (multiple selection) [key=%s, index=%d]",
                            itemKey, columnIndex));
                    columnMap.put(itemKey, columnIndex++);
                    headers.add(itemKey);
                }
            } else {
                Log.d(TAG, String.format("Mapping screen key [key=%s, index=%d]", screenKey, columnIndex));
                columnMap.put(screenKey, columnIndex++);
                headers.add(screenKey);
            }
        } else {
            if (screenType == ScreenType.FORM) {
                // Map field keys
                String fieldKey = null;
                if (metadata.fields != null && metadata.fields.size() > 0) {
                    for (int fieldIndex = 0; fieldIndex < metadata.fields.size(); fieldIndex++) {
                        final Field field = metadata.fields.get(fieldIndex);
                        fieldKey = (TextUtils.isEmpty(field.key)) ? null : field.key.trim();

                        if (fieldKey != null && !field.confidential) {
                            Log.d(TAG, String.format("Mapping field key [key=%s, index=%d]", fieldKey,
                                    columnIndex));
                            columnMap.put(fieldKey, columnIndex++);
                            headers.add(fieldKey);
                        }
                    }
                }
            } else {
                // Map item keys
                if (metadata.items != null) {
                    if (screenType == ScreenType.CHECKLIST) {
                        String itemKey;
                        for (int itemIndex = 0; itemIndex < metadata.items.size(); itemIndex++) {
                            final Item item = metadata.items.get(itemIndex);
                            itemKey = (TextUtils.isEmpty(item.key)) ? null : item.key.trim();

                            if (itemKey != null && !item.confidential) {
                                Log.d(TAG, String.format("Mapping item key (checklist) [key=%s, index=%d]",
                                        itemKey, columnIndex));
                                columnMap.put(itemKey, columnIndex++);
                                headers.add(itemKey);
                            }
                        }
                    }
                }
            }
        }
    }

    WritableWorkbook workbook = null;
    try {
        File exportRootDir = Environment.getExternalStoragePublicDirectory("NeoTree");
        if (!exportRootDir.isDirectory()) {
            if (!exportRootDir.mkdirs()) {
                throw new IOException("Error creating output directory: " + exportRootDir.getAbsolutePath());
            }
        }

        File noMediaFile = new File(exportRootDir, ".nomedia");
        if (!noMediaFile.exists()) {
            if (!noMediaFile.createNewFile()) {
                throw new IOException("Error creating .nomedia file: " + noMediaFile.getAbsolutePath());
            }
        }

        String title = exportData.getScript().title;
        String filename = String.format("%s-%s.xls",
                DateTime.now().toString(DateTimeFormat.forPattern("yyyyMMddHHmm")),
                title.replaceAll("[^a-zA-Z0-9]", "_"));
        File exportFile = new File(exportRootDir, filename);

        Log.d(TAG, "Filename :" + filename);
        Log.d(TAG, "File path:" + exportFile.getAbsolutePath());
        WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setLocale(Locale.ENGLISH);

        workbook = Workbook.createWorkbook(exportFile, wbSettings);

        WritableSheet sheet = workbook.createSheet(title, 0);

        // Add headers
        for (int c = 0; c < headers.size(); c++) {
            sheet.addCell(new Label(c, 0, headers.get(c)));
        }

        // Add rows
        String sessionId = null;
        int rowIndex = 0;

        for (SessionEntry entry : exportData.getEntries()) {
            if (sessionId == null || !sessionId.equals(entry.getSessionId())) {
                sessionId = entry.getSessionId();
                rowIndex++;
            }

            DataType dataType = entry.getDataTypeAsObject();
            switch (dataType) {
            case SET_ID:
                if (entry.getValues() != null) {
                    for (SessionValue value : entry.getValues()) {
                        String itemKey = String.format("%s_%s", value.getKey(), value.getStringValue());
                        try {
                            Label cell = new Label(columnMap.get(itemKey), rowIndex, "Yes");
                            sheet.addCell(cell);
                        } catch (Exception e) {
                            Log.e(TAG, String.format("item key for set does not exist: %s", itemKey), e);
                        }
                    }
                }
                break;
            default:
                String key = entry.getKey();
                try {
                    if (!TextUtils.isEmpty(key) && key.contains(" ")) {
                        key = key.replaceAll("\\s+", "");
                    }

                    String content = entry.getSingleValue().getValueAsExportString(getActivity());
                    sheet.addCell(new Label(columnMap.get(key), rowIndex, content));
                } catch (Exception e) {
                    Log.e(TAG, String.format("item key does not exist: %s", key), e);
                }
            }
        }

        workbook.write();

        // Tell the media scanner about the new file so that it is
        // immediately available to the user.
        MediaScannerConnection.scanFile(getActivity(), new String[] { exportFile.toString() }, null,
                (path, uri) -> {
                    Log.d(TAG, String.format("Success exporting data [path=%s, uri=%s]", path, uri));
                });

    } catch (IOException | WriteException e) {
        Log.e(TAG, "Error exporting Excel file", e);
        Crashlytics.logException(e);
        return false;
    } finally {
        try {
            if (workbook != null) {
                workbook.close();
            }
        } catch (IOException | WriteException e) {
            Log.e(TAG, "Error closing workbook file", e);
            Crashlytics.logException(e);
            return false;
        }
    }
    return true;
}

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

/**
 * Save the attachment to its final resting place (cache or sd card)
 *//*from  ww  w  .  ja  v  a2 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)
 *///  www.jav a  2 s  .  co 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)
 *//*from w  w w .j a va  2s  .  c  om*/
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.android.nfc.beam.BeamTransferManager.java

void processFiles() {
    // Check the amount of files we received in this transfer;
    // If more than one, create a separate directory for it.
    String extRoot = Environment.getExternalStorageDirectory().getPath();
    File beamPath = new File(extRoot + "/" + BEAM_DIR);

    if (!checkMediaStorage(beamPath) || mUris.size() == 0) {
        Log.e(TAG, "Media storage not valid or no uris received.");
        updateStateAndNotification(STATE_FAILED);
        return;/*w w w .  j  a v a2  s .  c om*/
    }

    if (mUris.size() > 1) {
        beamPath = generateMultiplePath(extRoot + "/" + BEAM_DIR + "/");
        if (!beamPath.isDirectory() && !beamPath.mkdir()) {
            Log.e(TAG, "Failed to create multiple path " + beamPath.toString());
            updateStateAndNotification(STATE_FAILED);
            return;
        }
    }

    for (int i = 0; i < mUris.size(); i++) {
        Uri uri = mUris.get(i);
        String mimeType = mTransferMimeTypes.get(i);

        File srcFile = new File(uri.getPath());

        File dstFile = generateUniqueDestination(beamPath.getAbsolutePath(), uri.getLastPathSegment());
        Log.d(TAG, "Renaming from " + srcFile);
        if (!srcFile.renameTo(dstFile)) {
            if (DBG)
                Log.d(TAG, "Failed to rename from " + srcFile + " to " + dstFile);
            srcFile.delete();
            return;
        } else {
            mPaths.add(dstFile.getAbsolutePath());
            mMimeTypes.put(dstFile.getAbsolutePath(), mimeType);
            if (DBG)
                Log.d(TAG, "Did successful rename from " + srcFile + " to " + dstFile);
        }
    }

    // We can either add files to the media provider, or provide an ACTION_VIEW
    // intent to the file directly. We base this decision on the mime type
    // of the first file; if it's media the platform can deal with,
    // use the media provider, if it's something else, just launch an ACTION_VIEW
    // on the file.
    String mimeType = mMimeTypes.get(mPaths.get(0));
    if (mimeType.startsWith("image/") || mimeType.startsWith("video/") || mimeType.startsWith("audio/")) {
        String[] arrayPaths = new String[mPaths.size()];
        MediaScannerConnection.scanFile(mContext, mPaths.toArray(arrayPaths), null, this);
        updateStateAndNotification(STATE_W4_MEDIA_SCANNER);
    } else {
        // We're done.
        updateStateAndNotification(STATE_SUCCESS);
    }

}

From source file:com.orpheusdroid.screenrecorder.RecorderService.java

private void indexFile() {
    //Create a new ArrayList and add the newly created video file path to it
    ArrayList<String> toBeScanned = new ArrayList<>();
    toBeScanned.add(SAVEPATH);/*from  w ww.  j  a va  2  s.c o m*/
    String[] toBeScannedStr = new String[toBeScanned.size()];
    toBeScannedStr = toBeScanned.toArray(toBeScannedStr);

    //Request MediaScannerConnection to scan the new file and index it
    MediaScannerConnection.scanFile(this, toBeScannedStr, null,
            new MediaScannerConnection.OnScanCompletedListener() {

                @Override
                public void onScanCompleted(String path, Uri uri) {
                    Log.i(Const.TAG, "SCAN COMPLETED: " + path);
                    //Show toast on main thread
                    Message message = mHandler.obtainMessage();
                    message.sendToTarget();
                    stopSelf();
                }
            });
}

From source file:net.gsantner.opoc.util.ContextUtils.java

/**
 * Request the givens paths to be scanned by MediaScanner
 *
 * @param files Files and folders to scan
 *//*  w ww . j  a  v a2  s  .co m*/
public void mediaScannerScanFile(File... files) {
    if (android.os.Build.VERSION.SDK_INT > 19) {
        String[] paths = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            paths[i] = files[i].getAbsolutePath();
        }
        MediaScannerConnection.scanFile(_context, paths, null, null);
    } else {
        for (File file : files) {
            _context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        }
    }
}

From source file:org.kontalk.util.MediaStorage.java

public static void scanFile(Context context, File file, String mime) {
    MediaScannerConnection.scanFile(context.getApplicationContext(), new String[] { file.getPath() },
            new String[] { mime }, null);
}

From source file:org.neotree.ui.fragment.DataExportFragment.java

private boolean exportAsJson(ExportData exportData) {
    if (exportData.getEntries() == null || exportData.getEntries().size() == 0) {
        Log.d(TAG, "Nothing to export for script");
        return false;
    }//from   w w w. ja va 2s .co m

    ObjectMapper mapper = new ObjectMapper();

    ObjectNode root = mapper.createObjectNode();
    ArrayNode jsonSessions = root.putArray("sessions");

    ObjectNode jsonSession = null;
    ArrayNode jsonSessionEntries = null;
    ObjectNode jsonEntry;
    ArrayNode jsonEntryValues;
    String sessionId = null;

    for (SessionEntry entry : exportData.getEntries()) {
        if (sessionId == null || !sessionId.equals(entry.getSessionId())) {
            if (jsonSession != null) {
                jsonSessions.add(jsonSession);
            }
            sessionId = entry.getSessionId();
            jsonSession = mapper.createObjectNode();
            jsonSession.put("sessionId", sessionId);

            ObjectNode jsonScript = jsonSession.putObject("script");
            jsonScript.put("id", exportData.getScript().scriptId);
            jsonScript.put("title", exportData.getScript().title);

            jsonSessionEntries = jsonSession.putArray("entries");
        }

        jsonEntry = mapper.createObjectNode();
        jsonEntry.put("key", entry.getKey());
        jsonEntry.put("type", entry.getDataType());
        jsonEntryValues = jsonEntry.putArray("values");

        jsonSessionEntries.add(jsonEntry);

        DataType dataType = entry.getDataTypeAsObject();
        ObjectNode jsonValue;
        SessionValue value;
        switch (dataType) {
        case BOOLEAN:
        case DATE:
        case DATETIME:
        case STRING:
        case ID:
        case NUMBER:
        case PERIOD:
        case TIME:
            value = entry.getSingleValue();

            jsonValue = mapper.createObjectNode();
            jsonValue.put("label", value.getValueLabel());
            switch (dataType) {
            case BOOLEAN:
                jsonValue.put("value", value.getBooleanValue());
                break;
            case DATE:
            case DATETIME:
            case STRING:
            case ID:
                jsonValue.put("value", value.getStringValue());
                break;
            case NUMBER:
                jsonValue.put("value", value.getDoubleValue());
                break;
            case PERIOD:
            case TIME:
                jsonValue.put("value", value.getValueAsFormattedString(getActivity()));
                break;
            }
            jsonEntryValues.add(jsonValue);
            break;

        case SET_ID:
            if (entry.getValues() != null) {
                for (SessionValue sessionValue : entry.getValues()) {
                    jsonValue = mapper.createObjectNode();
                    jsonValue.put("label", sessionValue.getValueLabel());
                    jsonValue.put("value", sessionValue.getStringValue());
                    jsonEntryValues.add(jsonValue);
                }
            }
            break;

        default:
            break;
        }
    }

    try {
        File exportRootDir = Environment.getExternalStoragePublicDirectory("NeoTree");
        if (!exportRootDir.isDirectory()) {
            if (!exportRootDir.mkdirs()) {
                throw new IOException("Error creating output directory: " + exportRootDir.getAbsolutePath());
            }
        }

        File noMediaFile = new File(exportRootDir, ".nomedia");
        if (!noMediaFile.exists()) {
            if (!noMediaFile.createNewFile()) {
                throw new IOException("Error creating .nomedia file: " + noMediaFile.getAbsolutePath());
            }
        }

        String title = exportData.getScript().title;
        String filename = String.format("%s-%s.json",
                DateTime.now().toString(DateTimeFormat.forPattern("yyyyMMddHHmm")),
                title.replaceAll("[^a-zA-Z0-9]", "_"));
        File exportFile = new File(exportRootDir, filename);

        // Write JSON output
        mapper.writeValue(exportFile, root);

        // Tell the media scanner about the new file so that it is
        // immediately available to the user.
        MediaScannerConnection.scanFile(getActivity(), new String[] { exportFile.toString() }, null,
                (path, uri) -> {
                    Log.d(TAG, String.format("Success exporting data [path=%s, uri=%s]", path, uri));
                });

    } catch (IOException e) {
        Log.e(TAG, "Error exporting Excel file", e);
        Crashlytics.logException(e);
        return false;
    }

    return true;
}

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

/**
 * Save the attachment to its final resting place (cache or sd card)
 *///  ww  w  . j  a v a 2 s . co  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;
}