【发布时间】:2011-12-19 00:40:47
【问题描述】:
我想使用非阻塞 IO 从后台进程读取流/输出。谁能给我一个关于如何在 Android 上使用非阻塞 IO 的示例?
感谢您的帮助。
【问题讨论】:
-
您的标题与您的帖子不一致。你说的是非缓冲 I/O 还是非阻塞 I/O?
我想使用非阻塞 IO 从后台进程读取流/输出。谁能给我一个关于如何在 Android 上使用非阻塞 IO 的示例?
感谢您的帮助。
【问题讨论】:
这里是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) 教程:
【讨论】:
WritableByteChannel.write() 在我的情况下仍然阻塞。
在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 开发者网站中找到。
【讨论】: