Java 类android.os.Environment 实例源码

项目:metacom-android    文件:ChatFragment.java   
@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case TAKE_PHOTO:
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(Environment.getExternalStorageDirectory() + TMP_METACOM_JPG);
            Uri uri = FileProvider.getUriForFile(getContext(), AUTHORITY_STRING, f);
            takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
            takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                startActivityForResult(takePictureIntent, PICK_IMAGE_FROM_CAMERA);
            }
            return true;
        case FILE_EXPLORER:
            Intent intent = new Intent();
            intent.setType("*/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, getString(R.string
                            .select_file)),
                    PICK_IMAGE_FROM_EXPLORER);
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}
项目:downloadmanager    文件:Helpers.java   
private static File getDestinationDirectory(Context context, int destination, boolean running)
        throws IOException {
    switch (destination) {
        case Downloads.Impl.DESTINATION_CACHE_PARTITION:
        case Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE:
        case Downloads.Impl.DESTINATION_CACHE_PARTITION_NOROAMING:
            if (running) {
                return context.getFilesDir();
            } else {
                return context.getCacheDir();
            }
        case Downloads.Impl.DESTINATION_EXTERNAL:
            final File target = new File(
                    Environment.getExternalStorageDirectory(), Environment.DIRECTORY_DOWNLOADS);
            if (!target.isDirectory() && target.mkdirs()) {
                throw new IOException("unable to create external downloads directory");
            }
            return target;

        default:
            throw new IllegalStateException("unexpected destination: " + destination);
    }
}
项目:siiMobilityAppKit    文件:FileUtils.java   
protected HashMap<String, String> getAvailableFileSystems(Activity activity) {
    Context context = activity.getApplicationContext();
    HashMap<String, String> availableFileSystems = new HashMap<String,String>();

    availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
    availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
    availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
    availableFileSystems.put("root", "/");
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      try {
        availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
        availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
        availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
      }
      catch(NullPointerException e) {
          LOG.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on");
      }
    }

    return availableFileSystems;
}
项目:humaniq-android    文件:Wallet.java   
public static Wallet generateWallet(Context context, ECKeyPair ecKeyPair,
                                    final String password)
        throws WalletNotGeneratedException
{
    try {
        final String address = Numeric.prependHexPrefix(Keys.getAddress(ecKeyPair));
        final File destDirectory = Environment.getExternalStorageDirectory().getAbsoluteFile();
        Log.d(TAG, Environment.getExternalStorageState());
        final String fileName = WalletUtils.generateWalletFile(password, ecKeyPair, destDirectory, false);
        final String destFilePath = destDirectory + "/" + fileName;

        return new Wallet(ecKeyPair, destFilePath, address);
    } catch (CipherException | IOException e)
    {
        e.printStackTrace();
        throw new WalletNotGeneratedException();
    }
}
项目:AndroidUtilCode-master    文件:SDCardUtils.java   
/**
 * 获取SD卡信息
 *
 * @return SDCardInfo
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public static String getSDCardInfo() {
    if (!isSDCardEnable()) return null;
    SDCardInfo sd = new SDCardInfo();
    sd.isExist = true;
    StatFs sf = new StatFs(Environment.getExternalStorageDirectory().getPath());
    sd.totalBlocks = sf.getBlockCountLong();
    sd.blockByteSize = sf.getBlockSizeLong();
    sd.availableBlocks = sf.getAvailableBlocksLong();
    sd.availableBytes = sf.getAvailableBytes();
    sd.freeBlocks = sf.getFreeBlocksLong();
    sd.freeBytes = sf.getFreeBytes();
    sd.totalBytes = sf.getTotalBytes();
    return sd.toString();
}
项目:Facebook-Video-Downloader    文件:HomeFragment.java   
public void downloadvideo(String pathvideo)
{
    if(pathvideo.contains(".mp4"))
    {
        File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"Facebook Videos");
        directory.mkdirs();
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(pathvideo));
        int Number=pref.getFileName();
        request.allowScanningByMediaScanner();
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        File root = new File(Environment.getExternalStorageDirectory() + File.separator+"Facebook Videos");
        Uri path = Uri.withAppendedPath(Uri.fromFile(root), "Video-"+Number+".mp4");
        request.setDestinationUri(path);
        DownloadManager dm = (DownloadManager)getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
        if(downloadlist.contains(pathvideo))
        {
            Toast.makeText(getActivity().getApplicationContext(),"The Video is Already Downloading",Toast.LENGTH_LONG).show();
        }
        else
        {
            downloadlist.add(pathvideo);
            dm.enqueue(request);
            Toast.makeText(getActivity().getApplicationContext(),"Downloading Video-"+Number+".mp4",Toast.LENGTH_LONG).show();
            Number++;
            pref.setFileName(Number);
        }

    }
}
项目:react-native-compress-image    文件:ImageCompressModule.java   
private void createCustomCompressedImageWithExceptions(String image, String directoryPath, int maxWidth, int maxHeight, int quality, final Callback successCb, final Callback failureCb) throws IOException {
    File imageFile = new ImageCompress(mContext)
                .setMaxWidth(maxWidth)
                .setMaxHeight(maxHeight)
                .setQuality(quality)
                .setCompressFormat(Bitmap.CompressFormat.JPEG)
                .setDestinationDirectoryPath(Environment.getExternalStorageDirectory().getPath())
                .compressToFile(new File(uriPath.getRealPathFromURI(Uri.parse(image))), directoryPath);

    if (imageFile != null) {
        WritableMap response = Arguments.createMap();
        response.putString("path", imageFile.getAbsolutePath());
        response.putString("uri", Uri.fromFile(imageFile).toString());
        response.putString("name", imageFile.getName());
        response.putDouble("size", imageFile.length());

        // Invoke success
        successCb.invoke(response);
    } else {
        failureCb.invoke("Error getting compressed image path");
    }
}
项目:cnBetaGeek    文件:MyTagHandler.java   
@Override
public void onClick(View widget) {
    // TODO Auto-generated method stub
    // ��ͼƬURLת��Ϊ����·�������Խ�ͼƬ���������ͼƬ�������дΪһ���������������

    String imageName = MD5.md5(url);
    String sdcardPath = Environment.getExternalStorageDirectory().toString(); // ��ȡSDCARD��·��
    //��ȡͼƬ��׺��
    String[] ss = url.split("\\.");
    String ext = ss[ss.length - 1];

    // ����ͼƬ���ֵĵ�ַ
    String savePath = sdcardPath + "/" + context.getPackageName() + "/" + imageName + "." + ext;

    File file = new File(savePath);
    if (file.exists()) {
        // �������¼�������һ���µ�activity��������ʾͼƬ
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "image/*");
        context.startActivity(intent);
    }
}
项目:Android-UtilCode    文件:SDCardUtils.java   
/**
 * 获取SD卡信息
 *
 * @return SDCardInfo
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public static String getSDCardInfo() {
    if (!isSDCardEnable()) return null;
    SDCardInfo sd = new SDCardInfo();
    sd.isExist = true;
    StatFs sf = new StatFs(Environment.getExternalStorageDirectory().getPath());
    sd.totalBlocks = sf.getBlockCountLong();
    sd.blockByteSize = sf.getBlockSizeLong();
    sd.availableBlocks = sf.getAvailableBlocksLong();
    sd.availableBytes = sf.getAvailableBytes();
    sd.freeBlocks = sf.getFreeBlocksLong();
    sd.freeBytes = sf.getFreeBytes();
    sd.totalBytes = sf.getTotalBytes();
    return sd.toString();
}
项目:editor-sql    文件:TmpFolderUtils.java   
public static void writeUserHelpLog(String key, String logInfo) {
    try {
        String cachePath = Environment.getExternalStorageDirectory().getPath() + File.separator + DOWNLOAD_FOLDER_NAME;
        File dir = new File(cachePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(cachePath, "logInfo.txt");
        if (!file.exists()) {
            file.createNewFile();
        }

        if (file.exists()) {
            FileWriter writer = new FileWriter(file, true);
            writer.write("\n\n" + key + "=" + logInfo + "\n\n");
            writer.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:TripBuyer    文件:UploadAirTicketActivity.java   
/**
     * 启动手机相册
     */
    private void fromGallery() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_NAME)));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            startActivityForResult(intent, GALLERY_KITKAT_REQUEST);
        } else {
            startActivityForResult(intent, GALLERY_REQUEST);
        }

//        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//        startActivityForResult(intent, 103);103
    }
项目:XPrivacy    文件:ActivityApp.java   
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    boolean accountsRestricted = PrivacyManager.getRestrictionEx(mAppInfo.getUid(), PrivacyManager.cAccounts, null).restricted;
    boolean appsRestricted = PrivacyManager.getRestrictionEx(mAppInfo.getUid(), PrivacyManager.cSystem, null).restricted;
    boolean contactsRestricted = PrivacyManager.getRestrictionEx(mAppInfo.getUid(), PrivacyManager.cContacts, null).restricted;

    menu.findItem(R.id.menu_accounts).setEnabled(accountsRestricted);
    menu.findItem(R.id.menu_applications).setEnabled(appsRestricted);
    menu.findItem(R.id.menu_contacts).setEnabled(contactsRestricted);

    boolean mounted = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    menu.findItem(R.id.menu_export).setEnabled(mounted);
    menu.findItem(R.id.menu_import).setEnabled(mounted);

    menu.findItem(R.id.menu_submit).setEnabled(Util.hasValidFingerPrint(this));

    menu.findItem(R.id.menu_dump).setVisible(Util.isDebuggable(this));

    return super.onPrepareOptionsMenu(menu);
}
项目:AssistantBySDK    文件:PcmPlayer.java   
public PcmPlayer(Context context, Handler handler) {
    this.mContext = context;
    this.audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, wBufferSize, AudioTrack.MODE_STREAM);
    this.handler = handler;
    audioTrack.setPlaybackPositionUpdateListener(this, handler);
    cacheDir = context.getExternalFilesDir(Environment.DIRECTORY_MUSIC);
}
项目:keemob    文件:FileUtils.java   
private JSONObject requestAllPaths() throws JSONException {
    Context context = cordova.getActivity();
    JSONObject ret = new JSONObject();
    ret.put("applicationDirectory", "file:///android_asset/");
    ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile()));
    ret.put("dataDirectory", toDirUrl(context.getFilesDir()));
    ret.put("cacheDirectory", toDirUrl(context.getCacheDir()));
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      try {
        ret.put("externalApplicationStorageDirectory", toDirUrl(context.getExternalFilesDir(null).getParentFile()));
        ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null)));
        ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir()));
        ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory()));
      }
      catch(NullPointerException e) {
        /* If external storage is unavailable, context.getExternal* returns null */
          LOG.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage");
      }
    }
    return ret;
}
项目:alerta-fraude    文件:DirectoryManager.java   
/**
 * Determine if a file or directory exists.
 * @param name              The name of the file to check.
 * @return                  T=exists, F=not found
 */
public static boolean testFileExists(String name) {
    boolean status;

    // If SD card exists
    if ((testSaveLocationExists()) && (!name.equals(""))) {
        File path = Environment.getExternalStorageDirectory();
        File newPath = constructFilePaths(path.toString(), name);
        status = newPath.exists();
    }
    // If no SD card
    else {
        status = false;
    }
    return status;
}
项目:siiMobilityAppKit    文件:DirectoryManager.java   
/**
 * Determine if SD card exists.
 *
 * @return              T=exists, F=not found
 */
public static boolean testSaveLocationExists() {
    String sDCardStatus = Environment.getExternalStorageState();
    boolean status;

    // If SD card is mounted
    if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
        status = true;
    }

    // If no SD card
    else {
        status = false;
    }
    return status;
}
项目:boohee_v5.6    文件:a.java   
public boolean c(String str, String str2) {
    if (!this.c) {
        return false;
    }
    try {
        d.a(Environment.getExternalStorageDirectory() + "/" + "Tencent/mta");
        File file = new File(Environment.getExternalStorageDirectory(), "Tencent/mta/.mid.txt");
        if (file != null) {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
            bufferedWriter.write(str + "," + str2);
            bufferedWriter.write("\n");
            bufferedWriter.close();
        }
        return true;
    } catch (Throwable th) {
        this.a.w(th);
        return false;
    }
}
项目:SWDemo    文件:WorkerThread.java   
private RtcEngine ensureRtcEngineReadyLock() {
    if (mRtcEngine == null) {
        String appId = mContext.getString(R.string.private_app_id);
        if (TextUtils.isEmpty(appId)) {
            throw new RuntimeException("NEED TO use your App ID, get your own ID at https://dashboard.agora.io/");
        }
        mRtcEngine = RtcEngine.create(mContext, appId, mEngineEventHandler.mRtcEventHandler);
        if (isLive) {
            mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);
        } else {
            mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_COMMUNICATION);
        }
        mRtcEngine.enableVideo();
        mRtcEngine.enableAudioVolumeIndication(200, 3); // 200 ms
        mRtcEngine.setLogFile(Environment.getExternalStorageDirectory()
                + File.separator + mContext.getPackageName() + "/log/agora-rtc.log");
    }
    return mRtcEngine;
}
项目:testloopmanager    文件:TestLoopsActivity.java   
private void runScenario(String packageName, int scenario) throws IOException {
  String filename = String.format("results%d.json", scenario > 0 ? scenario : 0);
  File f = new File(Environment.getExternalStorageDirectory(), filename);
  //noinspection ResultOfMethodCallIgnored
  f.createNewFile();
  String myPackageName = getPackageName();
  Uri fileUri = FileProvider.getUriForFile(this, myPackageName, f);

  Intent intent =
      new Intent("com.google.intent.action.TEST_LOOP")
          .setPackage(packageName)
          .setDataAndType(fileUri, "application/javascript")
          .setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  if (scenario >= 0) {
    intent.putExtra("scenario", scenario);
  }

  runningTestLoop = true;
  startActivityForResult(intent, TEST_LOOP_REQUEST_CODE);
}
项目:SuperHttp    文件:DiskCache.java   
private static File getDiskCacheDir(Context context, String dirName) {
    String cachePath;
    if ((Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            || !Environment.isExternalStorageRemovable())
            && context.getExternalCacheDir() != null) {
        cachePath = context.getExternalCacheDir().getPath();
    } else {
        cachePath = context.getCacheDir().getPath();
    }
    return new File(cachePath + File.separator + dirName);
}
项目:Godot-ShareImage    文件:ShareImage.java   
public void getAndroidExternalPath(final String fileName) {
    String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
    File dir = new File(dirPath);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dirPath, fileName);    
    showDebugToast("Returning path: " + file.toString());
    GodotLib.calldeferred(mInstanceId, "_on_path_returned", new Object[]{file.toString()});
}
项目:AndroidNetwork    文件:BaseUtils.java   
/**
 * 获取SD卡剩余空间的大小
 * 
 * @return long SD卡剩余空间的大小(单位:byte)
 */
public static long getSDSize()
{
    final String str = Environment.getExternalStorageDirectory().getPath();
    final StatFs localStatFs = new StatFs(str);
    final long blockSize = localStatFs.getBlockSize();
    return localStatFs.getAvailableBlocks() * blockSize;
}
项目:Android-DFU-App    文件:UARTActivity.java   
private void exportConfiguration() {
    // TODO this may not work if the SD card is not available. (Lenovo A806, email from 11.03.2015)
    final File folder = new File(Environment.getExternalStorageDirectory(), FileHelper.NORDIC_FOLDER);
    if (!folder.exists())
        folder.mkdir();
    final File serverFolder = new File(folder, FileHelper.UART_FOLDER);
    if (!serverFolder.exists())
        serverFolder.mkdir();

    final String fileName = mConfiguration.getName() + ".xml";
    final File file = new File(serverFolder, fileName);
    try {
        file.createNewFile();
        final FileOutputStream fos = new FileOutputStream(file);
        final OutputStreamWriter writer = new OutputStreamWriter(fos);
        writer.append(mDatabaseHelper.getConfiguration(mConfigurationSpinner.getSelectedItemId()));
        writer.close();

        // Notify user about the file
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "text/xml");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        final PendingIntent pendingIntent = PendingIntent.getActivity(this, 420, intent, 0);
        final Notification notification = new NotificationCompat.Builder(this).setContentIntent(pendingIntent).setContentTitle(fileName).setContentText(getText(R.string.uart_configuration_export_succeeded))
                .setAutoCancel(true).setShowWhen(true).setTicker(getText(R.string.uart_configuration_export_succeeded_ticker)).setSmallIcon(android.R.drawable.stat_notify_sdcard).build();
        final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        nm.notify(fileName, 823, notification);
    } catch (final Exception e) {
        Log.e(TAG, "Error while exporting configuration", e);
        Toast.makeText(this, R.string.uart_configuration_save_error, Toast.LENGTH_SHORT).show();
    }
}
项目:GitHub    文件:FolderChooserDialog.java   
@Override
public void onSelection(MaterialDialog materialDialog, View view, int i, CharSequence s) {
    if (canGoUp && i == 0) {
        parentFolder = parentFolder.getParentFile();
        if (parentFolder.getAbsolutePath().equals("/storage/emulated"))
            parentFolder = parentFolder.getParentFile();
        canGoUp = parentFolder.getParent() != null;
    } else {
        parentFolder = parentContents[canGoUp ? i - 1 : i];
        canGoUp = true;
        if (parentFolder.getAbsolutePath().equals("/storage/emulated"))
            parentFolder = Environment.getExternalStorageDirectory();
    }
    reload();
}
项目:AutoInteraction-Library    文件:SilenceLog.java   
private static void writeFile(String msg) {
    String sdStatus = Environment.getExternalStorageState();
    if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
        Log.d("TestFile", "SD card is not avaiable/writeable right now.");
        return;
    }
    try {
        String pathName = Environment.getExternalStorageDirectory().getPath() + "/ForeSightLog/";
        String fileName = "runningLog.txt";
        File path = new File(pathName);
        File file = new File(pathName + fileName);
        if (!path.exists()) {
            Log.d("runningLog", "Create the path:" + pathName);
            path.mkdir();
        }
        if (!file.exists()) {
            Log.d("runningLog", "Create the file:" + fileName);
            file.createNewFile();
        }
        FileOutputStream stream = new FileOutputStream(file, true);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINESE);
        String s = "[" + dateFormat.format(new Date()) + "][thread:" + Thread.currentThread().getId() + "][" +
                msg + "]\r\n";
        byte[] buf = s.getBytes();
        stream.write(buf);
        stream.close();

    } catch (Exception e) {
        Log.e("TestFile", "Error on writeFilToSD.");
        e.printStackTrace();
    }
}
项目:GodotAds    文件:Utils.java   
public static boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }

    return false;
}
项目:android-study    文件:Android7UI.java   
public void newCapture() {
  File file = new File(Environment.getExternalStorageDirectory(),
      "/temp/" + System.currentTimeMillis() + ".jpg");
  if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
  mImageUri = FileProvider.getUriForFile(getActivity(), "com.liuguoquan.module.ui.provider",
      file);//通过FileProvider创建一个content类型的Uri
  Log.d("lgq", mImageUri.toString());
  Intent intent = new Intent();
  intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
  intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
  intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将拍取的照片保存到指定URI
  startActivityForResult(intent, 1006);
}
项目:Phial    文件:FileProvider.java   
/**
 * Parse and return {@link PathStrategy} for given authority as defined in
 * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
 *
 * @see #getPathStrategy(Context, String)
 */
