【问题标题】:Android: Unbuffered IOAndroid:无缓冲 IO
【发布时间】:2011-12-19 00:40:47
【问题描述】:

我想使用非阻塞 IO 从后台进程读取流/输出。谁能给我一个关于如何在 Android 上使用非阻塞 IO 的示例?

感谢您的帮助。

【问题讨论】:

  • 您的标题与您的帖子不一致。你说的是非缓冲 I/O 还是非阻塞 I/O?

标签: java android


【解决方案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);

还有选择器方法,这里有一些关于选择器、通道和线程的很棒的 (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/

【讨论】:

  • WritableByteChannel.write() 在我的情况下仍然阻塞。
  • 这不是非阻塞实现。
【解决方案2】:

在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 开发者网站中找到。

【讨论】:

    猜你喜欢
    • 2014-09-12
    • 2010-11-29
    • 2011-07-11
    • 2012-07-08
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多