privatevoidscan(String[]directories,StringvolumeName){// don't sleep while scanningmWakeLock.acquire();ContentValuesvalues=newContentValues();values.put(MediaStore.MEDIA_SCANNER_VOLUME,volumeName);UriscanUri=getContentResolver().insert(MediaStore.getMediaScannerUri(),values);Uriuri=Uri.parse("file://"+directories[0]);sendBroadcast(newIntent(Intent.ACTION_MEDIA_SCANNER_STARTED,uri));try{if(volumeName.equals(MediaProvider.EXTERNAL_VOLUME)){openDatabase(volumeName);}MediaScannerscanner=createMediaScanner();scanner.scanDirectories(directories,volumeName);}catch(Exceptione){Log.e(TAG,"exception in MediaScanner.scan()",e);}getContentResolver().delete(scanUri,null,null);sendBroadcast(newIntent(Intent.ACTION_MEDIA_SCANNER_FINISHED,uri));mWakeLock.release();}
publicvoidonReceive(Contextcontext,Intentintent){Stringaction=intent.getAction();Uriuri=intent.getData();if(action.equals(Intent.ACTION_BOOT_COMPLETED)){// scan internal storagescan(context,MediaProvider.INTERNAL_VOLUME);}else{if(uri.getScheme().equals("file")){// handle intents related to external storageStringpath=uri.getPath();StringexternalStoragePath=Environment.getExternalStorageDirectory().getPath();Log.d(TAG,"action: "+action+" path: "+path);if(action.equals(Intent.ACTION_MEDIA_MOUNTED)){// scan whenever any volume is mountedscan(context,MediaProvider.EXTERNAL_VOLUME);}elseif(action.equals(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)&&path!=null&&path.startsWith(externalStoragePath+"/")){scanFile(context,path);}}}}
// this function is used to scan a single filepublicUriscanSingleFile(Stringpath,StringvolumeName,StringmimeType){try{initialize(volumeName);prescan(path,true);Filefile=newFile(path);if(!file.exists()){returnnull;}// lastModified is in milliseconds on Files.longlastModifiedSeconds=file.lastModified()/1000;// always scan the file, so we can return the content://media Uri for existing filesreturnmClient.doScanFile(path,mimeType,lastModifiedSeconds,file.length(),false,true,MediaScanner.isNoMediaPath(path));}catch(RemoteExceptione){Log.e(TAG,"RemoteException in MediaScanner.scanFile()",e);returnnull;}}