Example usage for android.os Environment getExternalStoragePublicDirectory

List of usage examples for android.os Environment getExternalStoragePublicDirectory

Introduction

In this page you can find the example usage for android.os Environment getExternalStoragePublicDirectory.

Prototype

public static File getExternalStoragePublicDirectory(String type) 

Source Link

Document

Get a top-level shared/external storage directory for placing files of a particular type.

Usage

From source file:com.segma.trim.MainActivity.java

private void loadUserSetting() {
    preferences = getSharedPreferences(USER_PREFERENCE, MODE_PRIVATE);
    preferenceEditor = preferences.edit();
    if (isSDCARDAvailable()) {
        // check phone version > 5.1
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            isExternalStorageAllowed = checkPermission_6_0(this);
        }//from   w ww. j  ava  2s.  com
        PREF_SAVE_LOCATION_NULL = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                .getAbsolutePath();
        PREF_SAVE_LOCATION_VALUE = preferences.getString(PREF_SAVE_LOCATION, PREF_SAVE_LOCATION_NULL);

        Log.d(TAG, "isExternalStorageAllowed: " + String.valueOf(isExternalStorageAllowed));
    } else {
        //Toast.makeText(getApplicationContext(), WARNING_NO_SDCARD, Toast.LENGTH_LONG).show();
        PREF_SAVE_LOCATION_NULL = getFilesDir().getAbsolutePath();
        PREF_SAVE_LOCATION_VALUE = preferences.getString(PREF_SAVE_LOCATION, PREF_SAVE_LOCATION_NULL);
    }

    PREF_COLOR_VALUE = preferences.getInt(PREF_COLOR, PREF_COLOR_NULL);
    ipv.setInkColor(PREF_COLOR_VALUE);

}

From source file:com.lastsoft.plog.adapter.GameAdapter.java

public void playPopup(View v, final int position) {

    try {/*  w ww  .  j  a  va  2s .  co  m*/
        InputMethodManager inputManager = (InputMethodManager) mActivity
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        inputManager.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    } catch (Exception ignored) {
    }

    PopupMenu popup = new PopupMenu(mActivity, v);

    MenuInflater inflater = popup.getMenuInflater();

    if (games.get(position).expansionFlag == true) {
        inflater.inflate(R.menu.game_expansion_overflow, popup.getMenu());
    } else {
        inflater.inflate(R.menu.game_overflow, popup.getMenu());
    }
    if (games.get(position).gameBGGID == null || games.get(position).gameBGGID.equals("")) {
        popup.getMenu().removeItem(R.id.update_bgg);
        popup.getMenu().removeItem(R.id.open_bgg);
        popup.getMenu().removeItem(R.id.add_bgg);
    }
    if (games.get(position).gameBoxImage == null || games.get(position).gameBoxImage.equals("")) {
        popup.getMenu().removeItem(R.id.view_box_photo);
    }
    if (games.get(position).taggedToPlay <= 0) {
        popup.getMenu().removeItem(R.id.remove_bucket_list);
    } else {
        popup.getMenu().removeItem(R.id.add_bucket_list);
    }

    SharedPreferences app_preferences;
    app_preferences = PreferenceManager.getDefaultSharedPreferences(mActivity);
    long currentDefaultPlayer = app_preferences.getLong("defaultPlayer", -1);
    if (games.get(position).collectionFlag || currentDefaultPlayer == -1) {
        popup.getMenu().removeItem(R.id.add_bgg);
    }

    //check if this game has been played
    //if so, can't delete
    if (GamesPerPlay.hasGameBeenPlayed(games.get(position))) {
        popup.getMenu().removeItem(R.id.delete_game);
    }
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.delete_game:
                ((MainActivity) mActivity).deleteGame(games.get(position).getId());
                return true;
            case R.id.add_tenbyten:
                ((MainActivity) mActivity).addToTenXTen(games.get(position).getId());
                return true;
            case R.id.view_plays:
                if (games.get(position).expansionFlag == true) {
                    ((MainActivity) mActivity).openPlays(games.get(position).gameName, false, 9, fragmentName,
                            currentYear);
                } else {
                    ((MainActivity) mActivity).openPlays(games.get(position).gameName, false, 0, fragmentName,
                            currentYear);
                }
                return true;
            case R.id.open_bgg:
                Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://bgg.cc/boardgame/" + games.get(position).gameBGGID));
                mActivity.startActivity(browserIntent);
                return true;
            case R.id.update_bgg:
                mPosition = position;
                if (games.get(position).expansionFlag == true) {
                    ((MainActivity) mActivity).searchGameViaBGG(games.get(position).gameName, false, true, -1);
                } else {
                    ((MainActivity) mActivity).searchGameViaBGG(games.get(position).gameName, false, false, -1);
                }
                return true;
            case R.id.add_bgg:
                mPosition = position;
                ((MainActivity) mActivity).updateGameViaBGG(games.get(position).gameName,
                        games.get(position).gameBGGID, "", true, false);
                return true;
            case R.id.add_box_photo:
                ((GamesFragment) mFragment).captureBox(games.get(position));
                return true;
            case R.id.view_box_photo:
                String[] photoParts = games.get(position).gameBoxImage.split("/");
                File newFile = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                                + "/Plog/",
                        photoParts[photoParts.length - 1]);
                Uri contentUri = FileProvider.getUriForFile(mActivity.getApplicationContext(),
                        "com.lastsoft.plog.fileprovider", newFile);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(contentUri, "image/*");
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                mActivity.startActivity(intent);
                return true;
            case R.id.add_bucket_list:
                String[] ids = TimeZone.getAvailableIDs(-5 * 60 * 60 * 1000);
                // if no ids were returned, something is wrong. get out.
                //if (ids.length == 0)
                //    System.exit(0);

                // begin output
                //System.out.println("Current Time");

                // create a Eastern Standard Time time zone
                SimpleTimeZone pdt = new SimpleTimeZone(-5 * 60 * 60 * 1000, ids[0]);

                // set up rules for daylight savings time
                pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
                pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);

                // create a GregorianCalendar with the Pacific Daylight time zone
                // and the current date and time
                Calendar calendar = new GregorianCalendar(pdt);
                Date trialTime = new Date();
                calendar.setTime(trialTime);
                int i = (int) (calendar.getTime().getTime() / 1000);
                games.get(position).taggedToPlay = i;
                games.get(position).save();

                Snackbar.make(((GamesFragment) mFragment).mCoordinatorLayout,
                        games.get(position).gameName + mActivity.getString(R.string.added_to_bl),
                        Snackbar.LENGTH_LONG)
                        .setAction(mActivity.getString(R.string.undo), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                games.get(position).taggedToPlay = 0;
                                games.get(position).save();
                                if (playListType == 2) {
                                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                                }
                            }
                        }).show(); // Do not forget to show!

                return true;
            case R.id.remove_bucket_list:
                final int taggedToPlay = games.get(position).taggedToPlay;
                final Game gameToUndo = games.get(position);
                games.get(position).taggedToPlay = 0;
                games.get(position).save();

                Snackbar.make(((GamesFragment) mFragment).mCoordinatorLayout,
                        games.get(position).gameName + mActivity.getString(R.string.removed_from_bl),
                        Snackbar.LENGTH_LONG)
                        .setAction(mActivity.getString(R.string.undo), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                gameToUndo.taggedToPlay = taggedToPlay;
                                gameToUndo.save();
                                if (playListType == 2) {
                                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                                }
                            }
                        }).show(); // Do not forget to show!
                if (playListType == 2) {
                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                }
                return true;
            default:
                return false;
            }
        }
    }

    );
    popup.show();
}

From source file:fpt.isc.nshreport.utilities.FileUtils.java

