Example usage for android.os FileObserver CLOSE_WRITE

List of usage examples for android.os FileObserver CLOSE_WRITE

Introduction

In this page you can find the example usage for android.os FileObserver CLOSE_WRITE.

Prototype

int CLOSE_WRITE

To view the source code for android.os FileObserver CLOSE_WRITE.

Click Source Link

Document

Event type: Someone had a file or directory open for writing, and closed it

Usage

From source file:org.ado.minesync.minecraft.MinecraftWorldObserver.java

private String getFileAction(int event) {
    String fileAction = null;//from w ww .  j av  a  2s .  c  o  m
    switch (event) {
    case FileObserver.ACCESS:
        fileAction = "ACCESS";
        break;
    case FileObserver.ALL_EVENTS:
        fileAction = "ALL_EVENTS";
        break;
    case FileObserver.ATTRIB:
        fileAction = "ATTRIB";
        break;
    case FileObserver.CLOSE_NOWRITE:
        fileAction = "CLOSE_NOWRITE";
        break;
    case FileObserver.CLOSE_WRITE:
        fileAction = "CLOSE_WRITE";
        break;
    case FileObserver.CREATE:
        fileAction = "CREATE";
        break;
    case FileObserver.DELETE:
        fileAction = "DELETE";
        break;
    case FileObserver.DELETE_SELF:
        fileAction = "DELETE_SELF";
        break;
    case FileObserver.MODIFY:
        fileAction = "MODIFY";
        break;
    case FileObserver.MOVE_SELF:
        fileAction = "MOVE_SELF";
        break;
    case FileObserver.MOVED_FROM:
        fileAction = "MOVED_FROM";
        break;
    case FileObserver.MOVED_TO:
        fileAction = "MOVED_TO";
        break;
    case FileObserver.OPEN:
        fileAction = "OPEN";
        break;
    }
    return fileAction;
}

From source file:com.owncloud.android.services.observer.InstantUploadsObserver.java

/**
 * Receives and processes events about updates of the monitored folder.
 *
 * This is almost heuristic. Do no expect it works magically with any camera.
 *
 * For instance, Google Camera creates a new video file when the user enters in "video mode", before
 * start to record, and saves it empty if the user leaves recording nothing. True store. Life is magic.
 *
 * @param event     Kind of event occurred.
 * @param path      Relative path of the file referred by the event.
 *///  w  w  w.  j av a  2 s  .  c  om
@Override
public void onEvent(int event, String path) {
    Log_OC.d(TAG, "Got event " + event + " on FOLDER " + mConfiguration.getSourcePath() + " about "
            + ((path != null) ? path : "") + " (in thread '" + Thread.currentThread().getName() + "')");

    if (path != null && path.length() > 0) {
        synchronized (mLock) {
            if ((event & FileObserver.CREATE) != 0) {
                // new file created, let's watch it; false -> not modified yet
                mObservedChildren.put(path, false);
            }
            if (((event & FileObserver.MODIFY) != 0) && mObservedChildren.containsKey(path)
                    && !mObservedChildren.get(path)) {
                // watched file was written for the first time after creation
                mObservedChildren.put(path, true);
            }
            if ((event & FileObserver.CLOSE_WRITE) != 0 && mObservedChildren.containsKey(path)
                    && mObservedChildren.get(path)) {
                // a file that was previously created and written has been closed;
                // testing for FileObserver.MODIFY is needed because some apps
                // close the video file right after creating it when the recording
                // is started, and reopen it to write with the first chunk of video
                // to save; for instance, Camera MX does so.
                mObservedChildren.remove(path);
                handleNewFile(path);
            }
            if ((event & FileObserver.MOVED_TO) != 0) {
                // a file has been moved or renamed into the folder;
                // for instance, Google Camera does so right after
                // saving a video recording
                handleNewFile(path);
            }
        }
    }

    if ((event & IN_IGNORE) != 0 && (path == null || path.length() == 0)) {
        Log_OC.d(TAG, "Stopping the observance on " + mConfiguration.getSourcePath());
    }
}

From source file:com.sat.sonata.MenuActivity.java

private void processPictureWhenReady(final String picturePath) {
    final File pictureFile = new File(picturePath);

    if (pictureFile.exists()) {
        // The picture is ready; process it.
    } else {//  w  w w .j a  v a  2s  .com
        // The file does not exist yet. Before starting the file observer, you
        // can update your UI to let the user know that the application is
        // waiting for the picture (for example, by displaying the thumbnail
        // image and a progress indicator).

        final File parentDirectory = pictureFile.getParentFile();
        FileObserver observer = new FileObserver(parentDirectory.getPath()) {
            // Protect against additional pending events after CLOSE_WRITE is
            // handled.
            private boolean isFileWritten;

            @Override
            public void onEvent(int event, String path) {
                if (!isFileWritten) {
                    // For safety, make sure that the file that was created in
                    // the directory is actually the one that we're expecting.
                    File affectedFile = new File(parentDirectory, path);
                    isFileWritten = (event == FileObserver.CLOSE_WRITE && affectedFile.equals(pictureFile));

                    if (isFileWritten) {
                        stopWatching();

                        // Now that the file is ready, recursively call
                        // processPictureWhenReady again (on the UI thread).
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                processPictureWhenReady(picturePath);
                            }
                        });
                    }
                }
            }
        };
        observer.startWatching();
    }
}

