出于某种原因,每次用户在使用 3g 数据时单击下载按钮时,屏幕都会完全变黑,并且应用会请求强制关闭。
private final String PATH = Environment.getExternalStorageDirectory() + "/folder";
public void DownloadFromUrl(String fileName, String saveTo) {
try {
URL url = new URL("http://example.com/" + fileName + ".png");
File file = new File(fileName + ".png");
long startTime = System.currentTimeMillis();
URLConnection urlconnection = url.openConnection();
InputStream iS = urlconnection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(iS);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(PATH + saveTo);
fos.write(baf.toByteArray());
fos.close();
Toast t= Toast.makeText(getApplicationContext(), "Downloaded '" + saveTo + "' to '" + PATH + "'.", Toast.LENGTH_SHORT);
t.show();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
最佳答案
因为您正在通过长时间运行的操作阻塞 UI 线程。
相反,尝试在后台线程中发出请求,Handler , Service , IntentService , AsyncTask ,或其他东西,这样 UI 线程就不会卡住。
关于android - 为什么应用程序在超过 3g 而不是通过 WiFi 下载时崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13638739/