0

我正在开发我的第一个 Android 应用程序,但我似乎无法使其正常工作。此应用程序应在单击时从站点(在本例中为我的个人站点)下载文件(具体而言是 pdf)并将其保存在 SDCard 上。我环顾四周,发现我应该为此使用 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 相关的问题。

4

3 回答 3

0

试试..这个

而不是 catch 语句

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

捕获特定异常,例如 IOEXCEPTION 或任何其他异常,因为

catch(Exception e)

声明异步任务捕获所有已发生的异常

于 2013-04-08T09:48:39.113 回答
0

您的清单中有错误。没有这样的标签<user-permission>,将其更改为<uses-permission>

如果这无助于更改您connection的声明HttpURLConnection并像这样使用它:

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

我不认为它真的很重要,但是我以这种方式使用它并且它每次都有效(根据声明的协议方案,可能需要转换为 HttpsURLConnection)。

于 2013-04-08T12:37:25.087 回答
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;
}

}

于 2013-04-08T18:37:42.780 回答