0

什麼是我的代碼的問題:Android的下載文件無法解析包解析錯誤

@Override 
    protected String doInBackground(String... sUrl) { 

     InputStream input = null; 

     URLConnection conection = null; 
     BufferedOutputStream bout = null; 
     FileOutputStream fos = null; 

     int downloaded = 0; 

     try { 
      URL url = new URL(sUrl[0]); 
      conection = url.openConnection(); 
      //conection.connect(); 

      int lenghtOfFile = conection.getContentLength(); 


      conection = null; 
      conection = url.openConnection(); 

      if(STATUS) { 
       File file = new File(Environment.getExternalStorageDirectory().getPath() + "/myapp.apk"); 
       if (file.exists()) { 
        downloaded = (int) file.length(); 
        conection.setRequestProperty("Range", "bytes=" + (file.length()) + "-"); 
       } 
      } 
      else { 
       conection.setRequestProperty("Range", "bytes=" + downloaded + "-") 
      } 

      conection.setDoInput(true); 
      conection.setDoOutput(true); 



      input = new BufferedInputStream(url.openStream(), 8192); 

      fos=(downloaded==0)? new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/myapp.apk"): new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/myapp.apk",true); 
      bout = new BufferedOutputStream(fos, 1024); 



      byte data[] = new byte[1024]; 

      long total = 0; 
      int count = 0; 

      while ((count = input.read(data, 0, 1024)) >= 0) { 
       if (isCancelled()) { 
        input.close(); 
        return null; 
       } 

       bout.write(data, 0, count); 
       downloaded += count; 
       publishProgress((int)(downloaded * 100/ lenghtOfFile)); 
       total += count; 
      } 

     } catch (Exception e) { 
      Log.e("Error: ", e.getMessage()); 
     } finally { 
      try { 
       if (output != null) 
        output.close(); 
       if (input != null) 
        input.close(); 
       if (fos != null) 
        fos.close(); 
       if (bout != null) 
        bout.close(); 
      } catch (IOException ignored) { 
      } 

      if (conection != null) 
       conection = null; 
     } 

     return null; 
    } 

和我設置發射到通知欄時,點擊它:

notification = new NotificationCompat.Builder(MainActivity.this) 
      .setSmallIcon(R.drawable.down_icon) 
      .setOngoing(true); 



    resultIntent = new Intent(MainActivity.this, DownloadsActivity.class); 

    PendingIntent resultPendingIntent = PendingIntent.getActivity(MainActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
    notification.setContentIntent(resultPendingIntent); 

當文件完全下載和點擊通知欄我看到這個錯誤:

There is a problem parsing the package 

我的代碼問題是什麼?
在此先感謝

+0

這是您的通知還是由系統提供? – hoomi 2014-08-30 07:13:31

+0

@hoomi它是由系統,因爲我下載了一個apk文件。我認爲問題出在我的'doInBackground'方法上。 – 2014-08-30 07:26:28

+0

您是否在LogCat中遇到任何異常或警告? – hoomi 2014-08-30 07:38:33

回答

0

你試過在while循環之後添加bout.flush()嗎?也許不是所有的字節都寫入您的文件