gpt4 book ai didi

java - Android FileObserver onEvent 没有被调用

转载 作者:搜寻专家 更新时间:2023-11-01 09:03:29 25 4
gpt4 key购买 nike

有人可以帮我解决这个问题吗?

我想观察一个文件,看看它是否被修改,以便我可以更新 Activity 。经过多次测试,我确定它根本无法正常工作。我做错了什么吗?

我正在创建一个带有 onEvent 方法的 FileObserver 来显示 Toast 和日志数据,只是为了查看它是否正常工作,但是永远不会调用 onEvent。我已经对现有文件和新文件都进行了尝试,但在这两种情况下似乎都不起作用。

    Context context = this;
File fileFolder = context.getFilesDir();

String fileName = "quest";
FileObserver questObserver = new FileObserver(fileFolder.getPath()) { // also tried fileFolder.getName()
@Override
public void onEvent(int event, String path) {
Toast.makeText(getApplicationContext(), "onEvent fired", Toast.LENGTH_LONG).show();
Log.d(TAG, "FileObserver().onEvent");
}
};
questObserver.startWatching();

/* create file */
ObjectOutputStream objectOut = null;
try {
FileOutputStream fileOut = context.openFileOutput(fileName, Context.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(new Quest());
fileOut.getFD().sync();
} catch (IOException e) {
Log.d(TAG, e.getMessage());
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
}

/* read file */
ObjectInputStream objectIn = null;
Quest quest = null;

try {
FileInputStream fileIn = context.openFileInput(fileName);
objectIn = new ObjectInputStream(fileIn);
quest = (Quest) objectIn.readObject();
} catch (FileNotFoundException e) {
// Do nothing
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
}
Toast.makeText(context, quest.getTitle(), Toast.LENGTH_LONG).show();

questObserver.stopWatching();

如有任何帮助,我们将不胜感激。

最佳答案

'public abstract void onEvent (int event, String path)"-

This method is invoked on a special FileObserver thread. It runs independently of any threads, so take care to use appropriate synchronization! Consider using post(Runnable) to shift event handling work to the main thread to avoid concurrency problems.

http://developer.android.com/reference/android/os/FileObserver.html

如果您通过 handler.post(new Runnable(){...}) 放置 toast ,那应该可以工作。

关于java - Android FileObserver onEvent 没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13546958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com