Android如何監測文件夾內容變化詳解

一. 概述:

android.os包下的FileObserver類是一個用於監聽文件訪問、創建、修改、刪除、移動等操作的監聽器,基於linux的INotify。FileObserver是個抽象類,必須繼承它才能使用。每個FileObserver對象監聽一個單獨的文件或者文件夾,如果監視的是一個文件夾,那麼文件夾下所有的文件和級聯子目錄的改變都會觸發監聽的事件。

FileObserver簡介Android.os包下的FileObserver類是一個用於監聽文件訪問、創建、修改、刪除、移動等操作的監聽器,基於Linux的INotify。

FileObserver是個抽象類,必須繼承它才能使用。每個FileObserver對象監聽一個單獨的文件或者文件夾,如果監視的是一個文件夾,那麼文件夾下所有的文件和級聯子目錄的改變都會觸發監聽的事件。

二. 監聽的事件類型:

ACCESS,即文件被訪問

     MODIFY,文件被 修改

     ATTRIB,文件屬性被修改,如 chmod、chown、touch 等

     CLOSE_WRITE,可寫文件被 close

     CLOSE_NOWRITE,不可寫文件被 close

     OPEN,文件被 open

     MOVED_FROM,文件被移走,如 mv

     MOVED_TO,文件被移來,如 mv、cp

     CREATE,創建新文件

     DELETE,文件被刪除,如 rm

     DELETE_SELF,自刪除,即一個可執行文件在執行時刪除自己

     MOVE_SELF,自移動,即一個可執行文件在執行時移動自己

     CLOSE,文件被關閉,等同於(IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)

     ALL_EVENTS,包括上面的所有事件

三.實例

import com.example.androidemail.R;  
import com.example.androidemail.R.layout;  
  
import android.app.Activity;  
import android.os.Bundle;  
import android.os.Environment;  
import android.os.FileObserver;  
  
public class AndroidFileListenerActivity extends Activity {  
    private FileObserver mFileObserver;  
      
    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        if(null == mFileObserver) {  
            mFileObserver = new SDCardFileObserver(Environment.getExternalStorageDirectory().getPath());  
            mFileObserver.startWatching(); //開始監聽  
        }  
    }  
  
    public void onDestory() {  
        if(null != mFileObserver) mFileObserver.stopWatching(); //停止監聽  
    }  
      
    static class SDCardFileObserver extends FileObserver {  
        //mask:指定要監聽的事件類型,默認為FileObserver.ALL_EVENTS  
        public SDCardFileObserver(String path, int mask) {  
            super(path, mask);  
        }  
  
        public SDCardFileObserver(String path) {  
            super(path);  
        }  
  
        @Override  
        public void onEvent(int event, String path) {  
            final int action = event & FileObserver.ALL_EVENTS;  
            switch (action) {  
            case FileObserver.ACCESS:  
                System.out.println("event: 文件或目錄被訪問, path: " + path);  
                break;  
                  
            case FileObserver.DELETE:  
                System.out.println("event: 文件或目錄被刪除, path: " + path);  
                break;  
                  
            case FileObserver.OPEN:  
                System.out.println("event: 文件或目錄被打開, path: " + path);  
                break;  
                  
            case FileObserver.MODIFY:  
                System.out.println("event: 文件或目錄被修改, path: " + path);  
                break;  
                  
            case FileObserver.CREATE:  
                System.out.println("event: 文件或目錄被創建, path: " + path);  
                break;  
            }  
        }  
          
    }  
}  

onEvent是回調,系統監聽到事件後會觸發此事件,參數event就是上面所說的事件類型,參數path就是觸發事件的目錄,鑒定隻針對於該層目錄,其他層次無效。

我們大多數需要監聽path目錄下的所有文件對象的相關操作,那該如何是好呢?解決問題方法之一就是重新實現FileObserver類,

下面是對FileObserver類的重寫實現過程

import java.io.File;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Stack;  
  
import android.os.FileObserver;  
import android.util.Log;  
  
@SuppressWarnings(value = { "rawtypes", "unchecked" })   
public class MultiFileObserver extends FileObserver {   
   
   /** Only modification events */   
    public static int CHANGES_ONLY = CREATE | MODIFY |DELETE | CLOSE_WRITE     
            | DELETE_SELF | MOVE_SELF | MOVED_FROM | MOVED_TO;   
   
    private List<SingleFileObserver> mObservers;   
    private String mPath;   
    private int mMask;   
   
    public MuityFileObserver(String path) {   
        this(path, ALL_EVENTS);   
    }   
   
    public MuityFileObserver(String path, int mask) {   
        super(path, mask);   
        mPath = path;   
        mMask = mask;   
    }   
   
    @Override   
    public void startWatching() {   
        if (mObservers != null)   
            return;   
   
        mObservers = new ArrayList<SingleFileObserver>();   
        Stack<String> stack = new Stack<String>();   
        stack.push(mPath);   
   
        while (!stack.isEmpty()) {   
            String parent = stack.pop();   
            mObservers.add(new SingleFileObserver(parent, mMask));   
            File path = new File(parent);   
            File[] files = path.listFiles();   
            if (null == files)   
                continue;   
            for (File f : files) {   
                if (f.isDirectory() && !f.getName().equals(".")   
                        && !f.getName().equals("..")) {   
                    stack.push(f.getPath());   
                }   
            }   
        }   
   
        for (int i = 0; i < mObservers.size(); i++) {   
            SingleFileObserver sfo =  mObservers.get(i);   
            sfo.startWatching();   
        }   
    };   
   
    @Override   
    public void stopWatching() {   
        if (mObservers == null)   
            return;   
   
        for (int i = 0; i < mObservers.size(); i++) {   
            SingleFileObserver sfo = mObservers.get(i);   
            sfo.stopWatching();   
        }   
           
        mObservers.clear();   
        mObservers = null;   
    };   
  
   
    @Override   
    public void onEvent(int event, String path) {   
        switch (event) {   
        case FileObserver.ACCESS:   
            Log.i("RecursiveFileObserver", "ACCESS: " + path);   
            break;   
        case FileObserver.ATTRIB:   
            Log.i("RecursiveFileObserver", "ATTRIB: " + path);   
            break;   
        case FileObserver.CLOSE_NOWRITE:   
            Log.i("RecursiveFileObserver", "CLOSE_NOWRITE: " + path);   
            break;   
        case FileObserver.CLOSE_WRITE:   
            Log.i("RecursiveFileObserver", "CLOSE_WRITE: " + path);   
            break;   
        case FileObserver.CREATE:   
            Log.i("RecursiveFileObserver", "CREATE: " + path);   
            break;   
        case FileObserver.DELETE:   
            Log.i("RecursiveFileObserver", "DELETE: " + path);   
            break;   
        case FileObserver.DELETE_SELF:   
            Log.i("RecursiveFileObserver", "DELETE_SELF: " + path);   
            break;   
        case FileObserver.MODIFY:   
            Log.i("RecursiveFileObserver", "MODIFY: " + path);   
            break;   
        case FileObserver.MOVE_SELF:   
            Log.i("RecursiveFileObserver", "MOVE_SELF: " + path);   
            break;   
        case FileObserver.MOVED_FROM:   
            Log.i("RecursiveFileObserver", "MOVED_FROM: " + path);   
            break;   
        case FileObserver.MOVED_TO:   
            Log.i("RecursiveFileObserver", "MOVED_TO: " + path);   
            break;   
        case FileObserver.OPEN:   
            Log.i("RecursiveFileObserver", "OPEN: " + path);   
            break;   
        default:   
            Log.i("RecursiveFileObserver", "DEFAULT(" + event + " : " + path);   
            break;   
        }   
    }   
   
    /** 
     * Monitor single directory and dispatch all events to its parent, with full 
     * path. 
     */   
    class SingleFileObserver extends FileObserver {   
        String mPath;   
   
        public SingleFileObserver(String path) {   
            this(path, ALL_EVENTS);   
            mPath = path;   
        }   
   
        public SingleFileObserver(String path, int mask) {   
            super(path, mask);   
            mPath = path;   
        }   
   
        @Override   
        public void onEvent(int event, String path) {   
            String newPath = mPath + "/" + path;   
            MultiFileObserver .this.onEvent(event, newPath);   
        }   
    }   
}

總結

到此這篇關於Android如何監測文件夾內容變化的文章就介紹到這瞭,更多相關Android監測文件夾內容內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: