我正在尝试通过单击更新按钮来下载 android apk 文件。我已经使用 Async Task 在后台执行该过程。
在手机的 Sdcard/Download 中创建了一个新文件ec.apk
,但没有下载文件。文件大小 = 0 字节。我还使用fos.flush()
方法使缓冲区为空。
if(v==btUpdate){
UpdateApp atualizaApp=new UpdateApp();
atualizaApp.setContext(getApplicationContext());
atualizaApp.execute("http://mobileapp.abc.org/e-mobapps/ec.apk");
}
public class UpdateApp extends AsyncTask<String,Void,Void>{
private Context context;
public void setContext(Context contextf){
context = contextf;
}
@Override
protected Void doInBackground(String... arg0) {
try {
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/download/");
file.mkdirs();
File outputFile = new File(file, "ec.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/download/" + "ec.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
context.startActivity(intent);
} catch (Exception e) {
Log.e("UpdateAPP", "Update error! " + e.getMessage());
}
return null;
}