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:org.mozilla.gecko.updater.UpdateService.java

private File downloadUpdatePackage(UpdateInfo info, boolean overwriteExisting) {
    URL url = null;/*w ww  .  j  a  va  2s.co  m*/
    try {
        url = info.uri.toURL();
    } catch (java.net.MalformedURLException e) {
        Log.e(LOGTAG, "failed to read URL: ", e);
        return null;
    }

    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    path.mkdirs();
    String fileName = new File(url.getFile()).getName();
    File downloadFile = new File(path, fileName);

    if (!overwriteExisting && info.buildID.equals(getLastBuildID()) && downloadFile.exists()) {
        // The last saved buildID is the same as the one for the current update. We also have a file
        // already downloaded, so it's probably the package we want. Verify it to be sure and just
        // return that if it matches.

        if (verifyDownloadedPackage(downloadFile)) {
            Log.i(LOGTAG, "using existing update package");
            return downloadFile;
        } else {
            // Didn't match, so we're going to download a new one.
            downloadFile.delete();
        }
    }

    if (!info.buildID.equals(getLastBuildID())) {
        // Delete the previous package when a new version becomes available.
        deleteUpdatePackage(getLastFileName());
    }

    Log.i(LOGTAG, "downloading update package");
    sendCheckUpdateResult(CheckUpdateResult.DOWNLOADING);

    OutputStream output = null;
    InputStream input = null;

    mDownloading = true;
    mCancelDownload = false;
    showDownloadNotification(downloadFile);

    try {
        NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected() && netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            mWifiLock.acquire();
        }

        URLConnection conn = openConnectionWithProxy(info.uri);
        int length = conn.getContentLength();

        output = new BufferedOutputStream(new FileOutputStream(downloadFile));
        input = new BufferedInputStream(conn.getInputStream());

        byte[] buf = new byte[BUFSIZE];
        int len = 0;

        int bytesRead = 0;
        int lastNotify = 0;

        while ((len = input.read(buf, 0, BUFSIZE)) > 0 && !mCancelDownload) {
            output.write(buf, 0, len);
            bytesRead += len;
            // Updating the notification takes time so only do it every 1MB
            if (bytesRead - lastNotify > 1048576) {
                mBuilder.setProgress(length, bytesRead, false);
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                lastNotify = bytesRead;
            }
        }

        mNotificationManager.cancel(NOTIFICATION_ID);

        // if the download was canceled by the user
        // delete the update package
        if (mCancelDownload) {
            Log.i(LOGTAG, "download canceled by user!");
            downloadFile.delete();

            return null;
        } else {
            Log.i(LOGTAG, "completed update download!");
            return downloadFile;
        }
    } catch (Exception e) {
        downloadFile.delete();
        showDownloadFailure();

        Log.e(LOGTAG, "failed to download update: ", e);
        return null;
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (java.io.IOException e) {
        }

        try {
            if (output != null)
                output.close();
        } catch (java.io.IOException e) {
        }

        mDownloading = false;

        if (mWifiLock.isHeld()) {
            mWifiLock.release();
        }
    }
}

From source file:com.ddoskify.CameraOverlayActivity.java

private static File getOutputMediaFile() {
    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "ddoskify");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.e("Ddoski", "failed to create directory " + mediaStorageDir.toString());
            return null;
        }/*from  w  w  w  .  ja va  2 s.  c om*/
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");

    return mediaFile;
}

From source file:com.remobile.camera.CameraLauncher.java

private String getPicutresPath() {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "IMG_" + timeStamp + ".jpg";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String galleryPath = storageDir.getAbsolutePath() + "/" + imageFileName;
    return galleryPath;
}

From source file:com.example.zf_android.activity.MerchantEdit.java

