Java Code Examples for android.os.Environment

The following examples show how to use android.os.Environment. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: PhotoViewSlider   Source File: PhotosViewSlider.java    License: Apache License 2.0 6 votes vote down vote up
private void preparePhotoForShare() {
    final Bitmap[] image = new Bitmap[1];

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                image[0] = Picasso.with(getContext())
                        .load(photos.get(currentPosition).getImageUrl())
                        .get();

                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                image[0].compress(Bitmap.CompressFormat.JPEG, 100, bytes);

                File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image_temp.jpg");
                FileOutputStream fo = new FileOutputStream(file);
                fo.write(bytes.toByteArray());
                sendPhotoForShare();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}
 
Example 2
Source Project: ExamplesAndroid   Source File: Metodos.java    License: Apache License 2.0 6 votes vote down vote up
public void createDirectoryAndSaveFile(PdfWriter imageToSave, String fileName) throws FileNotFoundException {


        File direct = new File(Environment.getExternalStorageDirectory() + "/TutorialesHackro");

        if (!direct.exists()) {
            File wallpaperDirectory = new File("/sdcard/TutorialesHackro/");
            wallpaperDirectory.mkdirs();
        }

        File file = new File(new File("/sdcard/TutorialesHackro/"), fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);

            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("edwq",e.getMessage());
        }
    }
 
Example 3
Source Project: Roid-Library   Source File: StorageUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static File getExternalCacheDir(Context context) {
    File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
    File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
    if (!appCacheDir.exists()) {
        if (!appCacheDir.mkdirs()) {
            L.w("Unable to create external cache directory");
            return null;
        }
        try {
            new File(appCacheDir, ".nomedia").createNewFile();
        } catch (IOException e) {
            L.i("Can't create \".nomedia\" file in application external cache directory");
        }
    }
    return appCacheDir;
}
 
Example 4
Source Project: scallop   Source File: ImageViewerActivity.java    License: MIT License 6 votes vote down vote up
@OnClick(R.id.download_button)
public void downloadImage() {
    String imageUrl = imageUrlList.get(imageViewPager.getCurrentItem());
    String fileName = StringUtils.getImageNameFromUrl(imageUrl);
    String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            .getAbsolutePath() + "/scallop";
    DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imageUrl));
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
            | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false)
            .setTitle(fileName)
            .setNotificationVisibility(
                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalPublicDir(path, fileName);
    downloadManager.enqueue(request);
}
 
Example 5
Source Project: MiBandDecompiled   Source File: BraceletApp.java    License: Apache License 2.0 6 votes vote down vote up
public String getStoragePath()
{
    String s = Environment.getExternalStorageState();
    Debug.i("BraceletApp", (new StringBuilder()).append("ext state =").append(s).toString());
    File file;
    if ("mounted".equals(s))
    {
        file = getExternalFilesDir("Millelet");
    } else
    {
        file = getFilesDir();
    }
    if (file == null)
    {
        file = getFilesDir();
    }
    if (file == null)
    {
        return (new StringBuilder()).append(Environment.getExternalStorageDirectory().getPath()).append("/").append("Millelet").toString();
    } else
    {
        String s1 = file.getPath();
        Debug.i("BraceletApp", (new StringBuilder()).append("getStoragePath:").append(s1).toString());
        return s1;
    }
}
 
Example 6
Source Project: DanDanPlayForAndroid   Source File: PlayFragmentPresenterImpl.java    License: MIT License 6 votes vote down vote up
/**
 * 刷新视频文件
 *
 * @param reScan true: 重新扫描整个系统目录
 *               false: 只查询数据库数据
 */
@Override
public void refreshVideo(Context context, boolean reScan) {
    //通知系统刷新目录
    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
    if (context != null)
        context.sendBroadcast(intent);

    if (reScan) {
        refreshAllVideo();
    } else {
        refreshDatabaseVideo();
    }

    EventBus.getDefault().post(new UpdateFolderDanmuEvent());
}
 
Example 7
Source Project: FriendBook   Source File: FileUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 计算SD卡的剩余空间
 *
 * @return 返回-1,说明没有安装sd卡
 */
public static long getFreeDiskSpace() {
    String status = Environment.getExternalStorageState();
    long freeSpace = 0;
    if (status.equals(Environment.MEDIA_MOUNTED)) {
        try {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            freeSpace = availableBlocks * blockSize / 1024;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        return -1;
    }
    return (freeSpace);
}
 
Example 8
Source Project: MultipleImagePicker   Source File: CustomGalleryActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void initImageLoader() {
	try {
		String CACHE_DIR = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/.temp_tmp";
		new File(CACHE_DIR).mkdirs();

		File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(),
				CACHE_DIR);

		DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
				getBaseContext())
				.defaultDisplayImageOptions(defaultOptions)
				.discCache(new UnlimitedDiscCache(cacheDir))
				.memoryCache(new WeakMemoryCache());

		ImageLoaderConfiguration config = builder.build();
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(config);

	} catch (Exception e) {

	}
}
 
Example 9
Source Project: twitt4droid   Source File: Images.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the disk cache when is closed or null.
 * 
 * @param context the application context.
 */
private static void intDiskCacheIfNeeded(Context context) {
    if (DISK_CACHE == null || DISK_CACHE.isClosed()) {
        try {
            long size = 1024 * 1024 * 10;
            String cachePath = 
                    Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || Files.isExternalStorageRemovable()
                    ? Files.getExternalCacheDir(context).getPath() 
                    : context.getCacheDir().getPath();
            File file = new File(cachePath + File.separator + IMAGE_CACHE_DIR);
            DISK_CACHE = DiskLruCache.open(file, 1, 1, size); // Froyo sometimes fails to initialize
        } catch (IOException ex) {
            Log.e(TAG, "Couldn't init disk cache", ex);
        }
    }
}
 
Example 10
Source Project: Android-utils   Source File: CrashHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Init crash log cache directory.
 *
 * @param application application
 * @param crashDirPath crash log file cache directory
 */
private static void initCacheDir(Application application, final String crashDirPath) {
    if (StringUtils.isSpace(crashDirPath)) {
        dir = null;
    } else {
        dir = crashDirPath.endsWith(FILE_SEP) ? crashDirPath : crashDirPath + FILE_SEP;
    }
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            && application.getExternalCacheDir() != null) {
        // defaultDir: /android/data/< package name >/cache/crash/...
        defaultDir = application.getExternalCacheDir() + FILE_SEP + "crash" + FILE_SEP;
    } else {
        // defaultDir: /data/data/< package name >/cache/crash/...
        defaultDir = application.getCacheDir() + FILE_SEP + "crash" + FILE_SEP;
    }
}
 
