栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何通知我的应用程序从SD卡(Android)删除了一个文件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何通知我的应用程序从SD卡(Android)删除了一个文件?

调查使用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. 挂载sdcard时(以及重新启动时),您必须进行同步。这可能很慢


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/438255.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号