android - 尝试从我的应用程序下载 PDF 文件,但不起作用

标签 android android-asynctask download progressdialog

我是android开发的初学者,我正在开发一个项目,为此我需要使用异步任务将PDF文件从URL下载到我的手机,我还需要显示<下载文件时的strong>进度对话框。

这是我的 MainActivity.java 的运行方式..

public class MainActivity extends Activity {

    String[] listItem;
    String[] listItemURLs;
    ProgressDialog mProgressDialog;
    ListView lv;

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

        // instantiate it within the onCreate method
        mProgressDialog = new ProgressDialog(MainActivity.this);
        mProgressDialog.setMessage("Downloading file..please wait.");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        listItem = new String[] { "File 1", "File 2", "File 3", "File 4",
                "File 5", "File 6", "File 7" };
        listItemURLs = new String[] { "http://www.ztsinc.com/MBTLA2_ds.pdf",
                "http://www.ztsinc.com/MBT1_ds.pdf",
                "http://www.ztsinc.com/MINIMBT_ds.pdf",
                "http://www.ztsinc.com/MINI9R_ds.pdf",
                "http://www.ztsinc.com/MBTLA2_OI.pdf",
                "http://www.ztsinc.com/MBT1_OI.pdf",
                "http://www.ztsinc.com/MINIMBT_MINI9R_OI.pdf" };

        lv = (ListView) findViewById(R.id.listview1);
        lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_1, listItem));
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, final View view,
                    final int position, long id) {

                AlertDialog.Builder da = new AlertDialog.Builder(
                        MainActivity.this);
                da.setMessage("Do you want to download this file?");
                da.setPositiveButton("YES", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        downloadPDF downloadpdf = new downloadPDF(view,
                                position);
                        downloadpdf.execute(listItemURLs[position]);

                    }
                });

                da.setNegativeButton("No", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                da.show();
            }

        });
    }

    public class downloadPDF extends AsyncTask<String, Integer, String> {

        private View mView;
        private int mPosition;

        public downloadPDF(View view, int position) {
            mView = view;
            mPosition = position;
        }

        @Override
        public void onPreExecute() {
            super.onPreExecute();
            mProgressDialog.show();
        }

        String fileName = listItem[mPosition];
        String fileExtension=".pdf";

        @Override
        protected String doInBackground(String... sUrl) {
            try {
                URL url = new URL(sUrl[mPosition]);
                HttpURLConnection connection =(HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setDoOutput(true);
                connection.connect();

                String PATH = Environment.getExternalStorageDirectory() + "/download/";
                File file = new File(PATH);
                file.mkdirs();
                File outputFile = new File(file,fileName + fileExtension);
                FileOutputStream fos = new FileOutputStream(outputFile);
                InputStream is = connection.getInputStream();


                // this will be useful so that you can show a typical 0-100%
                // progress bar
                int fileLength = connection.getContentLength();

                // download the file

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

                fos.flush();
                fos.close();
                is.close();
            } catch (Exception e) {
            }
            return null;
        }

        public void onPostExecute(Integer... progress) {
            super.onProgressUpdate(progress);
            mProgressDialog.setProgress(progress[0]);
            Toast.makeText(MainActivity.this, "Download Complete",
                    Toast.LENGTH_SHORT).show();
            mProgressDialog.dismiss();

        }

    }
}

我的 diff_view1.xml 是这样的......

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:weightSum="1" >



    <ListView
        android:id="@+id/listview1"
        android:layout_width="fill_parent"
        android:layout_height="400dp" >

    </ListView>

    <Button
        android:id="@+id/btnDownload"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Download"
        android:layout_marginTop="30dp"/>

</LinearLayout>

我还在我的 list 中添加了互联网、SD卡写入等权限。

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

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

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="Titles/Styled (via theme)"
            android:theme="@style/StyledIndicators" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

我有一个 ListView ,其中填充了一个数组适配器,其中包含“文件 1”、“文件 2”等元素。 我正在使用“URL”(存储在数组中的 URL)作为参数来启动异步任务的对象,但是当我运行并单击任何 ListView 项时,进度条只是停留在 0%,然后什么也没有发生。谁能帮我?已经这样做了几个小时但没有成功:(

谢谢。

最佳答案

使用以下代码。

public class DownloaderThread extends Thread
{
        // constants
        private static final int DOWNLOAD_BUFFER_SIZE = 4096;

        // instance variables
        private AndroidFileDownloader parentActivity;
        private String downloadUrl;

        /**
         * Instantiates a new DownloaderThread object.
         * @param parentActivity Reference to AndroidFileDownloader activity.
         * @param inUrl String representing the URL of the file to be downloaded.
         */
        public DownloaderThread(AndroidFileDownloader inParentActivity, String inUrl)
        {
                downloadUrl = "";
                if(inUrl != null)
                {
                        downloadUrl = inUrl;
                }
                parentActivity = inParentActivity;
        }

        /**
         * Connects to the URL of the file, begins the download, and notifies the
         * AndroidFileDownloader activity of changes in state. Writes the file to
         * the root of the SD card.
         */
        @Override
        public void run()
        {
                URL url;
                URLConnection conn;
                int fileSize, lastSlash;
                String fileName;
                BufferedInputStream inStream;
                BufferedOutputStream outStream;
                File outFile;
                FileOutputStream fileStream;
                Message msg;

                // we're going to connect now
                msg = Message.obtain(parentActivity.activityHandler,
                                AndroidFileDownloader.MESSAGE_CONNECTING_STARTED,
                                0, 0, downloadUrl);
                parentActivity.activityHandler.sendMessage(msg);

                try
                {
                        url = new URL(downloadUrl);
                        conn = url.openConnection();
                        conn.setUseCaches(false);
                        fileSize = conn.getContentLength();

                        // get the filename
                        lastSlash = url.toString().lastIndexOf('/');
                        fileName = "file.bin";
                        if(lastSlash >=0)
                        {
                                fileName = url.toString().substring(lastSlash + 1);
                        }
                        if(fileName.equals(""))
                        {
                                fileName = "file.bin";
                        }

                        // notify download start
                        int fileSizeInKB = fileSize / 1024;
                        msg = Message.obtain(parentActivity.activityHandler,
                                        AndroidFileDownloader.MESSAGE_DOWNLOAD_STARTED,
                                        fileSizeInKB, 0, fileName);
                        parentActivity.activityHandler.sendMessage(msg);

                        // start download
                        inStream = new BufferedInputStream(conn.getInputStream());
                        outFile = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
                        fileStream = new FileOutputStream(outFile);
                        outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
                        byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
                        int bytesRead = 0, totalRead = 0;
                        while(!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0)
                        {
                                outStream.write(data, 0, bytesRead);

                                // update progress bar
                                totalRead += bytesRead;
                                int totalReadInKB = totalRead / 1024;
                                msg = Message.obtain(parentActivity.activityHandler,
                                                AndroidFileDownloader.MESSAGE_UPDATE_PROGRESS_BAR,
                                                totalReadInKB, 0);
                                parentActivity.activityHandler.sendMessage(msg);
                        }

                        outStream.close();
                        fileStream.close();
                        inStream.close();

                        if(isInterrupted())
                        {
                                // the download was canceled, so let's delete the partially downloaded file
                                outFile.delete();
                        }
                        else
                        {
                                // notify completion
                                msg = Message.obtain(parentActivity.activityHandler,
                                                AndroidFileDownloader.MESSAGE_DOWNLOAD_COMPLETE);
                                parentActivity.activityHandler.sendMessage(msg);
                        }
                }
                catch(MalformedURLException e)
                {
                        String errMsg = parentActivity.getString(R.string.error_message_bad_url);
                        msg = Message.obtain(parentActivity.activityHandler,
                                        AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
                                        0, 0, errMsg);
                        parentActivity.activityHandler.sendMessage(msg);
                }
                catch(FileNotFoundException e)
                {
                        String errMsg = parentActivity.getString(R.string.error_message_file_not_found);
                        msg = Message.obtain(parentActivity.activityHandler,
                                        AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
                                        0, 0, errMsg);
                        parentActivity.activityHandler.sendMessage(msg); 
                }
                catch(Exception e)
                {
                        String errMsg = parentActivity.getString(R.string.error_message_general);
                        msg = Message.obtain(parentActivity.activityHandler,
                                        AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
                                        0, 0, errMsg);
                        parentActivity.activityHandler.sendMessage(msg); 
                }
        }

}

以上代码从以下链接的项目中提取。

Existing Project

关于android - 尝试从我的应用程序下载 PDF 文件,但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10958724/

相关文章:

java - Android:从 Firebase 数据库中检索特定用户的数据

android - 通过自定义权限启用两个 Android 应用程序之间的通信

安卓 java.net.UnknownHostException

android - 当最新版本具有更高的 minSDKversion 级别时,如何修复旧版本 android 应用程序中的错误?

java - 在 Android 中转换 AsyncTask

java - 计数器不会在 AsyncTask 的新实例中重新启动

ruby - 如何使用 Ruby 通过 HTTP 下载文件?

java - 下载多个文件 Java

php - 在 Zend Framework 中发送下载的多部分响应

java - 如何根据指定条件从数据库列表中检索项目