2013-06-26 58 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(); –

相關問題