public static File resizeImage(File file, int sizeMax) {
    try {/*w  w w  . ja  va 2  s.  c  o m*/

        // BitmapFactory options to downsize the image
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        o.inSampleSize = 6;
        // factor of downsizing the image

        FileInputStream inputStream = new FileInputStream(file);
        //Bitmap selectedBitmap = null;
        BitmapFactory.decodeStream(inputStream, null, o);
        inputStream.close();

        // The new size we want to scale to
        final int REQUIRED_SIZE = sizeMax;

        // Find the correct scale value. It should be the power of 2.
        int scale = 1;
        while ((o.outWidth) / scale >= REQUIRED_SIZE && (o.outHeight) / scale >= REQUIRED_SIZE) {
            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        inputStream = new FileInputStream(file);

        Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2);
        inputStream.close();

        // here i override the original image file
        /*String imageFileName = "JPEG_NSH_";
        File storageDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DCIM), "Camera");
        File image = File.createTempFile(
            imageFileName,
            ".jpg",
            storageDir
        );*/

        String imageFileName = "JPEG_NSH.jpg";
        File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                "Camera");

        File image = new File(storageDir, imageFileName);

        // Save a file: path for use with ACTION_VIEW intents
        FileOutputStream outputStream = new FileOutputStream(image);

        selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

        return image;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.nikhilnayak.games.octoshootar.ui.fragments.GameScoreFragment.java

private Uri writeScoreBytesToExternalStorage(ByteArrayOutputStream scoreBytes) {
    try {// ww w  . j a va  2s  .co  m
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_HH_ss");
        final String filePrefix = "score_";
        final String fileSuffix = ".jpg";
        final String fileName = filePrefix + simpleDateFormat.format(new Date()) + fileSuffix;
        final File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                + File.separator + "ChaseWhisply", fileName);
        if (!f.getParentFile().isDirectory()) {
            f.getParentFile().mkdirs();
        }
        f.createNewFile();
        final FileOutputStream fo = new FileOutputStream(f);
        fo.write(scoreBytes.toByteArray());
        fo.close();
        return Uri.fromFile(f);
    } catch (IOException e) {
        Log.e("GameScoreFragment", "error while sharing score", e);
        return null;
    }
}

From source file:com.simas.vc.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_concat:
        // ToDo ask user for a destination
        String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
                .getPath();//from  w w w.ja v  a2  s  . c o  m
        File output = new File(destination + File.separator + "output" + (++sNum) + ".mp4");
        if (output.exists()) {
            //noinspection ResultOfMethodCallIgnored
            output.delete();
        }
        try {
            // Concat videos
            FFmpeg.concat(output, sItems);
        } catch (IOException e) {
            Log.e(TAG, "Error!", e);
            new AlertDialog.Builder(this).setTitle(Utils.getString(R.string.error))
                    .setMessage("Unrecoverable error! Please try again.").setPositiveButton("OK...", null)
                    .show();
        } catch (VCException e) {
            Log.e(TAG, "Concatenation error:", e);
            new AlertDialog.Builder(this).setTitle(Utils.getString(R.string.error)).setMessage(e.getMessage())
                    .setPositiveButton("OK", null).show();
        }
        return true;
    case R.id.action_add_item:
        // When adding a new item
        showFileChooser(true);
        return true;
    case R.id.action_settings:
        return true;
    }

    return super.onOptionsItemSelected(item);
}

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;
    }//  w  w  w . j a  v  a2  s  .  c o  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:chinanurse.cn.nurse.Fragment_Nurse_job.IdentityFragment_ACTIVITY.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_CANCELED) {
        switch (requestCode) {
        case PHOTO_REQUEST_CAMERA:// 
            // ????
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                File tempFile = new File(path, "newpic.jpg");
                startPhotoZoom(Uri.fromFile(tempFile));
            } else {
                Toast.makeText(activity, "??", Toast.LENGTH_SHORT)
                        .show();//w w  w.j av a  2  s . c  om
            }
            break;
        case PHOTO_REQUEST_ALBUM:// 
            startPhotoZoom(data.getData());
            break;

        case PHOTO_REQUEST_CUT: // ??
            if (data != null) {
                getImageToView(data);
            }
            break;
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

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

/**
 * Save the attachment to its final resting place (cache or sd card)
 *//*from   w w w .ja va 2s.  c  om*/
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:cn.ucai.wechat.ui.SettingsActivity.java

void sendLogThroughMail() {
    String logPath = "";
    try {//from   ww w.j  a  v  a  2 s .  com
        logPath = EMClient.getInstance().compressLogs();
    } catch (Exception e) {
        e.printStackTrace();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(SettingsActivity.this, "compress logs failed", Toast.LENGTH_LONG).show();
            }
        });
        return;
    }
    File f = new File(logPath);
    File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    if (f.exists() && f.canRead()) {
        try {
            storage.mkdirs();
            File temp = File.createTempFile("hyphenate", ".log.gz", storage);
            if (!temp.canWrite()) {
                return;
            }
            boolean result = f.renameTo(temp);
            if (result == false) {
                return;
            }
            Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
            intent.setData(Uri.parse("mailto:"));
            intent.putExtra(Intent.EXTRA_SUBJECT, "log");
            intent.putExtra(Intent.EXTRA_TEXT, "log in attachment: " + temp.getAbsolutePath());

            intent.setType("application/octet-stream");
            ArrayList<Uri> uris = new ArrayList<>();
            uris.add(Uri.fromFile(temp));
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
            startActivity(intent);
        } catch (final Exception e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SettingsActivity.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}

From source file:net.jongrakko.zipsuri.activity.PostReviseActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {

        File cropFile = new File(UCrop.getOutput(data).getPath());

        int index = 0;
        for (int id : postImageViewIds) {
            ImageView mImageView = (ImageView) rootView.findViewById(id);
            if (mImageView.getTag() == null) {
                rootView.findViewById(postImageViewPlusIds[index]).setVisibility(View.VISIBLE);
                rootView.findViewById(postImageViewRemoveIds[index]).setVisibility(View.VISIBLE);
                mImageView.setImageBitmap(BitmapFactory.decodeFile(cropFile.getPath()));
                mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
                mImageView.setPadding(10, 10, 10, 10);
                mImageView.setTag(cropFile.getPath());
                mImageViewTitle.setImageDrawable(((ImageView) rootView.findViewById(id)).getDrawable());
                mImageViewTitle.setTag(id);
                break;
            }//from ww  w  .j av  a  2  s  . co m
            index++;
        }

    } else if (resultCode == Activity.RESULT_OK && requestCode == PICK_PHOTO_FOR_AVATAR) {
        UCrop.of(data.getData(),
                Uri.fromFile(
                        new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                System.currentTimeMillis() + ".jpg")))
                .withMaxResultSize(1920, 1920).start(getContext(), this);
    } else if (resultCode == Activity.RESULT_OK && requestCode == TAKE_PHOTO_FOR_AVATAR) {
        UCrop.of(Uri.fromFile(takeFile),
                Uri.fromFile(
                        new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                System.currentTimeMillis() + ".jpg")))
                .withMaxResultSize(1920, 1920).start(getContext(), this);

    } else if (resultCode == UCrop.RESULT_ERROR) {
        final Throwable cropError = UCrop.getError(data);
        Log.d("mox", "croperror" + cropError.toString());

    } else if (resultCode == Activity.RESULT_OK && requestCode == SEARCH_ADDRESS) {
        AddressModel mAddressModel = (AddressModel) data.getSerializableExtra("data");
        setAddressModel(mAddressModel);
    } else if (resultCode == Activity.RESULT_OK && requestCode == PICK_VIDEO_FOR_AVATAR) {
        String path = getPath(data.getData());
        showVideoAlertDialog(path);
    } else if (resultCode == Activity.RESULT_OK && requestCode == TAKE_VIDEO_FOR_AVATAR) {
        String path = takeFile.getPath();
        showVideoAlertDialog(path);
    }

}