您的位置:首页 > 移动开发 > Android开发

android4.4 ROM开发者全盘扫描解决方案

2015-07-28 15:14 447 查看
大家都知道android4.4之后,google屏蔽了Intent.ACTION_MEDIA_MOUNTED,这个广播的放送。所以导致的问题是我们没法全盘扫描,最近百度了很多方案都只是给予MediaScannerConnection.scanFile(),这个解决方法,但是这个方法并不理想无法达到我们全盘扫描的目的。在找不到更好方案的前提下,我只能另辟蹊径了,作为一个android ROM开发者最大的优势是能改framework层及其他provider代码,所以以下解决方案是修改MediaProvider完成的。

直接上代码

AndroidManifest.xml

<receiver android:name="MediaScannerReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<data android:scheme="file" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MEDIA_UNMOUNTED" />
<data android:scheme="file" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SCANNER_ALL" />
<data android:scheme="file" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MEDIA_SCANNER_SCAN_FILE" />
<data android:scheme="file" />
</intent-filter>
</receiver>


MediaScannerReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
final Uri uri = intent.getData();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
// Scan both internal and external storage
scan(context, MediaProvider.INTERNAL_VOLUME);
scan(context, MediaProvider.EXTERNAL_VOLUME);

} else {
if (uri.getScheme().equals("file")) {
// handle intents related to external storage
String path = uri.getPath();
String externalStoragePath = Environment.getExternalStorageDirectory().getPath();
String legacyPath = Environment.getLegacyExternalStorageDirectory().getPath();

try {
path = new File(path).getCanonicalPath();
} catch (IOException e) {
Log.e(TAG, "couldn't canonicalize " + path);
return;
}
if (path.startsWith(legacyPath)) {
path = externalStoragePath + path.substring(legacyPath.length());
}

Log.d(TAG, "action: " + action + " path: " + path);
//在这就加一句话就是这么简单
if (Intent.ACTION_MEDIA_MOUNTED.equals(action) || action.equals("android.intent.action.SCANNER_ALL")) {
// scan whenever any volume is mounted
scan(context, MediaProvider.EXTERNAL_VOLUME);
} else if (Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action) &&
path != null && path.startsWith(externalStoragePath + "/")) {
scanFile(context, path);
}
}
}
}


然后只要在你想全盘扫描的时候发送android.intent.action.SCANNER_ALL广播就行了。

第三方应用单独来实现全盘扫描方法如果有哪位高手知道请评论告诉我。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: