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:it.telecomitalia.my.base_struct_apps.VersionUpdate.java

@Override
protected Void doInBackground(String... urls) {
    /* metodo principale per aggiornamento */
    String xml = "";
    try {/*ww  w . ja v a 2s. co  m*/
        /* tento di leggermi il file XML remoto */
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(SERVER + PATH + VERSIONFILE);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);
        /* ora in xml c' il codice della pagina degli aggiornamenti */
    } catch (IOException e) {
        e.printStackTrace();
    }
    // TODO: org.apache.http.conn.HttpHostConnectException ovvero host non raggiungibile
    try {
        /* nella variabile xml, c' il codice della pagina remota per gli aggiornamenti.
        * Per le mie esigenze, prendo dall'xml l'attributo value per vedere a che versione  la
        * applicazione sul server.*/
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        // http://stackoverflow.com/questions/1706493/java-net-malformedurlexception-no-protocol
        InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
        Document dom = db.parse(is);
        Element element = dom.getDocumentElement();
        Element current = (Element) element.getElementsByTagName("current").item(0);
        currentVersion = current.getAttribute("value");
        currentApkName = current.getAttribute("apk");
    } catch (Exception e) {
        e.printStackTrace();
    }
    /* con il costruttore ho stabilito quale versione sta girando sul terminale, e con questi
    * due try, mi son letto XML remoto e preso la versione disponibile sul server e il relativo
    * nome dell'apk, caso ai dovesse servirmi. Ora li confronto e decido che fare */
    if (currentVersion != null & runningVersion != null) {
        /* esistono, li trasformo in double */
        Double serverVersion = Double.parseDouble(currentVersion);
        Double localVersion = Double.parseDouble(runningVersion);
        /* La versione server  superiore alla mia ! Occorre aggiornare */
        if (serverVersion > localVersion) {
            try {
                /* connessione al server */
                URL urlAPK = new URL(SERVER + PATH + currentApkName);
                HttpURLConnection con = (HttpURLConnection) urlAPK.openConnection();
                con.setRequestMethod("GET");
                con.setDoOutput(true);
                con.connect();
                // qual' la tua directory di sistema Download ?
                File downloadPath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                File outputFile = new File(downloadPath, currentApkName);
                //Log.i("test", downloadPath.getAbsolutePath());
                //Log.i("test", outputFile.getAbsolutePath());
                // se esistono download parziali o vecchi, li elimino.
                if (outputFile.exists())
                    outputFile.delete();
                /* mi creo due File Stream uno di input, quello che sto scaricando dal server,
                * e l'altro di output, quello che sto creando nella directory Download*/
                InputStream input = con.getInputStream();
                FileOutputStream output = new FileOutputStream(outputFile);
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = input.read(buffer)) != -1) {
                    output.write(buffer, 0, count);
                }
                output.close();
                input.close();
                /* una volta terminato il processo, attraverso un intent lancio il file che ho
                * appena scaricato in modo da installare immediatamente l'aggiornamento come
                * specificato qui
                * http://stackoverflow.com/questions/4967669/android-install-apk-programmatically*/
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(new File(outputFile.getAbsolutePath())),
                        "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:ar.com.lapotoca.resiliencia.gallery.ui.ImageDetailActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.image_menu, menu);
    MenuItem shareItem = menu.findItem(R.id.menu_share);
    shareItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override/*from  w w  w.j a v  a  2s  .c o  m*/
        public boolean onMenuItemClick(MenuItem item) {
            try {

                ImageHolder img = Images.image[mPager.getCurrentItem()];
                if (img == null) {
                    return false;
                }

                AnalyticsHelper.getInstance().sendImageShareEvent(img.getUrl());

                Uri bmpUri;
                if (img.isLocal()) {
                    bmpUri = Uri.parse("content://" + AssetProvider.CONTENT_URI + "/" + img.getUrl());
                } else {
                    ImageView iv = (ImageView) findViewById(R.id.picImageView);
                    bmpUri = getLocalBitmapUri(iv);
                }
                if (bmpUri != null) {
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                    shareIntent.setType("image/*");
                    startActivity(Intent.createChooser(shareIntent, getString(R.string.share_item)));

                    AnalyticsHelper.getInstance().sendImageShareCompleted();
                    return true;
                } else {

                    AnalyticsHelper.getInstance().sendImageShareCanceled();
                    return false;
                }
            } catch (Exception e) {
                AnalyticsHelper.getInstance().sendImageShareFailed(e.getMessage());
                return false;
            }
        }
    });

    MenuItem downloadItem = menu.findItem(R.id.download_asset);
    downloadItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {

            Context context = ImageDetailActivity.this;

            String appDirectoryName = context.getString(R.string.app_name);
            File imageRoot = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    appDirectoryName);

            ImageHolder img = Images.image[mPager.getCurrentItem()];
            if (img == null) {
                return false;
            }

            AssetManager assetManager = context.getAssets();
            try {
                InputStream is = assetManager.open(img.getUrl());
                String fileName = img.getUrl().split("/")[1];

                imageRoot.mkdirs();
                File image = new File(imageRoot, fileName);

                byte[] buffer = new byte[BUFFER_LENGHT];
                FileOutputStream fos = new FileOutputStream(image);
                int read = 0;

                while ((read = is.read(buffer, 0, 1024)) >= 0) {
                    fos.write(buffer, 0, read);
                }

                fos.flush();
                fos.close();
                is.close();

                String[] paths = { image.getAbsolutePath() };

                MediaScannerConnection.scanFile(context, paths, null, null);
                NotificationHelper.showNotification(context,
                        context.getString(R.string.download_image_succesfull));
                AnalyticsHelper.getInstance().sendDownloadImage(fileName);

            } catch (Exception e) {
                NotificationHelper.showNotification(context,
                        context.getString(R.string.download_no_permissions));
                AnalyticsHelper.getInstance().sendImageDownloadFailed(e.getMessage());
            }

            return true;
        }
    });

    return true;
}

From source file:com.microsoft.assetmanagement.DisplayCarActivity.java

/**
 * Creates the image file.//  w ww  .ja va  2 s. co  m
 *
 * @return the file
 * @throws IOException Signals that an I/O exception has occurred.
 */
@SuppressLint("SimpleDateFormat")
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(imageFileName, /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

From source file:com.example.linhdq.test.documents.creation.NewDocumentActivity.java

protected void startCamera() {
    try {//from www.  ja v a  2  s . c om
        cameraPicUri = null;
        dateCameraIntentStarted = new Date();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";

        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image;
        try {
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }
            image = new File(storageDir, imageFileName + ".jpg");
            if (image.exists()) {
                image.createNewFile();
            }
            cameraPicUri = Uri.fromFile(image);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPicUri);
            startActivityForResult(intent, REQUEST_CODE_MAKE_PHOTO);
        } catch (IOException e) {
            showFileError(PixLoadStatus.IO_ERROR);
        }

    } catch (ActivityNotFoundException e) {
        showFileError(PixLoadStatus.CAMERA_APP_NOT_FOUND);
    }
}

From source file:model.Document.java

/**
 * @return the validity in memory of this Document. A document is valid in
 *         memory during a week/*  w  w w  .  j  a  v  a  2s.c  om*/
 */
public boolean isOnMemory() {
    if (mLoadedDate.plusWeeks(1).isAfterNow()) {
        // Exits the function if the storage is not writable!
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Log.d("ClaroClient", "Missing SDCard");
            return false;
        }

        File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        File file = new File(root.getAbsolutePath(), getTitle() + "." + getExtension());
        return file.exists() && file.canRead();
    }
    return false;
}

From source file:jp.co.cyberagent.android.gpuimage.sample.activity.ActivityCamera.java

License:asdf

private static File getOutputMediaFile(final int type) {
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }//www. ja  v  a  2  s . c om
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}

From source file:com.tomi.ginatask.MainActivity.java

/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");

    //debug/*from   w  w  w. ja v a  2  s  . c  om*/
    Log.i("Directory name: ",
            (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)).getPath());

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}

From source file:ch.dbrgn.android.simplerepost.activities.RepostActivity.java

/**
 * Save the specified bitmap to the external storage. The
 * fileIdentifier parameter should be unique among all instagram
 * posts. If the file can be written, a File object pointing
 * to it will be returned./*from  w  ww . ja  va 2 s .c om*/
 */
private File saveToExternalStorage(String fileIdentifier, Bitmap bitmap) {
    // Check whether external storage is writeable
    final String externalStorageState = Environment.getExternalStorageState();
    boolean isWritable = externalStorageState.equals(Environment.MEDIA_MOUNTED);
    if (!isWritable) {
        ToastHelper.showShortToast(this, "External storage is not writeable.");
        return null;
    }

    // Create directory
    final File pubDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    final File directory = new File(pubDirectory, Config.PICTURES_DIRECTORY_NAME);
    if (!directory.exists()) {
        if (!directory.mkdirs()) {
            ToastHelper.showShortToast(this, "Could not create storage directory.");
            return null;
        }
    }

    // Write file
    final File file = new File(directory, fileIdentifier + ".png");
    if (file.exists()) {
        Log.w(LOG_TAG, "File " + file.toString() + " already exists");
        // This can only happen if the file has been reposted before.
        // In that case, overwrite.
        if (!file.delete()) {
            Log.e(LOG_TAG, "File " + file.toString() + " could not be deleted.");
            ToastHelper.showGenericErrorToast(this);
        } else {
            Log.i(LOG_TAG, "Deleted file " + file);
        }
    }
    try {
        FileOutputStream os = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, os);
        os.flush();
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
        ToastHelper.showGenericErrorToast(this);
    }

    return file;
}

From source file:java_lang_programming.com.android_media_demo.ImageSelectionCropDemo.java

/**
 * ???//from   w  ww. ja  v  a  2 s  .c o m
 *
 * @return
 */
private File getExternalStorageTempStoreFilePath() {
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File file = new File(path, "selected_temp_image.jpg");
    return file;
}

From source file:com.ruesga.rview.misc.ActivityHelper.java

@SuppressWarnings("ResultOfMethodCallIgnored")
public static void downloadUri(Context context, Uri uri, String fileName, @Nullable String mimeType) {
    // Create the destination location
    File destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    destination.mkdirs();//from   w  w w .j a v a  2s  . c  om
    Uri destinationUri = Uri.fromFile(new File(destination, fileName));

    // Use the download manager to perform the download
    DownloadManager downloadManager = (DownloadManager) context.getSystemService(Activity.DOWNLOAD_SERVICE);
    Request request = new Request(uri).setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationUri(destinationUri);
    if (mimeType != null) {
        request.setMimeType(mimeType);
    }
    request.allowScanningByMediaScanner();
    downloadManager.enqueue(request);
}