前言

由于各种原因,总有需求想监听文件夹的变化

实现

实际上Android或者linux提供了inotify接口同来监听文件夹变化

参考代码如下

    int monitorfd; //监听的fd    int watcher;    int epollfd; //用epoll来轮询事件    struct epoll_event event;    struct epoll_event events[2];    FILE* fp;        monitorfd = inotify_init(); //初始化监听的fd    if (-1 == monitorfd) {        ALOGE("inotify_init error");        return;    }    //把文件夹添加进监听器    watcher = inotify_add_watch(monitorfd, "/sdcard/", IN_ALL_EVENTS);    if (-1 == watcher) {        ALOGE("inotify_add_watch error");        return;    }    //打开监听的fd 准备读取事件    fp = fdopen(monitorfd, "r");    if (NULL == fp) {        ALOGE("fdopen error");        return;    }       event.data.fd = monitorfd;    event.events = EPOLLIN | EPOLLET;  //读入,边缘触发方式    int ctrl = epoll_ctl(epollfd, EPOLL_CTL_ADD, monitorfd, &event);    if (-1 == ctrl) {        ALOGE("epoll_ctl error");        return;    }while (1) {        int n = epoll_wait(epollfd, events, 5, -1);        for (int i = 0; i < n; i++) {            ALOGI("%d, %d, %d", events[i].data.fd, monitorfd, events[i].events);            if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) {                /* An error has occured on this fd, or the socket is not                   ready for reading (why were we notified then?) */                ALOGE("epoll error\n");                close(events[i].data.fd);                continue;            } else if (monitorfd == events[i].data.fd) {                struct inotify_event ie;                int read_len = 0;                while (1) {                    read_len = fread(&ie, sizeof(ie), 1, fp);                    if (read_len < 0) {                        ALOGD("read error %d:%s\n", errno, strerror(errno));                        break;                    }                    ALOGD("%d, %0x, %d\n", ie.wd, ie.mask, ie.len);                    if (ie.len > 0) {                        char name[ie.len];                        read_len = fread(name, ie.len, 1, fp);                        if (read_len > 0) {                        //somethine to do                        }                    }                }            }        }    }

更多相关文章

  1. View事件分发机制
  2. Android ViewPager多页面滑动切换以及单页卡内添加事件
  3. Android中的文本框,图片以及点击事件的设置
  4. Android中资源文件夹res/raw和assets的使用
  5. Android事件拦截机制
  6. 一点见解: Android事件分发机制(三)
  7. Android中的多击事件

随机推荐

  1. 【转】Android背景选择器Selector详解
  2. [置顶] Android学好Shape不再依赖美工
  3. Android 基础知识
  4. Android从Linux系统启动
  5. 在ListItem某组件添加响应事件
  6. 「Android Tips」解决 Mac OSX 无法识别
  7. Android系统信息获取 之十:移动网络相关信
  8. Android 使用grade实现Android 项目debug
  9. Android Geocoder(位置解析)
  10. Android Studio 使用小结