保存Bitmap 到存儲卡(SD卡) 並通知文件管理器 更新

保存Bitmap 到存儲卡(SD卡) 並通知文件管理器 更新

  private void saveImage(Bitmap bitmap) {
        //此處範圍的所謂外部存儲是手機的自帶內存32G,64G,並不是SD卡,是否有訪問權限

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File newFileDir = new File(Environment.getExternalStorageDirectory(), "Download");
            if (!newFileDir.exists()) {
                newFileDir.mkdir();
            }
            String fileName = System.currentTimeMillis() + ".png";
            File file = new File(newFileDir, fileName);
            //打開文件輸出流
            FileOutputStream os = null;
            try {
                os = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

//            // 保存到圖庫
//            try {
//                MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), fileName, null);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
//
//            //通知更新圖庫
//            Uri uri = Uri.parse("file://" + Environment.getExternalStorageDirectory());
//            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
//            sendBroadcast(intent);

            MediaScannerConnection.scanFile(this,
                    new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned " + path + ":");
                            Log.i("ExternalStorage", "-> uri=" + uri);
                        }
                    });


        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章