FileDocCategorySizeDatePackage
FileObserverTest.javaAPI DocAndroid 5.1 API4458Thu Mar 12 22:22:12 GMT 2015android.os

FileObserverTest

public class FileObserverTest extends android.test.AndroidTestCase

Fields Summary
private Observer
mObserver
private File
mTestFile
Constructors Summary
Methods Summary
private java.lang.StringgetEventString(int event)

        switch (event) {
            case  FileObserver.ACCESS:
                return "ACCESS";
            case FileObserver.MODIFY:
                return "MODIFY";
            case FileObserver.ATTRIB:
                return "ATTRIB";
            case FileObserver.CLOSE_WRITE:
                return "CLOSE_WRITE";
            case FileObserver.CLOSE_NOWRITE:
                return "CLOSE_NOWRITE";
            case FileObserver.OPEN:
                return "OPEN";
            case FileObserver.MOVED_FROM:
                return "MOVED_FROM";
            case FileObserver.MOVED_TO:
                return "MOVED_TO";
            case FileObserver.CREATE:
                return "CREATE";
            case FileObserver.DELETE:
                return "DELETE";
            case FileObserver.DELETE_SELF:
                return "DELETE_SELF";
            case FileObserver.MOVE_SELF:
                return "MOVE_SELF";
            default:
                return "UNKNOWN";
        }
    
protected voidsetUp()

        mTestFile = File.createTempFile(".file_observer_test", ".txt");
    
protected voidtearDown()

        if (mTestFile != null && mTestFile.exists()) {
            mTestFile.delete();
        }
    
public voidtestRun()

        // make file changes and wait for them
        assertTrue(mTestFile.exists());
        assertNotNull(mTestFile.getParent());

        mObserver = new Observer(mTestFile.getParent());
        mObserver.startWatching();

        FileOutputStream out = new FileOutputStream(mTestFile);
        try {
            out.write(0x20);
            waitForEvent(); // open
            waitForEvent(); // modify

            mTestFile.delete();
            waitForEvent(); // modify
            waitForEvent(); // delete

            mObserver.stopWatching();

            // Ensure that we have seen at least 3 events.
            assertTrue(mObserver.totalEvents > 3);
        } finally {
            out.close();
        }
    
private voidwaitForEvent()

        synchronized (mObserver) {
            boolean done = false;
            while (!done) {
                try {
                    mObserver.wait(2000);
                    done = true;
                } catch (InterruptedException e) {
                }
            }

            Iterator<Map> it = mObserver.events.iterator();

            while (it.hasNext()) {
                Map map = it.next();
                Log.i("FileObserverTest", "event: " + getEventString((Integer)map.get("event")) + " path: " + map.get("path"));
            }

            mObserver.events.clear();
        }