Android:无缓冲的IO

时间:2010-09-12 04:34:46

标签: java android

我想使用非阻塞IO来读取后台进程的流/输出。任何人都可以举例说明如何在Android上使用非阻塞IO?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

以下是the class I use从互联网下载文件或复制文件系统中的文件以及我如何使用它:

// 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);

还有Selector方法,这里有一些关于选择器,通道和线程的优秀(Java)教程:

  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/

答案 1 :(得分:1)

后台操作可以​​在Android中以多种方式完成。我建议你使用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
  }
}

然后你执行它:

public void onClick(View v) {
   new LongOperation().execute("");
}

参考:xoriant.com

在doInBackground方法中,您可以放置​​文件访问内容。 可以在android开发者站点找到文件访问的参考。