private void show3Dialog(int type, final String uri) {
    AlertDialog.Builder builder = new AlertDialog.Builder(MerchantEdit.this);
    final String[] items = getResources().getStringArray(R.array.apply_detail_view);

    MerchantEdit.this.type = type;
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override/*from ww w.  j  ava 2 s  .c  om*/
        public void onClick(DialogInterface dialog, int which) {

            switch (which) {
            case 0: {

                AlertDialog.Builder build = new AlertDialog.Builder(MerchantEdit.this);
                LayoutInflater factory = LayoutInflater.from(MerchantEdit.this);
                final View textEntryView = factory.inflate(R.layout.show_view, null);
                build.setView(textEntryView);
                final ImageView view = (ImageView) textEntryView.findViewById(R.id.imag);
                //               ImageCacheUtil.IMAGE_CACHE.get(uri, view);
                ImageLoader.getInstance().displayImage(uri, view, options);
                build.create().show();
                break;
            }

            case 1: {

                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                } else {
                    intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                startActivityForResult(intent, REQUEST_UPLOAD_IMAGE);
                break;
            }
            case 2: {
                String state = Environment.getExternalStorageState();
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                    if (!outDir.exists()) {
                        outDir.mkdirs();
                    }
                    File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
                    photoPath = outFile.getAbsolutePath();
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                    startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                } else {
                    CommonUtil.toastShort(MerchantEdit.this, getString(R.string.toast_no_sdcard));
                }
                break;
            }
            }
        }
    });

    builder.show();
}

From source file:no.barentswatch.fiskinfo.MapActivity.java

private void runScheduledAlarm() {
    new FiskinfoScheduledTaskExecutor(2).scheduleAtFixedRate(new Runnable() {

        @Override/*from   w  ww.j a v  a2s  .com*/
        public void run() {
            // Need to get alarm status and handle kill
            if (!cacheDeserialized) {
                if (checkCacheWriterStatus()) {
                    String directoryPath = Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
                    String directoryName = "FiskInfo";
                    String filename = "cachedResults";
                    String filePath = directoryPath + "/" + directoryName + "/" + filename;
                    tools = new FiskInfoUtility().deserializeFiskInfoPolygon2D(filePath);
                    cacheDeserialized = true;
                    // DEMO: HER LEGGER VI INN PUNKTENE SOM VI SKAL SKREMME
                    // FOLK MED!
                    // Point point = new Point(69.650543, 18.956831);
                    // tools.addPoint(point);
                }
            } else {
                if (alarmFiring) {
                    System.out.println("SHieeeeet");
                    notifyUserOfProximityAlert();
                } else {
                    double latitude, longitude = 0;
                    if (mGpsLocationTracker.canGetLocation()) {
                        latitude = mGpsLocationTracker.getLatitude();
                        cachedLat = latitude;
                        longitude = mGpsLocationTracker.getLongitude();
                        cachedLon = longitude;
                        System.out.println("Lat; " + latitude + "lon: " + longitude);
                        Log.i("GPS-LocationTracker", String.format("latitude: %s", latitude));
                        Log.i("GPS-LocationTracker", String.format("longitude: %s", longitude));
                    } else {
                        mGpsLocationTracker.showSettingsAlert();
                        return;
                    }
                    Point userPosition = new Point(cachedLat, cachedLon);
                    if (!tools.checkCollsionWithPoint(userPosition, Double.parseDouble(cachedDistance))) {
                        System.out.println("We no crash");
                        return;
                    }
                    // shieeeet
                    alarmFiring = true;
                }
            }

            System.out.println("BEEP");
        }

    }, 5, 20, TimeUnit.SECONDS); // <num1> is initial delay,<num2> is the subsequent delay between each call
}

From source file:com.kevin.cattalk.ui.SettingsFragment.java

