1. 发送 Intent.ACTION_MEDIA_SCANNER_SCAN_FILE 广播
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("/sdcard/xxx/xxx.jpg")));)
2.使用 MediacannerConnection 进行扫描, 也是指定路径对其进行扫描
MediaScannerConnection msc = new MediaScannerConnection(context, new MediaScannerConnectionClient() {
MediaProvider 中的MediaScannerReceiver.java 对 接收广播后,中的路径信息有判断(其实是有问题的。 外置sd卡 扫描不到的哦文件)
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Uri uri = intent.getData();
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// scan internal storage
scan(context, MediaProvider.INTERNAL_VOLUME);
} else {
if (uri.getScheme().equals("file")) {
// handle intents related to external storage
String path = uri.getPath();
String externalStoragePath = Environment.getExternalStorageDirectory().getPath();
Log.d(TAG, "action: " + action + " path: " + path);
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
// scan whenever any volume is mounted
scan(context, MediaProvider.EXTERNAL_VOLUME);
} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) &&
path != null && path.startsWith(externalStoragePath + "/")) {
scanFile(context, path);
}
}
}
}
稍微算正确点的,要修改 MediaProvider
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Uri uri = intent.getData();
// String externalStoragePath =
// Environment.getExternalStorageDirectory().getPath();
String externalSDStoragePath = Environment
.getExternalSDStorageDirectory().getPath();
String externalUDiskStoragePath = Environment
.getExternalUDiskStorageDirectory().getPath();
String externalExtSDStoragePath = Environment
.getExternalExtSDStorageDirectory().getPath();
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// scan internal storage
scan(context, MediaProvider.INTERNAL_VOLUME);
} else {
if (uri.getScheme().equals("file")) {
// handle intents related to external storage
String path = uri.getPath();
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
if (externalSDStoragePath.equals(path))
scan(context, MediaProvider.EXTERNAL_VOLUME_SD);
else if (externalUDiskStoragePath.equals(path))
scan(context, MediaProvider.EXTERNAL_VOLUME_UDISK);
else if (externalExtSDStoragePath.equals(path))
scan(context, MediaProvider.EXTERNAL_VOLUME_EXTSD);
else
Slog.w(TAG, "unknown volume path " + path);
} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
&& path != null
&& (path.startsWith(externalSDStoragePath + "/")
|| path.startsWith(externalExtSDStoragePath
+ "/") || path
.startsWith(externalUDiskStoragePath + "/"))) {
// 在上面的条件多些判断, 不然的话。外置SD卡 可是不扫描的
scanFile(context, path);
}
}
}
}
这里需要说一些。 看了源码(MediaProvider), 在 开机时, 他会进行全盘的扫描,所以文件就全出来咯。。