From source file:com.glasshack.checkmymath.CheckMyMath.java

private void processPictureWhenReady(final String picturePath) {
    final File pictureFile = new File(picturePath);

    if (pictureFile.exists()) {
        // The picture is ready; process it.
        Log.e("Picture Path", picturePath);
        List<NameValuePair> postData = new ArrayList<NameValuePair>();
        postData.add(new BasicNameValuePair("file", picturePath));
        postData.add(new BasicNameValuePair("answer", "1"));
        postData.add(new BasicNameValuePair("submit", "Submit"));
        String postResp = post("http://54.187.58.53/glassmath.php", postData);
        evaluateResponse(postResp);//from w ww.  j a v a 2  s  .c  o m
    } else {
        // The file does not exist yet. Before starting the file observer, you
        // can update your UI to let the user know that the application is
        // waiting for the picture (for example, by displaying the thumbnail
        // image and a progress indicator).

        final File parentDirectory = pictureFile.getParentFile();
        FileObserver observer = new FileObserver(parentDirectory.getPath(),
                FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) {
            // Protect against additional pending events after CLOSE_WRITE
            // or MOVED_TO is handled.
            private boolean isFileWritten;

            @Override
            public void onEvent(int event, String path) {
                if (!isFileWritten) {
                    // For safety, make sure that the file that was created in
                    // the directory is actually the one that we're expecting.
                    File affectedFile = new File(parentDirectory, path);
                    isFileWritten = affectedFile.equals(pictureFile);

                    if (isFileWritten) {
                        stopWatching();

                        // Now that the file is ready, recursively call
                        // processPictureWhenReady again (on the UI thread).
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                processPictureWhenReady(picturePath);
                            }
                        });
                    }
                }
            }
        };
        observer.startWatching();
    }
}

From source file:com.lovejoy777sarootool.rootool.fragments.BrowserFragment.java

@Override
public void onEvent(int event, String path) {
    // this will automatically update the directory when an action like this
    // will be performed
    switch (event & FileObserver.ALL_EVENTS) {
    case FileObserver.CREATE:
    case FileObserver.CLOSE_WRITE:
    case FileObserver.MOVE_SELF:
    case FileObserver.MOVED_TO:
    case FileObserver.MOVED_FROM:
    case FileObserver.ATTRIB:
    case FileObserver.DELETE:
    case FileObserver.DELETE_SELF:
        sHandler.removeCallbacks(mLastRunnable);
        sHandler.post(mLastRunnable = new NavigateRunnable(path));
        break;//from   w w w.ja  v a 2  s .c  o m
    }
}

From source file:com.luyaozhou.recognizethisforglass.ViewFinder.java

private void processPictureWhenReady(final String picturePath) {
    final File pictureFile = new File(picturePath);
    //Map<String, String > result = new HashMap<String,String>();

    if (pictureFile.exists()) {
        // The picture is ready; process it.
        Bitmap imageBitmap = null;/*  ww w . j  a  v  a2  s.  c  om*/
        try {
            //               Bundle extras = data.getExtras();
            //               imageBitmap = (Bitmap) extras.get("data");
            FileInputStream fis = new FileInputStream(picturePath); //get the bitmap from file
            imageBitmap = (Bitmap) BitmapFactory.decodeStream(fis);

            if (imageBitmap != null) {
                Bitmap lScaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 1600, 1200, false);
                if (lScaledBitmap != null) {
                    imageBitmap.recycle();
                    imageBitmap = null;

                    ByteArrayOutputStream lImageBytes = new ByteArrayOutputStream();
                    lScaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, lImageBytes);
                    lScaledBitmap.recycle();
                    lScaledBitmap = null;

                    byte[] lImageByteArray = lImageBytes.toByteArray();

                    HashMap<String, String> lValuePairs = new HashMap<String, String>();
                    lValuePairs.put("base64Image", Base64.encodeToString(lImageByteArray, Base64.DEFAULT));
                    lValuePairs.put("compressionLevel", "30");
                    lValuePairs.put("documentIdentifier", "DRIVER_LICENSE_CA");
                    lValuePairs.put("documentHints", "");
                    lValuePairs.put("dataReturnLevel", "15");
                    lValuePairs.put("returnImageType", "1");
                    lValuePairs.put("rotateImage", "0");
                    lValuePairs.put("data1", "");
                    lValuePairs.put("data2", "");
                    lValuePairs.put("data3", "");
                    lValuePairs.put("data4", "");
                    lValuePairs.put("data5", "");
                    lValuePairs.put("userName", "zbroyan@miteksystems.com");
                    lValuePairs.put("password", "google1");
                    lValuePairs.put("phoneKey", "1");
                    lValuePairs.put("orgName", "MobileImagingOrg");

                    String lSoapMsg = formatSOAPMessage("InsertPhoneTransaction", lValuePairs);

                    DefaultHttpClient mHttpClient = new DefaultHttpClient();
                    //                        mHttpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.R)
                    HttpPost mHttpPost = new HttpPost();

                    mHttpPost.setHeader("User-Agent", "UCSD Team");
                    mHttpPost.setHeader("Content-typURIe", "text/xml;charset=UTF-8");
                    //mHttpPost.setURI(URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx?op=InsertPhoneTransaction"));
                    mHttpPost.setURI(
                            URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx"));

                    StringEntity se = new StringEntity(lSoapMsg, HTTP.UTF_8);
                    se.setContentType("text/xml; charset=UTF-8");
                    mHttpPost.setEntity(se);
                    HttpResponse mResponse = mHttpClient.execute(mHttpPost, new BasicHttpContext());

                    String responseString = new BasicResponseHandler().handleResponse(mResponse);
                    parseXML(responseString);

                    //Todo: this is test code. Need to be implemented
                    //result = parseXML(testStr);
                    Log.i("test", "test:" + " " + responseString);
                    Log.i("test", "test: " + " " + map.size());

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // this part will be relocated in order to let the the server process picture
        if (map.size() == 0) {
            Intent display = new Intent(getApplicationContext(), DisplayInfoFailed.class);
            display.putExtra("result", (java.io.Serializable) iQAMsg);
            startActivity(display);
        } else {
            Intent display = new Intent(getApplicationContext(), DisplayInfo.class);
            display.putExtra("result", (java.io.Serializable) map);
            startActivity(display);

        }
    } else {
        // The file does not exist yet. Before starting the file observer, you
        // can update your UI to let the user know that the application is
        // waiting for the picture (for example, by displaying the thumbnail
        // image and a progress indicator).

        final File parentDirectory = pictureFile.getParentFile();
        FileObserver observer = new FileObserver(parentDirectory.getPath(),
                FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) {
            // Protect against additional pending events after CLOSE_WRITE
            // or MOVED_TO is handled.
            private boolean isFileWritten;

            @Override
            public void onEvent(int event, final String path) {
                if (!isFileWritten) {
                    // For safety, make sure that the file that was created in
                    // the directory is actually the one that we're expecting.
                    File affectedFile = new File(parentDirectory, path);
                    isFileWritten = affectedFile.equals(pictureFile);

                    if (isFileWritten) {
                        stopWatching();
                        // Now that the file is ready, recursively call
                        // processPictureWhenReady again (on the UI thread).
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new LongOperation().execute(picturePath);
                            }
                        });
                    }
                }
            }
        };
        observer.startWatching();

    }

}

From source file:com.veniosg.dir.android.fragment.FileListFragment.java

private FileObserver generateFileObserver(String pathToObserve) {
    return new FileObserver(pathToObserve, FileObserver.CREATE | FileObserver.DELETE | FileObserver.CLOSE_WRITE // Removed since in case of continuous modification
                                                                                                                // (copy/compress) we would flood with events.
            | FileObserver.MOVED_FROM | FileObserver.MOVED_TO) {
        private static final long MIN_REFRESH_INTERVAL = 2 * 1000;

        private long lastUpdate = 0;

        @Override/*ww w  .  java 2 s  .c  om*/
        public void onEvent(int event, String path) {
            if (System.currentTimeMillis() - lastUpdate <= MIN_REFRESH_INTERVAL || event == 32768) { // See https://code.google.com/p/android/issues/detail?id=29546
                return;
            }

            Logger.logV(Logger.TAG_OBSERVER, "Observed event " + event + ", refreshing list..");
            lastUpdate = System.currentTimeMillis();

            if (getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refresh();
                    }
                });
            }
        }
    };
}

From source file:com.dnielfe.manager.Browser.java

@Override
public void onEvent(int event, String path) {
    // this will automatically update the directory when an action like this
    // will be performed
    switch (event & FileObserver.ALL_EVENTS) {
    case FileObserver.CREATE:
    case FileObserver.CLOSE_WRITE:
    case FileObserver.MOVE_SELF:
    case FileObserver.MOVED_TO:
    case FileObserver.MOVED_FROM:
    case FileObserver.ATTRIB:
    case FileObserver.DELETE:
    case FileObserver.DELETE_SELF:
        sHandler.removeCallbacks(mLastRunnable);
        sHandler.post(mLastRunnable = new NavigateRunnable(mCurrentPath));
        break;/*from w ww.  j  a  v a 2  s  .  co m*/
    }
}