Android starts mediascannerservice to scan multimedia files in the system, and then adds the information of these multimedia files to the multimedia database, the application obtains the multimedia information from the multimedia database instead of the SD card. That is to say, if some multimedia files are added or deleted after the instance is started, the multimedia database will not be automatically refreshed. Android provides two intent broadcast methods for the system to automatically refresh the multimedia database, which are intent. action_media_mounted and intent. action_media_scanner_scan_file: scan the entire SD card, scan a file, and send intent. after the broadcast action_media_mounted, you can also use the broadcast receiver to listen to the broadcasts action_media_scan_started and action_medai_scan_finish, which are sent by the system when scanning is started and scanning is completed. It takes 3-5 seconds to perform a full-card scan (in my case). I have not tried scanning a certain file. Recently, DLA needs to use the function to refresh the media library. Otherwise, if a new file has been added, restart the mobile phone and the system will be dizzy. I searched the internet, and many of them are recommended:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath())));
However, after I tried it, I found that every time I added or reduced a multimedia file, my entire music list disappeared and I don't know why. Later I referred to the following two practices, and finally realized the function: http://www.cnblogs.com/tanlon/archive/2011/09/06/2169302.html and http://dev.10086.cn/cmdn/bbs/viewthread.php? Tid = 36475
My specific implementation is:
public class MainActivity extends Activity {private MediaScannerConnection mediaScanConn = null;private MusicSannerClient client = null;private File filePath = null;private String fileType = null;@SuppressLint("SdCardPath")@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.main);client = new MusicSannerClient();mediaScanConn = new MediaScannerConnection(this, client);scanfile(new File("/sdcard"));}class MusicSannerClient implementsMediaScannerConnection.MediaScannerConnectionClient {public void onMediaScannerConnected() {Log.e("---------", "media service connected");if (filePath != null) {if (filePath.isDirectory()) {File[] files = filePath.listFiles();if (files != null) {for (int i = 0; i < files.length; i++) {if (files[i].isDirectory())scanfile(files[i]);else {mediaScanConn.scanFile(files[i].getAbsolutePath(), fileType);}}}}}filePath = null;fileType = null;}public void onScanCompleted(String path, Uri uri) {// TODO Auto-generated method stubmediaScanConn.disconnect();}}private void scanfile(File f) {this.filePath = f;mediaScanConn.connect();}}