Example 11
Source Project: L.TileLayer.Cordova   Source File: DirectoryManager.java    License: MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example 12
Source Project: rscnn   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    rs = RenderScript.create(this);
    try {
        AssetManager assetManager = getAssets();
        String[] fileList = assetManager.list(modelPath);
        if (fileList.length != 0){
            detector = new MobileNetSSD(rs, assetManager, modelPath);
        }
        else {
            String modelDir = Environment.getExternalStorageDirectory().getPath() + "/" + modelPath;
            detector = new MobileNetSSD(rs, null, modelDir);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    setContentView(R.layout.activity_main);
}
 
Example 13
Source Project: TvRemoteControl   Source File: InputMethodManagerService.java    License: Apache License 2.0 6 votes vote down vote up
public InputMethodFileManager(HashMap<String, InputMethodInfo> methodMap, int userId) {
    if (methodMap == null) {
        throw new NullPointerException("methodMap is null");
    }
    mMethodMap = methodMap;
    final File systemDir = userId == UserHandle.USER_OWNER
            ? new File(Environment.getDataDirectory(), SYSTEM_PATH)
            : Environment.getUserSystemDirectory(userId);
    final File inputMethodDir = new File(systemDir, INPUT_METHOD_PATH);
    if (!inputMethodDir.mkdirs()) {
        Slog.w(TAG, "Couldn't create dir.: " + inputMethodDir.getAbsolutePath());
    }
    final File subtypeFile = new File(inputMethodDir, ADDITIONAL_SUBTYPES_FILE_NAME);
    mAdditionalInputMethodSubtypeFile = new AtomicFile(subtypeFile);
    if (!subtypeFile.exists()) {
        // If "subtypes.xml" doesn't exist, create a blank file.
        writeAdditionalInputMethodSubtypes(
                mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, methodMap);
    } else {
        readAdditionalInputMethodSubtypes(
                mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile);
    }
}
 
Example 14
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public File[] getExternalFilesDirs(String type) {
    synchronized (mSync) {
        if (mExternalFilesDirs == null) {
            mExternalFilesDirs = Environment.buildExternalStorageAppFilesDirs(getPackageName());
        }

        // Splice in requested type, if any
        File[] dirs = mExternalFilesDirs;
        if (type != null) {
            dirs = Environment.buildPaths(dirs, type);
        }

        // Create dirs if needed
        return ensureDirsExistOrFilter(dirs);
    }
}
 
Example 15
Source Project: letv   Source File: StorageUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static File getCacheDirectory(Context context, boolean preferExternal) {
    File appCacheDir = null;
    String externalStorageState;
    try {
        externalStorageState = Environment.getExternalStorageState();
    } catch (NullPointerException e) {
        externalStorageState = "";
    }
    if (preferExternal && "mounted".equals(externalStorageState) && hasExternalStoragePermission(context)) {
        appCacheDir = getExternalCacheDir(context);
    }
    if (appCacheDir == null) {
        appCacheDir = context.getCacheDir();
    }
    if (appCacheDir != null) {
        return appCacheDir;
    }
    L.w("Can't define system cache directory! '%s' will be used.", "/data/data/" + context.getPackageName() + "/cache/");
    return new File("/data/data/" + context.getPackageName() + "/cache/");
}
 
Example 16
Source Project: android-tesseract-ocr   Source File: OCRActivity.java    License: MIT License 6 votes vote down vote up
/**
 * http://developer.android.com/training/camera/photobasics.html
 */
private File createImageFile() throws IOException {
	// Create an image file name
	String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
			.format(new Date());
	String imageFileName = "JPEG_" + timeStamp + "_";
	String storageDir = Environment.getExternalStorageDirectory()
			+ "/TessOCR";
	File dir = new File(storageDir);
	if (!dir.exists())
		dir.mkdir();

	File image = new File(storageDir + "/" + imageFileName + ".jpg");

	// Save a file: path for use with ACTION_VIEW intents
	mCurrentPhotoPath = image.getAbsolutePath();
	return image;
}
 
Example 17
Source Project: Android-Application-ZJB   Source File: StorageUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static File getExternalCacheDir(Context context) {
	File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
	File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
	if (!appCacheDir.exists()) {
		if (!appCacheDir.mkdirs()) {
			L.w("Unable to create external cache directory");
			return null;
		}
		try {
			new File(appCacheDir, ".nomedia").createNewFile();
		} catch (IOException e) {
			L.i("Can't create \".nomedia\" file in application external cache directory");
		}
	}
	return appCacheDir;
}
 
Example 18
Source Project: SoftwarePilot   Source File: RoutineTemplate.java    License: MIT License 6 votes vote down vote up
byte[] read4k(){
    try {
        File file = new File(Environment.getExternalStorageDirectory().getPath()+"/AUAVtmp/fullPic.JPG");
        //File file = new File("../tmp/pictmp.jpg");
        FileChannel fileChannel = new RandomAccessFile(file, "r").getChannel();
        MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
        pic = new byte[buffer.capacity()];
        while(buffer.hasRemaining()){
            int remaining = pic.length;
            if(buffer.remaining() < remaining){
                remaining = buffer.remaining();
            }
            buffer.get(pic, 0, remaining);
        }
        return pic;
    } catch(Exception e){
        e.printStackTrace();
    }
    return new byte[0];
}
 
Example 19
Source Project: osmdroid   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * gets storage state and current cache size
 */
private void updateStorageInfo(){

    long cacheSize = updateStoragePreferences(this);
    //cache management ends here

    TextView tv = findViewById(R.id.sdcardstate_value);
    final String state = Environment.getExternalStorageState();

    boolean mSdCardAvailable = Environment.MEDIA_MOUNTED.equals(state);
    tv.setText((mSdCardAvailable ? "Mounted" : "Not Available") );
    if (!mSdCardAvailable) {
        tv.setTextColor(Color.RED);
        tv.setTypeface(null, Typeface.BOLD);
    }

    tv = findViewById(R.id.version_text);
    tv.setText(BuildConfig.VERSION_NAME + " " + BuildConfig.BUILD_TYPE);

    tv = findViewById(R.id.mainstorageInfo);
    tv.setText(Configuration.getInstance().getOsmdroidTileCache().getAbsolutePath() + "\n" +
        "Cache size: " + Formatter.formatFileSize(this,cacheSize));
}
 
Example 20
Source Project: PhotoMovie   Source File: DemoPresenter.java    License: Apache License 2.0 5 votes vote down vote up
private File initVideoFile() {
    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    if (!dir.exists()) {
        dir = mDemoView.getActivity().getCacheDir();
    }
    return new File(dir, String.format("photo_movie_%s.mp4",
            new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(System.currentTimeMillis())));
}
 
Example 21
Source Project: BotLibre   Source File: GraphicActivity.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void downloadFile(View v){

		if(gInstance.fileName.equals("")){
			MainActivity.showMessage("Missing file!", this);
			return;
		}
		
		String url=MainActivity.WEBSITE +"/"+ gInstance.media;
		
		try{
			
		DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
		request.setTitle(gInstance.fileName);
		request.setDescription(MainActivity.WEBSITE);
		
		//		request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);  only download thro wifi.
		
		request.allowScanningByMediaScanner();
		request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
		
		Toast.makeText(GraphicActivity.this, "Downloading " + gInstance.fileName, Toast.LENGTH_SHORT).show();
		
		request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, gInstance.fileName);
		DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
		
		BroadcastReceiver onComplete=new BroadcastReceiver() {
		    public void onReceive(Context ctxt, Intent intent) {
		        Toast.makeText(GraphicActivity.this, gInstance.fileName+" Downloaded!", Toast.LENGTH_SHORT).show();
		    }
		};
		manager.enqueue(request);
		registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
		
		}catch(Exception e){
			MainActivity.showMessage(e.getMessage(), this);
		}
	}
 
