使用FileObserver 类监听android sd卡变动

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.FileObserver;
import android.util.Log;

/**
 * sd卡上的目录创建监听器
 */
public class SDCardListener extends FileObserver {
    private Context context;

    public SDCardListener(Context context, String path) {
        // 这种构造方法是默认监听所有事件的,如果使用super(String,int)这种构造方法, 则int参数是要监听的事件类型.
        super(path);
        this.context = context;
        init();
    }

    /**
     * 注册监听器
     */
    public void init() {
        IntentFilter intentfilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED);
        intentfilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
        intentfilter.addDataScheme("file");
        ScanSdReceiver scanSdReceiver = new ScanSdReceiver();
        context.registerReceiver(scanSdReceiver, intentfilter);
    }

    @Override
    public void onEvent(int event, String path) {
        switch (event) {
        case FileObserver.CREATE://监听创建
            Log.d("Create", "path:" + path);
            rescanSdcard();
            break;
        case FileObserver.DELETE://监听删除
            Log.d("Delete", "path:" + path);
            rescanSdcard();
            break;
        }
    }

    /**
     * 刷新SD卡
     */
    public void rescanSdcard() {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
                Uri.parse("file://"+ Environment.getExternalStorageDirectory().getAbsolutePath())));
    }
}