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.httrack.android.HTTrackActivity.java

private File getExternalStorage() {
    final String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        if (android.os.Build.VERSION.SDK_INT >= VERSION_CODES.FROYO) {
            return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        } else {//from w  ww  .j  a v  a 2s  .c  o m
            return Environment.getExternalStorageDirectory();
        }
    } else {
        // Fallback.
        return getFilesDir();
    }
}

From source file:com.nordicsemi.nrfUARTspoon.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//www .ja  v  a  2s . co  m
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBtAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    messageListView = (ListView) findViewById(R.id.listMessage);
    listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail);
    messageListView.setAdapter(listAdapter);
    messageListView.setDivider(null);
    btnConnectDisconnect = (Button) findViewById(R.id.btn_select);
    btnSend = (Button) findViewById(R.id.sendButton);
    btnStartNewFile = (Button) findViewById(R.id.btn_start_new_file);
    edtMessage = (EditText) findViewById(R.id.sendText);
    fileMessage = (TextView) findViewById(R.id.fileStatusText);
    formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");
    buttonGo = (Button) findViewById(R.id.btnGO);

    service_init();

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

    // state of spoon buttons
    stateButtons = new Button[6];
    stateButtons[0] = (Button) this.findViewById(R.id.state0_button);
    stateButtons[1] = (Button) this.findViewById(R.id.state1_button);
    stateButtons[2] = (Button) this.findViewById(R.id.state2_button);
    stateButtons[3] = (Button) this.findViewById(R.id.state3_button);
    stateButtons[4] = (Button) this.findViewById(R.id.state4_button);
    stateButtons[5] = (Button) this.findViewById(R.id.state5_button);
    stateButtons[5].setEnabled(false);
    buttonState = 5;

    final CheckBox expert = (CheckBox) findViewById(R.id.ckBoxExpertMode);
    final ListView listViewData = (ListView) findViewById(R.id.listMessage);

    buttonGo.setVisibility(View.INVISIBLE);
    listViewData.setVisibility(ListView.INVISIBLE);

    //Expert Mode Option
    findViewById(R.id.ckBoxExpertMode).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (expert.isChecked()) {
                listViewData.setVisibility(ListView.VISIBLE);
            } else {
                listViewData.setVisibility(ListView.INVISIBLE);
            }
        }

    });
    // Handler Disconnect & Connect button
    btnConnectDisconnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //initialize stable sample
            buttonGo.setVisibility(View.INVISIBLE);
            MainActivity.stable_counter = 0;

            if (!mBtAdapter.isEnabled()) {
                Log.i(TAG, "onClick - BT not enabled yet");
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            } else {
                if (btnConnectDisconnect.getText().equals("Connect")) {

                    //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices

                    Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                    startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
                } else {
                    //Disconnect button pressed
                    if (mDevice != null) {
                        mService.disconnect();

                    }
                }
            }
        }
    });
    // Handler Send button  
    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText editText = (EditText) findViewById(R.id.sendText);
            String message = editText.getText().toString();
            byte[] value;
            try {
                //send data to service
                value = message.getBytes("UTF-8");
                mService.writeRXCharacteristic(value);
                //Update the log with time stamp
                String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                listAdapter.add("[" + currentDateTimeString + "] TX: " + message);
                messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                edtMessage.setText("");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
    // Handler File button  
    btnStartNewFile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Close an open file
            if (isFileOpen) {
                btnStartNewFile.setText("Start new file");
                fileMessage.setText("File closed");
                try {
                    Log.i(TAG, "Closing old file");
                    isFileOpen = false;
                    theWriter.flush();
                    theWriter.close();
                    theWriter = null;
                } catch (IOException ioe) {
                    Log.e(TAG, "Could not close previous file");
                }
            } else {
                // Open a new file               
                btnStartNewFile.setText("End file");

                String currentDateTimeStringFile = formatter.format(new Date());
                currentDateTimeStringFile += ".txt";
                File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
                path.mkdirs();
                File theFile = new File(path, currentDateTimeStringFile);
                try {
                    theWriter = new BufferedWriter(new FileWriter(theFile));
                } catch (IOException ioe) {
                    Log.e(TAG, "Buffered writer not created at" + theFile.getPath());
                    return;

                }
                fileMessage.setText("Writing to " + theFile.getPath());
                isFileOpen = true;
                fileTime = 0;
            }
        }
    });

    // Set initial UI state

}

