Android FileObserver example in Xamarin/C#? [closed]

我是研究僧i 提交于 2019-11-30 14:51:35

Create a class that inherits from Android.OS.FileObserver, you only need to implement the OnEvent() and one(+) Constructors. Its a really simple pattern after you see it once... ;-)

Notes:

  • Watch on a path, if you need to filter by file, do it in the OnEvent
  • Do not let your FileObserver object get GC'd or your OnEvents will magically stop :-/
  • Remember to call StartWatching() in order to receive OnEvent calls

FileObserver Class:

using System;
using Android.OS;
using Android.Util;

namespace MyFileObserver
{
    public class MyPathObserver : Android.OS.FileObserver
    {
        static FileObserverEvents _Events = (FileObserverEvents.AllEvents);
        const string tag = "StackoverFlow";

        public MyPathObserver (String rootPath) : base(rootPath, _Events)
        {
            Log.Info(tag, String.Format("Watching : {0}", rootPath)); 
        }

        public MyPathObserver (String rootPath, FileObserverEvents events) : base(rootPath, events)
        {
            Log.Info(tag, String.Format("Watching : {0} : {1}", rootPath, events)); 
        }

        public override void OnEvent(FileObserverEvents e, String path)
        {
            Log.Info(tag, String.Format("{0}:{1}",path, e)); 
        }
    }
}

Example Usage:

var pathToWatch = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
// Do not let myFileObserver get GC'd, stash it's ref in an activty, or ...
myFileObserver = new MyPathObserver (pathToWatch);
myFileObserver.StartWatching (); // and StopWatching () when you are done...
var document = Path.Combine(pathToWatch, "StackOverFlow.txt");
button.Click += delegate {
    if (File.Exists (document)) {
        button.Text = "Delete File";
        File.Delete (document);
    } else {
        button.Text = "Create File";
        File.WriteAllText (document, "Foobar");
    }
};

adb logcat Output (when clicking on the test button):

I/StackoverFlow( 3596): StackOverFlow.txt:Create
I/StackoverFlow( 3596): StackOverFlow.txt:Open
I/StackoverFlow( 3596): StackOverFlow.txt:Modify
I/StackoverFlow( 3596): StackOverFlow.txt:CloseWrite
I/StackoverFlow( 3596): StackOverFlow.txt:Delete
I/StackoverFlow( 3596): StackOverFlow.txt:Create
I/StackoverFlow( 3596): StackOverFlow.txt:Open
I/StackoverFlow( 3596): StackOverFlow.txt:Modify
I/StackoverFlow( 3596): StackOverFlow.txt:CloseWrite
I/StackoverFlow( 3596): StackOverFlow.txt:Delete
I/StackoverFlow( 3596): StackOverFlow.txt:Create
I/StackoverFlow( 3596): StackOverFlow.txt:Open
I/StackoverFlow( 3596): StackOverFlow.txt:Modify
I/StackoverFlow( 3596): StackOverFlow.txt:CloseWrite
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!