private static PathStrategy parsePathStrategy(Context context, String authority)
        throws IOException, XmlPullParserException {
    final SimplePathStrategy strat = new SimplePathStrategy(authority);

    final ProviderInfo info = context.getPackageManager()
            .resolveContentProvider(authority, PackageManager.GET_META_DATA);
    final XmlResourceParser in = info.loadXmlMetaData(
            context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
    if (in == null) {
        throw new IllegalArgumentException(
                "Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
    }

    int type;
    while ((type = in.next()) != END_DOCUMENT) {
        if (type == START_TAG) {
            final String tag = in.getName();

            final String name = in.getAttributeValue(null, ATTR_NAME);
            String path = in.getAttributeValue(null, ATTR_PATH);

            File target = null;
            if (TAG_ROOT_PATH.equals(tag)) {
                target = DEVICE_ROOT;
            } else if (TAG_FILES_PATH.equals(tag)) {
                target = context.getFilesDir();
            } else if (TAG_CACHE_PATH.equals(tag)) {
                target = context.getCacheDir();
            } else if (TAG_EXTERNAL.equals(tag)) {
                target = Environment.getExternalStorageDirectory();
            } else if (TAG_EXTERNAL_FILES.equals(tag)) {
                File[] externalFilesDirs = getExternalFilesDirs(context, null);
                if (externalFilesDirs.length > 0) {
                    target = externalFilesDirs[0];
                }
            } else if (TAG_EXTERNAL_CACHE.equals(tag)) {
                File[] externalCacheDirs = getExternalCacheDirs(context);
                if (externalCacheDirs.length > 0) {
                    target = externalCacheDirs[0];
                }
            }

            if (target != null) {
                strat.addRoot(name, buildPath(target, path));
            }
        }
    }

    return strat;
}
项目:Mire    文件:WallpaperHelper.java   
public static File getDefaultWallpapersDirectory(@NonNull Context context)
{
       try 
    {
           if (Preferences.getPreferences(context).getWallsDirectory().length() == 0) 
        {
               return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + context.getResources().getString(R.string.app_name));
           }
           return new File(Preferences.getPreferences(context).getWallsDirectory());
       } 
    catch (Exception e) 
    {
           return new File(context.getFilesDir().toString() + "/Pictures/"+ context.getResources().getString(R.string.app_name));
       }
   }
项目:VirtualAPK    文件:MainActivity.java   
private void loadPlugin(Context base) {
    PluginManager pluginManager = PluginManager.getInstance(base);
    File apk = new File(Environment.getExternalStorageDirectory(), "Test.apk");
    if (apk.exists()) {
        try {
            pluginManager.loadPlugin(apk);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
项目:ClouldReader    文件:QRCodeUtil.java   
private static String getFileRoot(Context context) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        File external = context.getExternalFilesDir(null);
        if (external != null) {
            return external.getAbsolutePath();
        }
    }

    return context.getFilesDir().getAbsolutePath();
}
项目:letv    文件:FileStoreImpl.java   
boolean isExternalStorageAvailable() {
    if ("mounted".equals(Environment.getExternalStorageState())) {
        return true;
    }
    Fabric.getLogger().w(Fabric.TAG, "External Storage is not mounted and/or writable\nHave you declared android.permission.WRITE_EXTERNAL_STORAGE in the manifest?");
    return false;
}
项目:Orin    文件:MusicUtil.java   
@NonNull
@SuppressWarnings("ResultOfMethodCallIgnored")
public static File createAlbumArtDir() {
    File albumArtDir = new File(Environment.getExternalStorageDirectory(), "/albumthumbs/");
    if (!albumArtDir.exists()) {
        albumArtDir.mkdirs();
        try {
            new File(albumArtDir, ".nomedia").createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return albumArtDir;
}
项目:AndroidBasicLibs    文件:MemoryUtil.java   
/**
 * Get internal memory size
 *
 * @return
 */
public static long getTotalInternalMemorySize() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long totalBlocks = stat.getBlockCount();
    return totalBlocks * blockSize;
}
项目:localcloud_fe    文件:LocalFilesystem.java   
private boolean isPublicDirectory(String absolutePath) {
    // TODO: should expose a way to scan app's private files (maybe via a flag).
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Lollipop has a bug where SD cards are null.
        for (File f : context.getExternalMediaDirs()) {
            if(f != null && absolutePath.startsWith(f.getAbsolutePath())) {
                return true;
            }
        }
    }

    String extPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    return absolutePath.startsWith(extPath);
}
项目:Ae4Team    文件:UserProfileActivity.java   
public void doTakePhotoAction() {
    int permissionCheck = ContextCompat.checkSelfPermission(UserProfileActivity.this, Manifest.permission.CAMERA);
    if (permissionCheck == PackageManager.PERMISSION_DENIED) {
        ActivityCompat.requestPermissions(UserProfileActivity.this, new String[]{Manifest.permission.CAMERA}, 0);
    } else {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String url = "profile.jpg";
        mlmageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), url));
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mlmageCaptureUri);
        startActivityForResult(intent, PICK_FROM_CAMERA);
        Log.i(TAG, "test1-camera");
    }
}
项目:BaseCore    文件:LogUtils.java   
/**
 * 初始化函数
 * <p>与{@link #getBuilder()}两者选其一</p>
 *
 * @param logSwitch      日志总开关
 * @param log2FileSwitch 日志写入文件开关
 * @param logFilter      输入日志类型有{@code v, d, i, w, e}<br>v代表输出所有信息,w则只输出警告...
 * @param tag            标签
 */
public static void init(boolean logSwitch, boolean log2FileSwitch, char logFilter, String tag) {
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        dir = Utils.getContext().getExternalCacheDir().getPath() + File.separator;
    } else {
        dir = Utils.getContext().getCacheDir().getPath() + File.separator;
    }
    LogUtils.logSwitch = logSwitch;
    LogUtils.log2FileSwitch = log2FileSwitch;
    LogUtils.logFilter = logFilter;
    LogUtils.tag = tag;
}
项目:foco    文件:EditDocCoverDialog.java   
/**
 * Open a file picker dialog to ease select a new image from external storage.
 */
public void openFilePickerDialog() {
    DialogProperties properties = new DialogProperties();

    properties.selection_mode = DialogConfigs.SINGLE_MODE;
    properties.selection_type = DialogConfigs.FILE_SELECT;
    // initial directory should be pictures directory
    properties.offset = new File("/mnt/sdcard" + File.separator + Environment.DIRECTORY_PICTURES);
    // show accepted image format only
    properties.extensions = new String[]{"jpg","jpeg","png","gif","bmp","webp"};

    FilePickerDialog dialog = new FilePickerDialog(getActivity(), properties);
    dialog.setTitle(R.string.dialog_edit_doc_cover_image_select_title);
    dialog.setPositiveBtnName(getString(R.string.dialog_edit_doc_cover_image_select_ok));
    dialog.setNegativeBtnName(getString(android.R.string.cancel));

    dialog.setDialogSelectionListener(new DialogSelectionListener() {
        @Override
        public void onSelectedFilePaths(String[] files) {
            if (files.length > 0) {
                mImagePath = files[0];
                updateImage();
            }
        }
    });

    dialog.show();

    // There is a problem with library dialog theme, it does not support a light
    // primary color because header text color is always white.
    // With this hack (we had to study library layout) it ensures that header background
    // is ok.
    dialog.findViewById(R.id.header).setBackgroundColor(
            ContextCompat.getColor(getActivity(), R.color.colorAccent));
}
项目:ArtOfAndroid    文件:ImageLoadUtil.java   
private File getDiskCacheDir(Context context, String uniqueName) {
    boolean externalStorageAvailable = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    String cachePath;
    if (externalStorageAvailable) {
        cachePath = context.getExternalCacheDir().getPath();
    } else {
        cachePath = context.getCacheDir().getPath();
    }
    return new File(cachePath + File.separator + uniqueName);
}
项目:ChenYan    文件:JoinedUserActivity.java   
private String getSDPath() {
    File sdDir = null;
    boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    if (sdCardExist) {
        sdDir = Environment.getExternalStorageDirectory();
    }
    String dir = sdDir.toString();
    return dir;
}