2013-06-26 57 views
0

我正在尝试通过单击更新按钮来下载android APK文件。我使用异步任务在后台执行此过程。无法以编程方式下载.apk文件

在手机的SD卡/下载中创建了一个新文件ec.apk,但未下载文件。文件大小= 0字节。我也用​​方法使缓冲区变空。

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; 
    } 
+0

你有WRITE权限吗? – Blackbelt

+0

是的,我授予了WRITE_EXTERNAL_STORAGE –

+0

至少在每次通过while循环时记录len1的值,也可能是累计总数。这应该有助于区分不获取任何数据,而不是管理写入数据。 –

回答

0

我也使用fos.flush()方法来使缓冲器空。

如果您试图立即使用该文件,这是不够的,因为您似乎在这里执行此操作。您还需要在close()之前FileOutputStream上拨打getFD().sync(),以便OS缓冲区刷新到磁盘。详情请见this Android Developers Blog

除此之外,您可能希望使用三参数e()方法,以便获得完整的堆栈跟踪,然后仔细检查LogCat以查看是否遇到任何问题。

+0

你的意思是fos.flush(); –

+0

then fos.getFD()。sync(); –

相关问题