android.os.Environment Java Examples

The following examples show how to use android.os.Environment. 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 check out the related API usage on the sidebar.
Example #1
Source File: PcmPlayer.java    From AssistantBySDK with Apache License 2.0 8 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 #2
Source File: RoutineTemplate.java    From SoftwarePilot with 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 #3
Source File: BraceletApp.java    From MiBandDecompiled with 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 #4
Source File: MainActivity.java    From osmdroid with 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 #5
Source File: ImageViewerActivity.java    From scallop with 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 #6
Source File: Metodos.java    From ExamplesAndroid with 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 #7
Source File: StorageUtils.java    From Roid-Library with 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 #8
Source File: PhotosViewSlider.java    From PhotoViewSlider with 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 #9
Source File: PlayFragmentPresenterImpl.java    From DanDanPlayForAndroid with 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 #10
Source File: FileUtil.java    From FriendBook with 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 #11
Source File: CustomGalleryActivity.java    From MultipleImagePicker with 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 #12
Source File: StorageUtils.java    From Android-Application-ZJB with 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 #13
Source File: OCRActivity.java    From android-tesseract-ocr with 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 #14
Source File: Images.java    From twitt4droid with 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 #15
Source File: StorageUtils.java    From letv with 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 File: ContextImpl.java    From AndroidComponentPlugin with 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 #17
Source File: CrashHelper.java    From Android-utils with 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 #18
Source File: DirectoryManager.java    From L.TileLayer.Cordova with 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 #19
Source File: MainActivity.java    From rscnn with 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 #20
Source File: InputMethodManagerService.java    From TvRemoteControl with 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 #21
Source File: Helpers.java    From mobile-manager-tool with MIT License 5 votes vote down vote up
/**
    * @return the root of the filesystem containing the given path
    */
   public static File getFilesystemRoot(String path) {
File cache = Environment.getDownloadCacheDirectory();
if (path.startsWith(cache.getPath())) {
    return cache;
}
File external = Environment.getExternalStorageDirectory();
if (path.startsWith(external.getPath())) {
    return external;
}
throw new IllegalArgumentException(
	"Cannot determine filesystem root for " + path);
   }
 
Example #22
Source File: ImageUtil.java    From GenerateQRCode with Apache License 2.0 5 votes vote down vote up
/**
 * 保存图片到指定路径
 *
 * @param context
 * @param bitmap   要保存的图片
 * @param fileName 自定义图片名称
 * @return
 */
public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
    // 保存图片至指定路径
    String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode";
    File appDir = new File(storePath);
    if (!appDir.exists()) {
        appDir.mkdir();
    }
    File file = new File(appDir, fileName);
    try {
        FileOutputStream fos = new FileOutputStream(file);
        //通过io流的方式来压缩保存图片(80代表压缩20%)
        boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
        fos.flush();
        fos.close();

        //发送广播通知系统图库刷新数据
        Uri uri = Uri.fromFile(file);
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        if (isSuccess) {
            return true;
        } else {
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example #23
Source File: BaseUtils.java    From AndroidNetwork with MIT License 5 votes vote down vote up
/**
 * 检查是否安装了sd卡
 * 
 * @return false 未安装
 */
public static boolean sdcardMounted()
{
    final String state = Environment.getExternalStorageState();
    if (state.equals(Environment.MEDIA_MOUNTED) && !state.equals(Environment.MEDIA_MOUNTED_READ_ONLY))
    {
        return true;
    }
    return false;
}
 
Example #24
Source File: StorageUtils.java    From a with 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());
}
 
Example #25
Source File: ArtistList.java    From prettygoodmusicplayer with GNU General Public License v3.0 5 votes vote down vote up
@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 #26
Source File: MainActivity.java    From AudioAnchor with 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 #27
Source File: FileUtils.java    From AdBlockedWebView-Android with 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 #28
Source File: DemoPresenter.java    From PhotoMovie with 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 #29
Source File: OMADownloadHandler.java    From AndroidChromium with 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 #30
Source File: PhotoUtil.java    From GankLock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param name 图片的_id
 */
public static void savePhotoByBitmap(final Context context, final Bitmap bitmap, final String name) {
    final String fileName = name + ".jpg";
    final File fileDir = new File(Environment.getExternalStorageDirectory(),
        "GankLock");//GankLock/Images
    if (!fileDir.exists()) {
        fileDir.mkdir();
    } else if (fileDir.listFiles().length != 0) {
        for (File file : fileDir.listFiles()) {
            if (file.getName().equals(fileName)) {
                Toast.makeText(context, "图片已经下载了", Toast.LENGTH_SHORT).show();
                return;
            }
        }
    }

    Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(ObservableEmitter<String> emitter) throws Exception {
            String photoUrl = createPhoto(context, fileDir, fileName, bitmap);
            emitter.onNext("图片已保存至" + photoUrl);
        }
    }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(String s) throws Exception {
                    Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
                }
            });
}