2013-04-08 32 views
0

我正在處理我的第一個Android應用程序,但似乎無法使其正常工作。這個應用程序應該從網站(在這種情況下,我的個人網站)下載一個文件(一個pdf,具體),並將其保存在SD卡上。 我看了看這裏四周,發現我應該使用的AsyncTask用於此目的,這是我想出了代碼:AsyncTask無法從外部網站下載文件

package it.uniroma3.tirocinioandroid; 

import java.io.BufferedInputStream; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.URL; 
import java.net.URLConnection; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Environment; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 

public class MainActivity extends Activity implements OnClickListener { 

    private Button dlbutton; 
    private ProgressDialog mProgressDialog; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     dlbutton = (Button) findViewById(R.id.dlbutton); 
     dlbutton.setOnClickListener(this); 
     mProgressDialog = new ProgressDialog(MainActivity.this); 
     mProgressDialog.setMessage("Currently downloading..."); 
     mProgressDialog.setIndeterminate(false); 
     mProgressDialog.setMax(100); 
     mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     Log.i("Main", "finito onCreate"); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     //TODO sistemare il menù 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 


    @Override 
    public void onClick(View v) { 
     switch (v.getId()) 
     { 
     case R.id.dlbutton: 
      DownloadFile downloadFile = new DownloadFile(); 
      downloadFile.execute("http://dragon-nest.net/catalogo.pdf"); 
      Log.i("Main", "finito onClik"); 
      break; 
     } 

    } 

    private class DownloadFile extends AsyncTask<String, Integer, String> { 
     @Override 
     protected String doInBackground(String... sUrl) { 
      try { 
       URL url = new URL(sUrl[0]); 
       URLConnection connection = url.openConnection(); 
       connection.connect(); 
       Log.i("Main", "connected"); 
       // this will be useful so that you can show a typical 0-100% progress bar 
       int fileLength = connection.getContentLength(); 

       // download the file 
       InputStream input = new BufferedInputStream(url.openStream()); 
       Log.i("Main", "input set"); 
       OutputStream output = new FileOutputStream(Environment.getDataDirectory().getAbsolutePath().concat("download/catalogo.pdf")); 
       Log.i("Main", "output set"); 

       byte data[] = new byte[1024]; 
       long total = 0; 
       int count; 
       while ((count = input.read(data)) != -1) { 
        total += count; 
        // publishing the progress.... 
        publishProgress((int) (total * 100/fileLength)); 
        output.write(data, 0, count); 
       } 

       output.flush(); 
       output.close(); 
       input.close(); 
      }catch(Exception e){ 
        Log.e("ERROR_TAG", e.getMessage()); 
        return "fine"; 
       } 
      String s ="fine"; 
      Log.i("Main", "end download"); 
      return s; 
     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      mProgressDialog.show(); 
      Log.i("Main", "end preExecute"); 
     } 

     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 
      mProgressDialog.dismiss(); 
      Log.i("Main", "end postExecute"); 
     } 

     @Override 
     protected void onProgressUpdate(Integer... progress) { 
      super.onProgressUpdate(progress); 
      mProgressDialog.setProgress(progress[0]); 
      Log.i("Main", "update..."); 
     } 


    } 
} 

然而,這似乎是無法連接到該網站開始下載。從Logcat中可以看出,它在嘗試連接時會產生一個異常,在下載真正開始之前會被捕獲並阻塞所有內容。

這裏也是清單的應用:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="it.uniroma3.tirocinioandroid" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="17" /> 

    <user-permission android:name="android.permission.INTERNET" /> 
    <user-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name="it.uniroma3.tirocinioandroid.MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <activity 
      android:name="it.uniroma3.tirocinioandroid.FileDownloader" 
      android:label="@string/title_activity_file_downloader" > 
     </activity> 
    </application> 

</manifest> 

順便說一句,我想看看,也許這是我的地盤行事古怪,但我可以從瀏覽器就好了下載文件。我也嘗試從另一個網站的另一個文件,但我得到同樣的問題。 AVD和我的平板電腦都出現這種情況,所以我不認爲這是AVD相關的問題。

+1

你做了什麼異常?請把這個堆棧跟蹤。而且,如果您下載的網站位於https://請讓我知道。 – Darpan 2013-04-08 09:41:25

回答

0

有您的Manifest中出現錯誤。沒有<user-permission>等標籤,請將其更改爲<uses-permission>

如果這不會幫助你的connectionHttpURLConnection的變化申報和使用它像這樣:

HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 

我不認爲這真的很重要,我卻用它的方式和它的作品每時間(根據聲明的協議方案,可能需要轉換爲HttpsURLConnection)。

+0

你是完全正確的,我拼寫的權限,感謝您指出,它現在工作正常! – AdK 2013-04-10 13:30:27

0

試試..這出

相反catch語句的

catch(Exception e){ 
       Log.e("ERROR_TAG", e.getMessage()); 
       return "fine"; 
      } 

捕捉特定的異常,如IOException異常或其他任何異常,因爲由

catch(Exception e) 

聲明異步任務捕獲所有發生的異常

+0

感謝您的回答,它幫助我找到修復此問題並解決問題後得到的另一個錯誤。 – AdK 2013-04-10 13:38:59

0

此代碼與我合作!

protected class myClass extends AsyncTask{ 
    @Override 
protected Object doInBackground(Object... arg0) { 
    // TODO Auto-generated method stub 
    try{ 

     File cacheDir = new File(android.os.Environment.getExternalStorageDirectory(),"FolderName"); 
     if(!cacheDir.exists()) 
      cacheDir.mkdirs(); 
     File f=new File(cacheDir,"q.mp3"); 
     text1.setText("file"); 
     URL url = new URL("your link"); 
     InputStream input = new BufferedInputStream(url.openStream()); 
     OutputStream output = new FileOutputStream(f); 

        byte data[] = new byte[1024]; 
        long total = 0; 
        int count=0; 
           while ((count = input.read()) != -1) { 
         total++; 
         Log.e("while","A"+total); 

         output.write(data, 0, count); 
        } 

        output.flush(); 
        output.close(); 
        input.close(); 

     } 

    catch (Exception e) { 
        e.printStackTrace();} 

    return null; 
} 

}