在启动设备时使用Android FileObserver的优雅方式

时间:2014-03-26 09:55:46

标签: android boot mount fileobserver

我开发的应用程序在设备启动时自动启动,并且需要监视设备内存中的某些特殊目录,为此我使用FileObservers,我的代码片段是:

 if (folder == null)
    throw new FailedExecutionException(
            "Trying to check the limit of a null directory");

Log.d(TAG, "Setting a limit for " + folder.getAbsolutePath());

if (!folder.isDirectory())
    throw new FailedExecutionException(
            "FolderLimit should be checked on directories, "
                    + folder.getAbsolutePath() + " is not a directory");

    //Then create the FileObserver...

当我启动此应用程序并且设备正在运行时,分区在哪里是我观察的文件夹,我可以监视它,问题是当我重启设备时,然后执行此代码在系统安装分区之前,它并没有将其识别为文件夹:

com.mycompany.android.helpers.util.FailedExecutionException: FolderLimit should be checked on directories, /mnt/sdcard1/mycompany/photo/white_list is not a directory

当然我可以做某种while(!created){ attempt() }但是我想问一下是否有一种更优雅的方式来通知这个应用程序分区已经挂载并且系统已准备好。

如果我在shell中执行mount,我所拥有的是:

127|root@android:/ # mount | busybox grep sdcard1                              
/dev/block/vold/179:4 /mnt/sdcard1 vfat        rw,dirsync,nosuid,nodev,noexec,relatime,uid=1000,gid=1015,fmask=0702,dmask=0702,allow_utime= 0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0
tmpfs /mnt/sdcard1/.android_secure tmpfs ro,relatime,size=0k,mode=000 0 0

谢谢

编辑我忘了说,我不能使用Environment.getExternalStorage(),它是一个修改过的设备,这是一个不保证是外部存储的分区发布版本中的路径

1 个答案:

答案 0 :(得分:1)

最后我是通过蛮力做到的......

private void attemptToCreateFolderLimit(final File file,
    final long limitCount, final long recycle) {

ThreadFactory.startNewThread(TAG, new Runnable() {

    @Override
    public void run() {
    for (int i = 0; i < FOLDER_LIMIT_CREATION_ATTEMPTS; i++) {
        Log.d(TAG,
            "creating folder limit for "
                + file.getAbsoluteFile());

        try {
        FolderLimit limit = new FolderLimit(file, limitCount,
            recycle);
        folderLimits.add(limit);
        } catch (FailedExecutionException e) {
        Log.e(TAG, "Limit not created");
        Log.e(TAG, Log.getStackTraceString(e));
        }
        try {
        Thread.sleep(FOLDER_LIMIT_TIME_BETWEEN_ATTEMPTS);
        } catch (InterruptedException e) {
        Log.e(TAG, Log.getStackTraceString(e));
        }

    }
    }
});

}