void sendLogThroughMail() {
    String logPath = "";
    try {/*from   w  w  w  . jav  a  2 s  .  c o  m*/
        logPath = EMClient.getInstance().compressLogs();
    } catch (Exception e) {
        e.printStackTrace();
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getActivity(), "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();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}

From source file:com.raspi.chatapp.ui.chatting.ChatActivity.java

/**
 * will start the asyncTask to download the update
 *
 * @param version the version to download
 *//*from  w  w  w .  j  a v  a 2s.c  om*/
private void downloadUpdate(String version) {
    MyFileUtils mfu = new MyFileUtils();
    // if we have access to the external storage
    if (mfu.isExternalStorageWritable()) {
        // get the default download location and execute the asyncTask
        UpdateAppAsyncTask asyncTask = new UpdateAppAsyncTask();
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                version + ".apk");
        asyncTask.execute(new String[] { version + ".apk", file.getAbsolutePath() });
    } else {
        new AlertDialog.Builder(ChatActivity.this).setTitle(R.string.download_failed)
                .setNegativeButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }
}

From source file:jp.mau.twappremover.MainActivity.java

@SuppressLint("NewApi")
private void writeOut(String str) {
    FileOutputStream fos = null;/* ww w  .j  av  a 2  s .  c o  m*/
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
            "test.txt");
    try {
        fos = new FileOutputStream(file);
        fos.write(str.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (Exception e) {
                ;
            }
    }
}

From source file:com.andfchat.frontend.activities.ChatScreen.java

public void exportChat() {
    int permissionCheck = ContextCompat.checkSelfPermission(context,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (ContextCompat.checkSelfPermission(context,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    } else {/*ww w. j  a va 2s .c om*/
        String filename = "FListLog-" + chatroomManager.getActiveChat().getName() + "-"
                + System.currentTimeMillis() + ".txt";
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File file = new File(path, filename);

        try {
            path.mkdirs();

            OutputStream os = new FileOutputStream(file);
            os.write(Exporter.exportText(this, chatroomManager.getActiveChat()));
            os.close();

            ChatEntry entry = entryFactory.getNotation(charManager.findCharacter(CharacterManager.USER_SYSTEM),
                    R.string.exported, new Object[] { filename });
            chatroomManager.addMessage(chatroomManager.getActiveChat(), entry);

            // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, Uri uri) {

                        }
                    });
        } catch (IOException e) {
            Ln.w("ExternalStorage", "Error writing " + file, e);
            ChatEntry entry = entryFactory.getError(charManager.findCharacter(CharacterManager.USER_SYSTEM),
                    R.string.export_failed);
            chatroomManager.addMessage(chatroomManager.getActiveChat(), entry);
        }
    }

}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void createProximityAlertSetupDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_proximity_alert_create,
            R.string.create_proximity_alert);

    Button setProximityAlertWatcherButton = (Button) dialog
            .findViewById(R.id.create_proximity_alert_create_alert_watcher_button);
    Button stopCurrentProximityAlertWatcherButton = (Button) dialog
            .findViewById(R.id.create_proximity_alert_stop_existing_alert_button);
    Button cancelButton = (Button) dialog.findViewById(R.id.create_proximity_alert_cancel_button);
    SeekBar seekbar = (SeekBar) dialog.findViewById(R.id.create_proximity_alert_seekBar);
    final EditText radiusEditText = (EditText) dialog.findViewById(R.id.create_proximity_alert_range_edit_text);
    final Switch formatSwitch = (Switch) dialog.findViewById(R.id.create_proximity_alert_format_switch);

    final double seekBarStepSize = (double) (getResources()
            .getInteger(R.integer.proximity_alert_maximum_warning_range_meters)
            - getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)) / 100;

    radiusEditText.setText(/*from   www.  ja  va2s. c o  m*/
            String.valueOf(getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)));

    formatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                buttonView.setText(getString(R.string.range_format_nautical_miles));
            } else {
                buttonView.setText(getString(R.string.range_format_meters));
            }
        }
    });

    seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                String range = String.valueOf(
                        (int) (getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)
                                + (seekBarStepSize * progress)));
                radiusEditText.setText(range);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    setProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String toastText;

            if (proximityAlertWatcher == null) {
                toastText = getString(R.string.proximity_alert_set);
            } else {

                toastText = getString(R.string.proximity_alert_replace);
            }

            if (proximityAlertWatcher != null) {
                proximityAlertWatcher.cancel(true);
            }

            mGpsLocationTracker = new GpsLocationTracker(getActivity());
            double latitude, longitude;

            if (mGpsLocationTracker.canGetLocation()) {
                latitude = mGpsLocationTracker.getLatitude();
                cachedLat = latitude;
                longitude = mGpsLocationTracker.getLongitude();
                cachedLon = longitude;
            } else {
                mGpsLocationTracker.showSettingsAlert();
                return;
            }

            if (formatSwitch.isChecked()) {
                cachedDistance = Double.valueOf(radiusEditText.getText().toString())
                        * getResources().getInteger(R.integer.meters_per_nautical_mile);
            } else {
                cachedDistance = Double.valueOf(radiusEditText.getText().toString());
            }

            dialog.dismiss();

            Response response;

            try {
                String apiName = "fishingfacility";
                String format = "OLEX";
                String filePath;
                String fileName = "collisionCheckToolsFile";

                response = barentswatchApi.getApi().geoDataDownload(apiName, format);

                if (response == null) {
                    Log.d(TAG, "RESPONSE == NULL");
                    throw new InternalError();
                }

                if (fiskInfoUtility.isExternalStorageWritable()) {
                    String directoryPath = Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
                    String directoryName = "FiskInfo";
                    filePath = directoryPath + "/" + directoryName + "/";
                    InputStream zippedInputStream = null;

                    try {
                        TypedInput responseInput = response.getBody();
                        zippedInputStream = responseInput.in();
                        zippedInputStream = new GZIPInputStream(zippedInputStream);

                        InputSource inputSource = new InputSource(zippedInputStream);
                        InputStream input = new BufferedInputStream(inputSource.getByteStream());
                        byte data[];
                        data = FiskInfoUtility.toByteArray(input);

                        InputStream inputStream = new ByteArrayInputStream(data);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        FiskInfoPolygon2D serializablePolygon2D = new FiskInfoPolygon2D();

                        String line;
                        boolean startSet = false;
                        String[] convertedLine;
                        List<Point> shape = new ArrayList<>();
                        while ((line = reader.readLine()) != null) {
                            Point currPoint = new Point();
                            if (line.length() == 0 || line.equals("")) {
                                continue;
                            }
                            if (Character.isLetter(line.charAt(0))) {
                                continue;
                            }

                            convertedLine = line.split("\\s+");

                            if (line.length() > 150) {
                                Log.d(TAG, "line " + line);
                            }

                            if (convertedLine[0].startsWith("3sl")) {
                                continue;
                            }

                            if (convertedLine[3].equalsIgnoreCase("Garnstart") && startSet) {
                                if (shape.size() == 1) {
                                    // Point

                                    serializablePolygon2D.addPoint(shape.get(0));
                                    shape = new ArrayList<>();
                                } else if (shape.size() == 2) {

                                    // line
                                    serializablePolygon2D.addLine(new Line(shape.get(0), shape.get(1)));
                                    shape = new ArrayList<>();
                                } else {

                                    serializablePolygon2D.addPolygon(new Polygon(shape));
                                    shape = new ArrayList<>();
                                }
                                startSet = false;
                            }

                            if (convertedLine[3].equalsIgnoreCase("Garnstart") && !startSet) {
                                double lat = Double.parseDouble(convertedLine[0]) / 60;
                                double lon = Double.parseDouble(convertedLine[1]) / 60;
                                currPoint.setNewPointValues(lat, lon);
                                shape.add(currPoint);
                                startSet = true;
                            } else if (convertedLine[3].equalsIgnoreCase("Brunsirkel")) {
                                double lat = Double.parseDouble(convertedLine[0]) / 60;
                                double lon = Double.parseDouble(convertedLine[1]) / 60;
                                currPoint.setNewPointValues(lat, lon);
                                shape.add(currPoint);
                            }
                        }

                        reader.close();
                        new FiskInfoUtility().serializeFiskInfoPolygon2D(filePath + fileName + "." + format,
                                serializablePolygon2D);

                        tools = serializablePolygon2D;

                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ArrayIndexOutOfBoundsException e) {
                        Log.e(TAG, "Error when trying to serialize file.");
                        Toast error = Toast.makeText(getActivity(), "Ingen redskaper i omrdet du definerte",
                                Toast.LENGTH_LONG);
                        e.printStackTrace();
                        error.show();
                        return;
                    } finally {
                        try {
                            if (zippedInputStream != null) {
                                zippedInputStream.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Toast.makeText(v.getContext(), R.string.download_failed, Toast.LENGTH_LONG).show();
                    dialog.dismiss();
                    return;
                }

            } catch (Exception e) {
                Log.d(TAG, "Could not download tools file");
                Toast.makeText(getActivity(), R.string.download_failed, Toast.LENGTH_LONG).show();
            }

            runScheduledAlarm(getResources().getInteger(R.integer.zero),
                    getResources().getInteger(R.integer.proximity_alert_interval_time_seconds));

            Toast.makeText(getActivity(), toastText, Toast.LENGTH_LONG).show();
        }
    });

    if (proximityAlertWatcher != null) {
        TypedValue outValue = new TypedValue();
        stopCurrentProximityAlertWatcherButton.setVisibility(View.VISIBLE);

        getResources().getValue(R.dimen.proximity_alert_dialog_button_text_size_small, outValue, true);
        float textSize = outValue.getFloat();

        setProximityAlertWatcherButton.setTextSize(textSize);
        stopCurrentProximityAlertWatcherButton.setTextSize(textSize);
        cancelButton.setTextSize(textSize);

        stopCurrentProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                proximityAlertWatcher.cancel(true);
                proximityAlertWatcher = null;
                dialog.dismiss();
            }
        });
    }

    cancelButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));

    dialog.show();
}