From source file:link.kjr.file_manager.MainActivity.java

public void clickDownloads(View view) {
    String path = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))
            .getAbsolutePath();/* www.j  a v a 2 s  .  c o m*/
    setDirectoryView(path);
    Log.i(BuildConfig.APPLICATION_ID, " set to Download");
}

From source file:link.kjr.file_manager.MainActivity.java

public void clickPictures(View view) {
    String path = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))
            .getAbsolutePath();/*from w  w  w  . j  a v  a 2s .c om*/
    setDirectoryView(path);
    Log.i(BuildConfig.APPLICATION_ID, " set to Pictures");
}

From source file:com.bloc.blocparty.TimelineFragment.java

/** Create a File for saving an image or video */
private File getOutputMediaFile(int type) {
    // To be safe, you should check that the SDCard is mounted

    if (Environment.getExternalStorageState() != null) {
        // this works for Android 2.2 and above
        File mediaStorageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "AndroidCameraTestsFolder");

        // 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()) {
                return null;
            }//from  w w  w.  ja va  2s  .c  o  m
        }

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

        return mediaFile;
    }
    return null;
}

From source file:com.vuze.android.remote.service.VuzeService.java

@Override
public void onCreate() {
    super.onCreate();
    if (CorePrefs.DEBUG_CORE) {
        Log.d(TAG, "VuzeService: onCreate");
    }//  w  w  w  . j  a va2 s.c  o m

    instance = this;
    if (BuildConfig.DEBUG) {
        //android.os.Debug.waitForDebugger();
    }

    if (!AndroidUtils.hasPermisssion(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // TODO: implement check
        Log.d(TAG, "onCreate: No WRITE_EXTERNAL_STORAGE permission");
    }

    // requires WRITE_EXTERNAL_STORAGE
    File storageRoot = Environment.getExternalStorageDirectory();

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
        File dirDoc = Environment.getExternalStoragePublicDirectory("Documents");
        File dirDl = Environment.getExternalStoragePublicDirectory("Download");
        File dirVideo = Environment.getExternalStoragePublicDirectory("Movies");
        File dirAudio = Environment.getExternalStoragePublicDirectory("Music");
        if (CorePrefs.DEBUG_CORE) {
            Log.d("VuzeService", "Doc=" + dirDoc + "\nDL=" + dirDl + "\nVideo=" + dirVideo + "\nAudio="
                    + dirAudio + "\nStorage=" + storageRoot);
        }

    }

    File vuzeDownloadDir = new File(new File(storageRoot, "Vuze"), "Downloads");
    File internalRoot = this.getApplicationContext().getFilesDir();
    vuzeCoreConfigRoot = new File(internalRoot, ".vuze");

    if (!vuzeCoreConfigRoot.exists() || !vuzeDownloadDir.exists()) {
        File vuzeCustomDir = new File(vuzeCoreConfigRoot, "custom");
        vuzeCustomDir.mkdirs();
        try {
            File configFile = new File(vuzeCustomDir, "VuzeRemote.config");
            FileWriter fileWriter = new FileWriter(configFile, false);
            fileWriter.write(
                    "Default\\ save\\ path=string:" + vuzeDownloadDir.getAbsolutePath().replace("\\", "\\\\"));
            fileWriter.close();
        } catch (IOException e) {
        }
        vuzeDownloadDir.mkdirs();
    }

    if (CorePrefs.DEBUG_CORE) {
        Log.d(TAG, "onCreate: config root=" + vuzeCoreConfigRoot + ";manager=" + vuzeManager);
    }

    if (vuzeManager == null) {

        // TODO: If non-cellular only:
        // - Check ConnectivityManager.getActiveNetworkInfo().getType
        // - if TYPE_MOBILE, bind to "lo" or "127.0.0.1" before core start
        // - if non TYPE_MOBILE, check what's in UP state (ex. eth0, wlan0).
        // Should not be rmnet
        // - if not rmnet, bind before core start
        // ALSO
        // on network change, do the above, restarting core (shut down and start
        // again) if bind needs to change
        // If any network (cellular or otherwise)
        // - Ensure binding is blank, restart core if needed

        NetworkState networkState = VuzeRemoteApp.getNetworkState();
        networkState.addListener(this); // triggers

        buildCustomFile();
        vuzeManager = new VuzeManager(vuzeCoreConfigRoot);
        staticCore = vuzeManager.getCore();

        if (!AndroidUtils.DEBUG) {
            System.setOut(new PrintStream(new OutputStream() {
                public void write(int b) {
                    //DO NOTHING
                }
            }));
        }

        SimpleTimer.addPeriodicEvent("Update Notification", 30000, new TimerEventPerformer() {
            @Override
            public void perform(TimerEvent event) {
                updateNotification();
            }
        });

        PairingManager pairingManager = PairingManagerFactory.getSingleton();
        if (pairingManager != null) {
            try {
                Field ui = pairingManager.getClass().getDeclaredField("ui");
                ui.setAccessible(true);
                ui.set(pairingManager, this);
            } catch (Throwable t) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.e(TAG, "onCreate: ", t);
                }
            }
        }
        if (CorePrefs.getPrefOnlyPluggedIn()) {
            boolean wasConnected = AndroidUtils.isPowerConnected(VuzeRemoteApp.getContext());
            boolean isConnected = AndroidUtils.isPowerConnected(VuzeRemoteApp.getContext());

            if (wasConnected != isConnected) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "state changed while starting up.. stop core and try again");
                }

                restartService();
                return;
            }
        }
        staticCore.addLifecycleListener(new AzureusCoreLifecycleAdapter() {

            @Override
            public void started(AzureusCore core) {
                // not called if listener is added after core is started!
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "started: core");
                }

                coreStarted = true;
                sendStuff(MSG_OUT_CORE_STARTED, null);

                updateNotification();

                core.getGlobalManager().addListener(new GlobalManagerListener() {

                    @Override
                    public void downloadManagerAdded(DownloadManager dm) {

                    }

                    @Override
                    public void downloadManagerRemoved(DownloadManager dm) {

                    }

                    @Override
                    public void destroyInitiated() {

                    }

                    @Override
                    public void destroyed() {

                    }

                    @Override
                    public void seedingStatusChanged(boolean seeding_only_mode,
                            boolean potentially_seeding_only_mode) {
                        VuzeService.this.seeding_only_mode = seeding_only_mode;
                        if (CorePrefs.DEBUG_CORE) {
                            Log.d(TAG, "seedingStatusChanged: " + seeding_only_mode);
                        }

                        if (seeding_only_mode) {
                            CorePrefs.releasePowerLock();
                        } else {
                            CorePrefs.adjustPowerLock();
                        }
                    }
                });
            }

            @Override
            public void componentCreated(AzureusCore core, AzureusCoreComponent component) {
                // GlobalManager is always called, even if already created
                if (component instanceof GlobalManager) {

                    String s = NetworkAdmin.getSingleton().getNetworkInterfacesAsString();
                    if (CorePrefs.DEBUG_CORE) {
                        Log.d(TAG, "started: " + s);
                    }

                }
                if (component instanceof PluginInterface) {
                    String pluginID = ((PluginInterface) component).getPluginID();
                    if (CorePrefs.DEBUG_CORE) {
                        Log.d(TAG, "plugin " + pluginID + " started");
                    }

                    if (pluginID.equals("xmwebui")) {
                        webUIStarted = true;
                        sendStuff(MSG_OUT_WEBUI_STARTED, null);
                        updateNotification();
                    }
                } else {
                    Log.d(TAG, "component " + component.getClass().getSimpleName() + " started");
                }
            }

            @Override
            public void stopped(AzureusCore core) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopped: core");
                }

                core.removeLifecycleListener(this);

                sendStuff(MSG_OUT_CORE_STOPPED, null);

                // This will never get called if there's a non-deamon thread
                // (measurement-1 from GA, also Binder_2, Binder_1).  Instead,
                // System.exit(0) is called, which kills the service.
                // The service is restarted (STICKY) by android & everything starts
                // up nicely.

                // in case we do get here, keep exit path consistent
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopped: core!");
                }

                NetworkState networkState = VuzeRemoteApp.getNetworkState();
                networkState.removeListener(VuzeService.this);

                // Delay exitVM otherwise Vuze core will error with:
                //Listener dispatch timeout: failed = com.vuze.android.remote
                // .service.VuzeService
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (CorePrefs.DEBUG_CORE) {
                            Log.d(TAG, "stopped: delayed exit vm");
                        }

                        SESecurityManager.exitVM(0);
                    }
                });
                thread.setDaemon(false);
                thread.start();
                //System.exit(0);
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopped: core!!");
                }

            }

            @Override
            public void stopping(AzureusCore core) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopping: core");
                }

                isCoreStopping = true;

                VuzeEasyTracker.getInstance().stop();
                sendStuff(MSG_OUT_CORE_STOPPING, null);
                CorePrefs.releasePowerLock();

                updateNotification();
            }
        });
    } else {
        if (CorePrefs.DEBUG_CORE) {
            Log.d(TAG, "onCreate: vuzeManager already created");
        }
    }
}

