前言

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

实现

实际上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. [Android(安卓)中级]Voip之CSipSimple类库的编绎
  2. 【Unity3d】Unity5与Android交互通信(使用Android(安卓)Studio2.4
  3. Android常用控件总结
  4. Android(安卓)requires compiler compliance level 5.0 or 6.0.
  5. Android中资源文件夹res/raw和assets的使用
  6. Android传感器应用
  7. seekBar,RatingBar拖动条
  8. [Google Android] 理解NDK(1)-- 编译Android(安卓).so文件
  9. Android(安卓)adb不是内部或外部命令 问题解决

随机推荐

  1. 深入浅析Android手机卫士保存密码时进行m
  2. Android集成腾讯X5WebView
  3. 【Android】android模拟器命令详解
  4. Android 4.0 SDK 环境搭建体验(Windows 7
  5. 查看Sqlite 数据库
  6. android merge标签的用法
  7. Android JNI入门第一篇——HelloJni
  8. Android 学习手札(三) 视图(View)
  9. Android测试教程(3):测试项目
  10. Android原子操作的实现原理