Android Xamarin/C# 中的 FileObserver 示例?

Android FileObserver example in Xamarin/C#?

我需要有关在 Xamarin c# 中创建文件观察器的指导 (Android)

某种可行的例子会很棒!

我曾尝试将 java 转换为 C#,但由于我在 C# 环境中缺乏经验,编译时会抛出太多错误..并在其中获取写入参考代码C# vs java 被证明是令人恼火的..

所以,拜托!,可能有人会给我指出一些可行的方法

这是一个 java 文件观察者的例子 https://gist.github.com/shirou/659180

创建一个继承自 Android.OS.FileObserver, you only need to implement the OnEvent() 和一个 (+) 构造函数的 class。看过一次之后,它是一个非常简单的模式......;-)

备注:

  • 路径上观看,如果您需要按文件过滤,请在OnEvent
  • 中进行
  • 不要让您的 FileObserver 对象被 GC 处理,否则您的 OnEvents 会神奇地停止 :-/
  • 记得调用 StartWatching() 以接收 OnEvent 调用

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 = "Whosebug";

        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)); 
        }
    }
}

用法示例:

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, "Whosebug.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 输出(点击测试按钮时):

I/Whosebug( 3596): Whosebug.txt:Create
I/Whosebug( 3596): Whosebug.txt:Open
I/Whosebug( 3596): Whosebug.txt:Modify
I/Whosebug( 3596): Whosebug.txt:CloseWrite
I/Whosebug( 3596): Whosebug.txt:Delete
I/Whosebug( 3596): Whosebug.txt:Create
I/Whosebug( 3596): Whosebug.txt:Open
I/Whosebug( 3596): Whosebug.txt:Modify
I/Whosebug( 3596): Whosebug.txt:CloseWrite
I/Whosebug( 3596): Whosebug.txt:Delete
I/Whosebug( 3596): Whosebug.txt:Create
I/Whosebug( 3596): Whosebug.txt:Open
I/Whosebug( 3596): Whosebug.txt:Modify
I/Whosebug( 3596): Whosebug.txt:CloseWrite