Example 22
Source Project: AndroidBase   Source File: FileUtil.java    License: Apache License 2.0 5 votes vote down vote up
/** 判断SD卡是否挂载 */
public static boolean isSDCardAvailable() {
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        return true;
    } else {
        return false;
    }
}
 
Example 23
Source Project: stynico   Source File: SimpleActivity.java    License: MIT License 5 votes vote down vote up
/**
    * 获得机身可用内存
    *
    * @return
    */
   private String getRomAvailableSize()
{
       File path = Environment.getDataDirectory();
       StatFs stat = new StatFs(path.getPath());
       long blockSize = stat.getBlockSize();
       long availableBlocks = stat.getAvailableBlocks();
       return Formatter.formatFileSize(SimpleActivity.this, blockSize * availableBlocks);
   }
 
Example 24
Source Project: YalpStore   Source File: FileProvider.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parse and return {@link PathStrategy} for given authority as defined in
 * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code &lt;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 = buildPath(DEVICE_ROOT, path);
            } else if (TAG_FILES_PATH.equals(tag)) {
                target = buildPath(context.getFilesDir(), path);
            } else if (TAG_CACHE_PATH.equals(tag)) {
                target = buildPath(context.getCacheDir(), path);
            } else if (TAG_EXTERNAL.equals(tag)) {
                target = buildPath(Environment.getExternalStorageDirectory(), path);
            }
            if (target != null) {
                strat.addRoot(name, target);
            }
        }
    }
    return strat;
}
 
Example 25
Source Project: BaseProject   Source File: SDCardUtil.java    License: MIT License 5 votes vote down vote up
/**
 * SD卡是否可用
 *
 * @return true:可用,false:不可用
 */
public static boolean isCanUseSD() {
    try {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 26
Source Project: cannonball-android   Source File: App.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isExternalStorageReadable() {
    final String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
            Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}
 
Example 27
/**
 * date: 7/12/17
 * author: chenli
 * description: 利用系统的下载服务
 */
private void downLoadFile(String url, String contentDisposition, String mimetype) {
    //创建下载任务,downloadUrl就是下载链接
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    //指定下载路径和下载文件名
    request.setDestinationInExternalPublicDir("/download/", URLUtil.guessFileName(url, contentDisposition, mimetype));
    //获取下载管理器
    DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    //将下载任务加入下载队列,否则不会进行下载
    if (downloadManager != null) downloadManager.enqueue(request);
    ToastUtils.showToast(BaseApplication.getContext(),
            "下载完成:" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    .getAbsolutePath() + File.separator + URLUtil.guessFileName(url, contentDisposition, mimetype));
}
 
Example 28
Source Project: LLApp   Source File: FileOperateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 外置存储卡的路径
 *
 * @return
 */
public static String getExternalStorePath() {
    if (isExistExternalStore()) {
        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }
    return null;
}
 
Example 29
Source Project: hipda   Source File: Utils.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void download(Context ctx, String url, String filename) {
    String authCookie = OkHttpHelper.getInstance().getAuthCookie();

    if (TextUtils.isEmpty(url) || TextUtils.isEmpty(filename)
            || (url.contains(HiUtils.ForumUrlPattern) && TextUtils.isEmpty(authCookie))) {
        UIUtils.toast("下载信息不完整,无法进行下载");
        return;
    }

    if (UIUtils.askForStoragePermission(ctx)) {
        return;
    }

    if (DownloadManagerResolver.resolve(ctx)) {
        DownloadManager dm = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url));
        req.addRequestHeader("User-agent", HiUtils.getUserAgent());
        if (url.contains(HiUtils.ForumUrlPattern)) {
            req.addRequestHeader("Cookie", "cdb_auth=" + authCookie);
        }
        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
        if (filename.toLowerCase().endsWith(".apk"))
            req.setMimeType("application/vnd.android.package-archive");
        dm.enqueue(req);
    }
}
 
Example 30
Source Project: AssistantBySDK   Source File: PcmPlayer.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 31
boolean hasExternalStoragePublicPicture() {
    // Create a path where we will place our picture in the user's
    // public pictures directory and check if the file exists.  If
    // external storage is not currently mounted this will think the
    // picture doesn't exist.
    File path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File file = new File(path, "DemoPicture.jpg");
    return file.exists();
}
 
Example 32
Source Project: Pioneer   Source File: IoUtils.java    License: Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static long getExtStorageAvailableApi18() {
    if (hasExtStorage()) {
        File extStorage = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(extStorage.getAbsolutePath());
        return sf.getAvailableBlocksLong() * sf.getBlockSizeLong();
    }
    return 0;
}
 
Example 33
Source Project: PracticeCode   Source File: ExplorerSetting.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_settings) {
        explorer.setCurrentDir(Environment.getExternalStorageDirectory().getPath());
        return true;
    }
    return super.onOptionsItemSelected(item);
}
 
Example 34
Source Project: DragScaleCircleView   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void loadImage() {
    if (hasWriteExternalStoragePermission()) {
        Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() + CAMERA_CROP_IMAGE_PATH);
        if (bitmap != null) {
            bitmap.copy(Bitmap.Config.ARGB_8888, true);
            croppedImage.setImageDrawable(null);
            croppedImage.setImageBitmap(bitmap);
        } else {
            Toast.makeText(getApplicationContext(), "NO SAVED IMAGE FOUND!", Toast.LENGTH_SHORT).show();
        }
    } else {
        requestWriteExternalStoragePermission(REQUEST_CODE_LOAD_IMAGE);
    }
}
 
Example 35
Source Project: sctalk   Source File: CommonUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @Description 获取sdcard可用空间的大小
 * @return
 */
@SuppressWarnings("deprecation")
public static long getSDFreeSize() {
    File path = Environment.getExternalStorageDirectory();
    StatFs sf = new StatFs(path.getPath());
    long blockSize = sf.getBlockSize();
    long freeBlocks = sf.getAvailableBlocks();
    // return freeBlocks * blockSize; //单位Byte
    // return (freeBlocks * blockSize)/1024; //单位KB
    return (freeBlocks * blockSize) / 1024 / 1024; // 单位MB
}
 
