我有一个应用程序可以在 Asynctask 中下载多个文件(并检查下载速度)。但是,当我连接到 3G(并且有切换)或设备从 WiFi 切换到 3G 时,我的应用程序冻结,我无法处理这个问题
@Override
protected Integer doInBackground(String... sUrl) {
try {
speed=0; //initial value
int i=0;
while ((i<sUrl.length)) {
URL url = new URL(sUrl[i]);
URLConnection connection = url.openConnection();
connection.setReadTimeout(10000);
connection.connect();
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024*1024]; //1MB buffer
long total = 0;
int count;
long start = System.currentTimeMillis();
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
long finish = System.currentTimeMillis();
long tempSpeed= (fileLength *8)/(finish-start);
if (tempSpeed>speed) {
speed=tempSpeed;
}
output.flush();
output.close();
input.close(); // connection is closed
i++;
}
}catch(SocketTimeoutException e) {
exceptions.add(e);
messageProgressDialog.setCancelable(true);
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(gui.getActivity()).create();
alertDialog.setTitle("Network problem");
alertDialog.setMessage("connection dropped");
alertDialog.show();
} catch (IOException e) {
exceptions.add(e);
messageProgressDialog.setCancelable(true);
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(gui.getActivity()).create();
alertDialog.setTitle("IOException");
alertDialog.setMessage("IOException error");
alertDialog.show();
} catch(Exception e) {
exceptions.add(e);
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(gui.getActivity()).create();
alertDialog.setTitle("Exception");
alertDialog.setMessage("Exception error");
alertDialog.show();
}
return 1;
}
我已经阅读了很多关于 stackoverflow 的主题,但是没有一个可以帮助我解决我在应用程序中遇到的问题。我有 try/catch 子句,但似乎没有什么不同。当我使用 3G 并且手机连接到另一根天线时,或者出现网络问题时,应用程序冻结。我能做些什么 ?
我发现了问题。这是InputStream input = new BufferedInputStream(url.openStream());
我用作输入流的这一行 url。我用这行替换它:InputStream input = new BufferedInputStream(connection.getInputStream());
现在它似乎工作得更好,当它超时时,应用程序崩溃。
}catch(SocketTimeoutException e) {
String erro=Integer.toString(count);
Log.d("error socketTimeout",erro);//1st log
exceptions.add(e);
onPostExecute(1);
Log.d("error sockteTimeout", "here"); //2nd log to see if onPostExecute worked
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(gui.getActivity()).create();
alertDialog.setTitle("Network problem");
alertDialog.setMessage("connection dropped");
alertDialog.show();
这是我使用的捕获。似乎当我尝试在 catch 子句中调用 onPostExecute 方法时,我的应用程序崩溃了。
protected void onPostExecute(Integer result) {
Log.d("onpost was called", "here");
messageProgressDialog.setMessage("Your speed is: " + speed +" KBit/sec");
messageProgressDialog.setCancelable(true);
}
查看日志查看器,仅显示第一个日志。调用 onPostExecute 时,应用程序崩溃。onPostExecute 从未实际执行。有任何想法吗?