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/files
new DownloadFile(ctxt, "http://yourfile", ctxt.openFileOutput("destinationfile.ext", Context.MODE_PRIVATE));
// Copy a file from raw resource to the files directory as above
InputStream in = ctxt.getResources().openRawResource(R.raw.myfile);
OutputStream out = ctxt.openFileOutput("filename.ext", Context.MODE_PRIVATE);
final ReadableByteChannel ic = Channels.newChannel(in);
final WritableByteChannel oc = Channels.newChannel(out);
DownloadFile.fastChannelCopy(ic, oc);
There also is the Selector approach, here are some great (Java) tutorials about Selectors, Channels and Threads:
- http://jfarcand.wordpress.com/2006/05/30/tricks-and-tips-with-nio-part-i-why-you-must-handle-op_write
- http://jfarcand.wordpress.com/2006/07/06/tricks-and-tips-with-nio-part-ii-why-selectionkey-attach-is-evil/
- http://jfarcand.wordpress.com/2006/07/07/tricks-and-tips-with-nio-part-iii-to-thread-or-not-to-thread/
- http://jfarcand.wordpress.com/2006/07/19/httpweblogs-java-netblog20060719tricks-and-tips-nio-part-iv-meet-selectors/
- 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:
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// perform long running operation operation
return null;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For example showing ProgessDialog
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
@Override
protected void onProgressUpdate(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:
public void onClick(View v) {
new LongOperation().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"