出于某种原因,每当用户在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/