系統:android4.4及其以上
功能:app中拍照, 並實現瀏覽、刪除照片操作。
實現:
1.拍照,存儲到指定路徑path
2.通知系統多媒體數據庫刷新數據。
主要使用MediaScannerConnection,該類向應用提供了將新增多媒體文件發送給多媒體掃描服務的方法,進而將數據寫入到系統多媒體數據庫,參考實現如下:

public class MediaScanner { private MediaScannerConnection mediaScanConn = null; private PhotoSannerClient client = null; private String filePath = null; private String fileType = null; private static MediaScanner mediaScanner= null; /** * 然后調用MediaScanner.scanFile("/sdcard/2.mp3"); * */ public MediaScanner(Context context) { // 創建MusicSannerClient if (client == null) { client = new PhotoSannerClient(); } if (mediaScanConn == null) { mediaScanConn = new MediaScannerConnection(context, client); } } public static MediaScanner getInstanc(Context context){ if (mediaScanner==null){ mediaScanner = new MediaScanner(context); } return mediaScanner; } private class PhotoSannerClient implements MediaScannerConnection.MediaScannerConnectionClient { public void onMediaScannerConnected() { if (filePath != null) { mediaScanConn.scanFile(filePath, fileType); } filePath = null; fileType = null; } public void onScanCompleted(String path, Uri uri) { // TODO Auto-generated method stub mediaScanConn.disconnect(); } } /** * 掃描文件標簽信息 * * @param filePath * 文件路徑 eg:/sdcard/MediaPlayer/dahai.mp3 * @param fileType * 文件類型 eg: audio/mp3 media/* application/ogg * */ public void scanFile(String filepath, String fileType) { this.filePath = filepath; this.fileType = fileType; // 連接之后調用MusicSannerClient的onMediaScannerConnected()方法 mediaScanConn.connect(); } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } }
3.刪除照片, 並刪除多媒體數據庫中的相關內容。對於刪除操作, 都可以通過content provider直接操作多媒體數據庫執行刪除,參考代碼如下:

if (file.isFile()) { String filePath = file.getPath(); if(filePath.endsWith(".mp4")){ int res = context.getContentResolver().delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, MediaStore.Audio.Media.DATA + "= \"" + filePath+"\"", null); if (res>0){ file.delete(); }else{ Log.e(TAG, "刪除文件失敗"); } }else if (filePath.endsWith(".jpg")||filePath.endsWith(".png")||filePath.endsWith(".bmp")){ int res = context.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Audio.Media.DATA + "= \"" + filePath+"\"", null); if (res>0){ file.delete(); }else{ Log.e(TAG, "刪除文件失敗"); } }else{ file.delete(); } //刪除多媒體數據庫中的數據 return; }