From source file:link.kjr.file_manager.MainActivity.java

public void clickDCIM(View view) {
    String path = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)).getAbsolutePath();
    setDirectoryView(path);
}

From source file:com.google.transporttracker.TrackerService.java

private void logStatusToStorage(Map<String, Object> transportStatus) {
    try {//from ww w. jav  a 2s.  c o m
        File path = new File(Environment.getExternalStoragePublicDirectory(""), "transport-tracker-log.txt");
        if (!path.exists()) {
            path.createNewFile();
        }
        FileWriter logFile = new FileWriter(path.getAbsolutePath(), true);
        logFile.append(transportStatus.toString() + "\n");
        logFile.close();
    } catch (Exception e) {
        Log.e(TAG, "Log file error", e);
    }
}

From source file:link.kjr.file_manager.MainActivity.java

public void clickMusic(View view) {
    String path = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC))
            .getAbsolutePath();/* w  w  w  . j  a va2 s  .  c om*/
    setDirectoryView(path);

}

From source file:info.shibafu528.gallerymultipicker.MultiPickerActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    int id = item.getItemId();
    if (id == android.R.id.home) {
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack();
        } else {/*w w w  . ja  va2s .  com*/
            setResult(RESULT_CANCELED);
            finish();
        }
    } else if (id == R.id.info_shibafu528_gallerymultipicker_action_decide) {
        accept(getSelectedUris());
    } else if (id == R.id.info_shibafu528_gallerymultipicker_action_gallery) {
        Intent intent = new Intent(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? Intent.ACTION_PICK
                : Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_GALLERY);
    } else if (id == R.id.info_shibafu528_gallerymultipicker_action_take_a_photo) {
        boolean existExternal = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (!existExternal) {
            Toast.makeText(this, R.string.info_shibafu528_gallerymultipicker_storage_error, Toast.LENGTH_SHORT)
                    .show();
            return true;
        } else {
            File extDestDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                    mCameraDestDir != null ? mCameraDestDir : "Camera");
            if (!extDestDir.exists()) {
                extDestDir.mkdirs();
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String fileName = sdf.format(new Date(System.currentTimeMillis()));
            File destFile = new File(extDestDir.getPath(), fileName + ".jpg");
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.TITLE, fileName);
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            values.put(MediaStore.Images.Media.DATA, destFile.getPath());
            mCameraTemp = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraTemp);
            startActivityForResult(intent, REQUEST_CAMERA);
        }
    }
    return true;
}