Skip to content Skip to sidebar Skip to footer

Android: Unbuffered Io

I want to use an Non Blocking IO to read a stream/output from a background process.Can anyone give me an example on how to use the Non Blocking IO on Android? Thanks for the help.

Solution 1:

Here is the class I use to download a file from the internet or copy a file within the filesystem and how I use it:

// Download a file to /data/data/your.app/filesnewDownloadFile(ctxt, "http://yourfile", ctxt.openFileOutput("destinationfile.ext", Context.MODE_PRIVATE));

// Copy a file from raw resource to the files directory as aboveInputStreamin= ctxt.getResources().openRawResource(R.raw.myfile);
OutputStreamout= ctxt.openFileOutput("filename.ext", Context.MODE_PRIVATE);
finalReadableByteChannelic= Channels.newChannel(in);
finalWritableByteChanneloc= Channels.newChannel(out);
DownloadFile.fastChannelCopy(ic, oc);

There also is the Selector approach, here are some great (Java) tutorials about Selectors, Channels and Threads:

  1. http://jfarcand.wordpress.com/2006/05/30/tricks-and-tips-with-nio-part-i-why-you-must-handle-op_write
  2. http://jfarcand.wordpress.com/2006/07/06/tricks-and-tips-with-nio-part-ii-why-selectionkey-attach-is-evil/
  3. http://jfarcand.wordpress.com/2006/07/07/tricks-and-tips-with-nio-part-iii-to-thread-or-not-to-thread/
  4. http://jfarcand.wordpress.com/2006/07/19/httpweblogs-java-netblog20060719tricks-and-tips-nio-part-iv-meet-selectors/
  5. http://jfarcand.wordpress.com/2006/09/21/tricks-and-tips-with-nio-part-v-ssl-and-nio-friend-or-foe/

Solution 2:

background operation can be done in many ways in Android. I suggest you to use AsyncTask:

privateclassLongOperationextendsAsyncTask<String, Void, String> {

 @OverrideprotectedStringdoInBackground(String... params) {
  // perform long running operation operationreturnnull;
 }

 /* (non-Javadoc)
  * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
  */@OverrideprotectedvoidonPostExecute(String result) {
  // execution of result of Long time consuming operation
 }

 /* (non-Javadoc)
  * @see android.os.AsyncTask#onPreExecute()
  */@OverrideprotectedvoidonPreExecute() {
 // Things to be done before execution of long running operation. For example showing ProgessDialog
 }

 /* (non-Javadoc)
  * @see android.os.AsyncTask#onProgressUpdate(Progress[])
  */@OverrideprotectedvoidonProgressUpdate(Void... values) {
      // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
  }
}

Then you execute it like this:

publicvoidonClick(View v) {
   newLongOperation().execute("");
}

reference: xoriant.com

In the doInBackground method, you can put your file access stuff. reference for file access can be found in the android developer site.

Post a Comment for "Android: Unbuffered Io"