Example 36
Source Project: AndroidChromium   Source File: OMADownloadHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onPostExecute(OMAInfo omaInfo) {
    if (omaInfo == null) return;
    // Send notification if required attributes are missing.
    if (omaInfo.getTypes().isEmpty() || getSize(omaInfo) <= 0
            || omaInfo.isValueEmpty(OMA_OBJECT_URI)) {
        sendNotification(omaInfo, mDownloadInfo, DownloadItem.INVALID_DOWNLOAD_ID,
                DOWNLOAD_STATUS_INVALID_DESCRIPTOR);
        return;
    }
    // Check version. Null version are treated as 1.0.
    String version = omaInfo.getValue(OMA_DD_VERSION);
    if (version != null && !version.startsWith("1.")) {
        sendNotification(omaInfo, mDownloadInfo, DownloadItem.INVALID_DOWNLOAD_ID,
                DOWNLOAD_STATUS_INVALID_DDVERSION);
        return;
    }
    // Check device capabilities.
    if (Environment.getExternalStorageDirectory().getUsableSpace() < getSize(omaInfo)) {
        showDownloadWarningDialog(
                R.string.oma_download_insufficient_memory,
                omaInfo, mDownloadInfo, DOWNLOAD_STATUS_INSUFFICIENT_MEMORY);
        return;
    }
    if (getOpennableType(mContext.getPackageManager(), omaInfo) == null) {
        showDownloadWarningDialog(
                R.string.oma_download_non_acceptable_content,
                omaInfo, mDownloadInfo, DOWNLOAD_STATUS_NON_ACCEPTABLE_CONTENT);
        return;
    }
    showOMAInfoDialog(mDownloadId, mDownloadInfo, omaInfo);
}
 
Example 37
Source Project: AdBlockedWebView-Android   Source File: FileUtils.java    License: MIT License 5 votes vote down vote up
public static long downloadFile(Context context, String url, String mimeType) {
    try {
        String[] fnm = url.split("/");
        String fileName = fnm[fnm.length - 1];
        fileName = getFileName(fileName);
        String host = fnm[2];
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if(extension.equals(""))
            extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
        String fileNameWithExtension = fileName + "." + extension;

        DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setTitle(fileNameWithExtension);
        request.setMimeType(mimeType);
        request.setDescription(host);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileNameWithExtension);
        File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        if (!downloadsDir.exists()) {
            //noinspection ResultOfMethodCallIgnored
            downloadsDir.mkdirs();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        } else {
            //noinspection deprecation
            request.setShowRunningNotification(true);
        }
        request.setVisibleInDownloadsUi(true);
        long downloadId = dm.enqueue(request);

        Toast.makeText(context, context.getString(R.string.message_download_started), Toast.LENGTH_SHORT).show();

        return downloadId;
    } catch (SecurityException e) {
        throw new SecurityException("No permission allowed: android.permission.WRITE_EXTERNAL_STORAGE");
    }
}
 
Example 38
Source Project: AudioAnchor   Source File: MainActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void showChangeDirectorySelector() {
    File baseDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
    FileDialog fileDialog = new FileDialog(this, baseDirectory, null);
    fileDialog.setSelectDirectoryOption(true);
    fileDialog.addDirectoryListener(directory -> {
        // Set the storage directory to the selected directory
        if (mDirectory != null) {
            changeDirectoryWithConfirmation(directory);
        } else {
            setDirectory(directory);
        }
    });
    fileDialog.showDialog();
}
 
Example 39
@Override
protected void onStart() {
	super.onStart();
       SharedPreferences prefs = getSharedPreferences("PrettyGoodMusicPlayer", MODE_PRIVATE);
       Log.i(TAG, "Preferences " + prefs + " " + ((Object)prefs));
       baseDir = prefs.getString("ARTIST_DIRECTORY", new File(Environment.getExternalStorageDirectory(), "Music").getAbsolutePath());
       Log.d(TAG, "Got configured base directory of " + baseDir);

       populateArtists(baseDir);
       
       simpleAdpt = new SimpleAdapter(this, artists, R.layout.pgmp_list_item, new String[] {"artist"}, new int[] {R.id.PGMPListItemText});
       ListView lv = (ListView) findViewById(R.id.artistListView);
       lv.setAdapter(simpleAdpt);
   }
 
Example 40
Source Project: a   Source File: StorageUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 下载的文件的保存路径,必须为外部存储,以“/”结尾
 *
 * @return 诸如 :/mnt/sdcard/Download/
 */
public static String getDownloadPath() throws RuntimeException {
    File file;
    if (externalMounted()) {
        file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    } else {
        throw new RuntimeException("外置存储不可用!");
    }
    return FileUtils.separator(file.getAbsolutePath());
}