gpt4 book ai didi

java - 我如何通知我的应用程序一个文件已从 SDCard (Android) 中删除?

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

我正在将几首歌曲保存在播放列表中(在我的应用程序数据库中)。当从播放列表中已存在的 SDCard 中删除特定歌曲时,如何在我的数据库中反射(reflect)更改?

最佳答案

考虑使用 FileObserver

您可以监控单个文件或目录。所以您需要做的是确定您在哪些目录中有歌曲并监控每个目录。否则你可以监控你的外部存储目录,然后每次有任何变化时,检查它是否是你数据库中的文件之一。

它的工作原理非常简单,像这样应该可以工作:

import android.os.FileObserver;
public class SongDeletedFileObserver extends FileObserver {
public String absolutePath;
public MyFileObserver(String path) {
//not sure if you need ALL_EVENTS but it was the only one in the doc listed as a MASK
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
}
@Override
public void onEvent(int event, String path) {
if (path == null) {
return;
}
//a new file or subdirectory was created under the monitored directory
if ((FileObserver.DELETE & event)!=0) {
//handle deleted file
}

//data was written to a file
if ((FileObserver.MODIFY & event)!=0) {
//handle modified file (maybe id3 info changed?)
}

//the monitored file or directory was deleted, monitoring effectively stops
if ((FileObserver.DELETE_SELF & event)!=0) {
//handle when the whole directory being monitored is deleted
}

//a file or directory was opened
if ((FileObserver.MOVED_TO & event)!=0) {
//handle moved file
}

//a file or subdirectory was moved from the monitored directory
if ((FileObserver.MOVED_FROM & event)!=0) {
//?
}

//the monitored file or directory was moved; monitoring continues
if ((FileObserver.MOVE_SELF & event)!=0) {
//?
}

}
}

那么当然你需要让这个 FileObserver 一直运行才能有效,所以你需要把它放在一个服务中。从你会做的服务

SongDeletedFileObserver fileOb = new SongDeletedFileObserver(Environment.getExternalStorageDirectory());

您必须记住一些棘手的事情:

  1. 如果你让它一直运行,这会更耗电。
  2. 您必须在安装 SD 卡时(以及重新启动时)进行同步。这可能会很慢

关于java - 我如何通知我的应用程序一个文件已从 SDCard (Android) 中删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11555697/

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