後,我有這個簡單的AyncTask中,我從網址提取字節:無法從URL裏面的AsyncTask得到InputStream的應用程序關閉
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
謝謝你的幫助。
我認爲您錯過了關閉連接,如:connection.close()。 –