標籤:
今天在測試android拍照功能時遇到一個困惑:照片拍成功了,程式能都能讀取到,但是在手機儲存中怎麼也找不到拍的照片。先將學習過程中經過的曲折過程記錄如下:
一:拍照並保持
通過調用android 的Camera介面,拍照片,在回調介面中儲存圖片:
public void onPictureTaken(byte[] bytes, Camera camera) { // 定義檔案名稱 Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmssSS"); String fileName = dateFormat.format(date)+".jpg"; FileOutputStream os = null; boolean success = true; try{ // 儲存到內部儲存 os = getActivity().openFileOutput(path, Context.MODE_PRIVATE); os.write(bytes); }catch (IOException e){ success = false; Log.e(TAG, "Error writing to file " + fileName, e);}
原來此次調用的:getActivity().openFileOutput(path, Context.MODE_PRIVATE);是把檔案儲存到了APP的私人儲存中的/data/data/...app包路徑/file 中了,這個私人目錄是不能被外部存取的,所以在手機儲存中肯定看不到。
二:該為儲存到外部儲存
public void onPictureTaken(byte[] bytes, Camera camera) { // 定義檔案名稱 Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmssSS"); String fileName = dateFormat.format(date)+".jpg"; FileOutputStream os = null; boolean success = true; try{ File path = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); File file = new File(path, fileName); path.mkdirs(); if (path.exists()){ os = new FileOutputStream(file); }else { Log.e(TAG,"Create path failed"); return; } // 儲存到內部儲存 os.write(bytes); }catch (IOException e){ success = false; Log.e(TAG, "Error writing to file " + fileName, e); }
向外部儲存讀寫檔案需要申請許可權,在app設定檔中增加如下許可權:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
好了,檔案儲存成功了,但是還是在手機儲存中看不到,為什嗎?
原來,android儲存中新增檔案,並不能及時重新整理儲存目錄,需要重啟手機或者通過代碼手動重新整理目錄。手動重新整理目錄經過我測試的有以下兩種方式:
1.發廣播
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath().toString())));
其中第二個參數指的是儲存檔案的絕對路徑
2.MediaScannerConnection
MediaScannerConnection.scanFile(getActivity(), new String[]{file.getAbsolutePath().toString()}, null, null);
三:總結
Android的儲存分為app私人儲存和外部儲存。app私人儲存是不可以被其他app訪問的。外部儲存是可以被其他app共用的。外部儲存並不是指SD卡儲存,也包括手機自身的儲存空間。
關於android儲存