[英]Cannot get InputStream from URL inside AsyncTask after application closes
我有一个简单的AyncTask,我从URL中获取字节:
class MyAsyncTask extends AsyncTask<String, Void, ArrayList<MyObject>> {
private ProgressDialog dialog;
private FragmentActivity context;
public MyAsyncTask(FragmentActivity activity) {
context = activity;
dialog = new ProgressDialog(context);
}
protected void onPreExecute() {
this.dialog.setMessage("...");
this.dialog.show();
}
@Override
protected ArrayList<MyObject> doInBackground(String... params) {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
ArrayList<MyObject> objects = null;
try {
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
String line;
objects = new ArrayList<MyObject>();
MyObject mo = new MyObject();
while ((line = reader.readLine()) != null) {
// Process data
}
reader.close();
in.close();
} catch (Exception e) {
return null;
} finally {
if (connection != null)
connection.disconnect();
}
return objects;
}
@Override
protected void onPostExecute(ArrayList<MyObject> data) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (data == null) {
Toast.makeText(context, "fail", Toast.LENGTH_SHORT).show();
}
else {
}
}
}
此代码的问题在于,只有在打开应用程序时,它才第一次起作用。 关闭我的应用程序后,这将不再起作用。 问题出现在此行:
InputStream in = connection.getInputStream();
我根本无法获得getInputStream();
关闭我的应用程序后再次工作。 在我的AsyncTask再次启动后,它仅显示进度栏并停留在该位置。 使用LogCat,我发现它停止在该行,就像流仍在打开一样。
可能是什么问题? 关闭应用程序时,我不会收到任何异常,只有此警告:
IInputConnectionWrapper showStatusIcon on inactive InputConnection
谢谢您的帮助。
您能不能尝试在catch块中调用断开连接? 因为如果发生某些异常,Url连接将保持不断开状态。
catch (Exception e) {
if (connection != null)
connection.disconnect();
return null;
} finally {
if (connection != null)
connection.disconnect();
}
输入连接尚未关闭时,会发生此问题。 使用以下命令检查是否关闭了输入连接:
connection.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.