Example usage for android.os FileObserver FileObserver

List of usage examples for android.os FileObserver FileObserver

Introduction

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

Prototype

public FileObserver(String path, int mask) 

Source Link

Document

Create a new file observer for a certain file or directory.

Usage

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;/*from  ww  w.j  a v  a 2  s  .  c o  m*/
        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:org.protocoderrunner.apprunner.api.PFileIO.java

@ProtoMethod(description = "Observer file changes in a folder", example = "")
@ProtoMethodParam(params = { "path", "function(action, file" })
public void observeFolder(String path, final FileObserverCB callback) {

    fileObserver = new FileObserver(
            ProjectManager.getInstance().getCurrentProject().getStoragePath() + "/" + path,
            FileObserver.CREATE | FileObserver.MODIFY | FileObserver.DELETE) {

        @Override//from   w w w  .j  a v a2 s .  c  o  m
        public void onEvent(int event, String file) {

            if ((FileObserver.CREATE & event) != 0) {
                callback.event("create", file);
            } else if ((FileObserver.DELETE & event) != 0) {
                callback.event("delete", file);
            } else if ((FileObserver.MODIFY & event) != 0) {
                callback.event("modify", file);
            }
        }

    };
    fileObserver.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/*from   w  ww  . j av a2 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.alexlionne.apps.avatars.Utils.DirectoryChooserFragment.java

/**
 * Sets up a FileObserver to watch the current directory.
 *//*from  w w  w.  j  a v a2  s  .c  om*/
private FileObserver createFileObserver(String path) {
    return new FileObserver(path,
            FileObserver.CREATE | FileObserver.DELETE | FileObserver.MOVED_FROM | FileObserver.MOVED_TO) {

        @Override
        public void onEvent(int event, String path) {
            debug("FileObserver received event %d", event);
            final Activity activity = getActivity();

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

From source file:com.andrada.sitracker.ui.fragment.DirectoryChooserFragment.java

/**
 * Sets up a FileObserver to watch the current directory.
 *//*ww w .  ja  v  a  2s.com*/
@NotNull
private FileObserver createFileObserver(String path) {
    return new FileObserver(path,
            FileObserver.CREATE | FileObserver.DELETE | FileObserver.MOVED_FROM | FileObserver.MOVED_TO) {

        @Override
        public void onEvent(int event, String path) {
            debug("FileObserver received event %d", event);
            final Activity activity = getActivity();

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

From source file:org.protocoderrunner.apprunner.AppRunnerFragment.java

public void startFileObserver() {

    if (mIsProjectLoaded) {

        // set up mContext file observer to watch this directory on sd card
        fileObserver = new FileObserver(mCurrentProject.getStoragePath(),
                FileObserver.CREATE | FileObserver.DELETE) {

            @Override//from  ww w . ja v a 2s  .  c  om
            public void onEvent(int event, String file) {
                JSONObject msg = new JSONObject();
                String action = null;

                if ((FileObserver.CREATE & event) != 0) {
                    MLog.d(TAG, "created " + file);
                    action = "new_files_in_project";

                } else if ((FileObserver.DELETE & event) != 0) {
                    MLog.d(TAG, "deleted file " + file);
                    action = "deleted_files_in_project";
                }

                try {
                    msg.put("action", action);
                    msg.put("type", "ide");
                    IDEcommunication.getInstance(mActivity).send(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        };
    }

}