做一個音樂播放器,有個本地掃描功能,大家都知道是使用contentresover 來獲取媒體庫
的數據的,但是我新下載的MP3
文件如何能實時的掃描到本地音樂庫呢?網上用的兩種方法,
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory().toString()));
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
還有context.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment
.getExternalStorageDirectory()
.getAbsolutePath())));
並不是每個手機都有效的,就算有效,掃描時間也特別長,怎麼能像QQ音樂那樣 ,實時的就更新到本地數據庫的呢?
解決了。。。首先掃描制定 文件的類
public class MediaScannerFile {
/**
* 掃描指定的文件
*
* @param context
* @param filePath
* @param sListener
*/
public MediaScannerConnection scanFile(Context context,
String[] filePath, String[] mineType,
OnScanCompletedListener sListener) {
ClientProxy client = new ClientProxy(filePath, mineType, sListener);
try {
MediaScannerConnection connection = new MediaScannerConnection(
context.getApplicationContext(), client);
client.mConnection = connection;
connection.connect();
return connection;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
class ClientProxy implements MediaScannerConnectionClient {
final String[] mPaths;
final String[] mMimeTypes;
final OnScanCompletedListener mClient;
MediaScannerConnection mConnection;
int mNextPath;
ClientProxy(String[] paths, String[] mimeTypes,
OnScanCompletedListener client) {
mPaths = paths;
mMimeTypes = mimeTypes;
mClient = client;
}
public void onMediaScannerConnected() {
scanNextPath();
}
public void onScanCompleted(String path, Uri uri) {
if (mClient != null) {
mClient.onScanCompleted(path, uri);
}
scanNextPath();
}
/**
* 自動掃描下一個
*/
void scanNextPath() {
if (mNextPath >= mPaths.length) {
mConnection.disconnect();
return;
}
String mimeType = mMimeTypes != null ? mMimeTypes[mNextPath]
: null;
mConnection.scanFile(mPaths[mNextPath], mimeType);
mNextPath++;
}
}
}
調用
添加掃描完畢的監聽:
MediaScannerFile mMediaScannerFile = new MediaScannerFile();
if (null != mMediaScannerFile) {
mMediaScannerFile
.scanFile(context,
new String[] { dinfo
.getSavePath() },
null, new OnScanCompletedListener());
}
public void onScanCompleted(final String path, final Uri uri) {
//to do something
}