当我尝试从 URL 下载文件时,我在使用 Android 4.0 或更高版本时遇到问题,它在 Android Galaxy Y 2.3/2.2 中工作正常,但当我对 Galaxy S3(4.1.1) 使用相同的代码时,它会正常工作。 2) 下载开始但未完成。
代码:
public void update() {
Log.d(TAG, "Método para fazer a atualização iniciado.");
try {
Log.d(TAG, "Conectando com a internet...");
URL url = new URL(
url);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
Log.d(TAG, "Iniciando arquivo...");
String PATH = Environment.getExternalStorageDirectory()
+ "/test/Update/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "test.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
Log.d(TAG, "Iniciando Stream...");
InputStream is = c.getInputStream();
Log.d(TAG, "Iniciando o download...");
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Log.d(TAG, "Iniciando instalador...");
final Intent promptInstall = new Intent(Intent.ACTION_VIEW);
promptInstall.setDataAndType(Uri.fromFile(new File(PATH + "test.apk")),"application/vnd.android.package-archive");
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(promptInstall);
Log.d(TAG, "Instalador iniciado com sucesso!");
} catch (MalformedURLException e) {
Log.e(TAG, "Malformed URL. Mensagem: " + e.getMessage()
+ " Causa: " + e.getCause());
} catch (IOException e) {
Log.e(TAG, "IOException. Mensagem: " + e.getMessage() + " Causa: "
+ e.getCause());
} catch (Exception e) {
Log.e(TAG, "Exception. Mensagem: " + e.getMessage() + " Causa: "
+ e.getCause());
}
}
观察:没有错误,只是开始下载然后停止。 文件大小:126,188 字节,Galaxy S3 为 6,403 字节
最佳答案
使用AsyncTask提出您的请求。
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
关于java - android 4.0/4.1.2 下载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14319335/