本文示範如何掃描 SD 卡中的音樂檔,並透過廣播接收機即時監聽掃描的开始與結束事件。
一、撰寫廣播接收機
- public class ScanSdReceiver extends BroadcastReceiver
- {
- @Override
- public void onReceive(Context context, Intent intent)
- {
- String action = intent.getAction();
- if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action))
- {
- //開始掃描,把你的程式碼放這裡
- }
- else if (Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action))
- {
- //掃描結束,把你的程式碼放這裡
- }
- }
- }
二、註冊廣播接收機以監聽 SD 卡掃描事件
- IntentFilter intentfilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED);
- intentfilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
- intentfilter.addDataScheme("file");
- ScanSdReceiver scanSdReceiver = new ScanSdReceiver();
- registerReceiver(scanSdReceiver, intentfilter);
三、觸發 SD 卡掃描
- sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
- Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath())));