简体   繁体   English

无法以编程方式下载.apk文件

[英]Unable to download .apk file programmatically

I am trying to download an android apk file by clicking on update button. 我正在尝试通过单击更新按钮来下载一个android apk文件。 I have used Async Task to carry out the process in background. 我使用异步任务在后台执行该过程。

A new file ec.apk is created in phone's Sdcard/Download but file is not downloaded. 在手机的SD卡/下载中创建了一个新文件ec.apk ,但未下载文件。 File size = 0 bytes. 文件大小= 0字节。 I also used fos.flush() method to make buffer empty. 我还使用了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;
  }

I also used fos.flush() method to make buffer empty. 我还使用了fos.flush()方法来使缓冲区为空。

That is insufficient if you are trying to use the file immediately, as you appear to be doing here. 如果您尝试立即使用该文件,那是不够的,就像您在这里所做的那样。 You also need to call getFD().sync() on the FileOutputStream before close() , so the OS buffers get flushed to disk. 您还需要在close()之前在FileOutputStream上调用getFD().sync() close() ,以便将OS缓冲区刷新到磁盘。 See this Android Developers Blog post for more. 有关更多信息,请参见此Android开发者博客文章。

Beyond that, you might wish to use the three-parameter e() method, so you get the full stack trace, then double-check LogCat to see if you are encountering any problems. 除此之外,您可能希望使用三参数e()方法,以便获得完整的堆栈跟踪,然后再次检查LogCat以查看是否遇到任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM