Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 掃描 SD 卡上的音樂檔並監聽掃描事件

本文示範如何掃描 SD 卡中的音樂檔,並透過廣播接收機即時監聽掃描的开始與結束事件。

一、撰寫廣播接收機

  1. public class ScanSdReceiver extends BroadcastReceiver
  2.     {
  3.         @Override
  4.         public void onReceive(Context context, Intent intent)
  5.         {
  6.             String action = intent.getAction();
  7.             if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action))
  8.             {
  9.                 //開始掃描,把你的程式碼放這裡
  10.             }
  11.             else if (Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action))
  12.             {
  13.                 //掃描結束,把你的程式碼放這裡
  14.             }
  15.         }
  16.     }

二、註冊廣播接收機以監聽 SD 卡掃描事件

  1. IntentFilter intentfilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED);
  2. intentfilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
  3. intentfilter.addDataScheme("file");
  4. ScanSdReceiver scanSdReceiver = new ScanSdReceiver();
  5. registerReceiver(scanSdReceiver, intentfilter);

三、觸發 SD 卡掃描

  1. sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
  2.     Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath())));
Copyright © Linux教程網 All Rights Reserved