android - 尝试下载pdf文件时出错

标签 android download handler

在我的应用程序中,我试图从服务器下载 PDF 文件并将其存储在 SD 卡中,但是当我尝试下载时,下载总是失败,并且 logcat 显示找不到处理程序。我需要帮助来解决这个问题,请帮助我。谢谢

下载文本.java

package mobile.download;

import java.io.*;
import java.net.*;
import java.util.regex.Pattern;

import mobile.config.Kondownload;

import com.karismaelearning.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.text.util.Linkify;
import android.util.Log;
import android.widget.TextView;

public class DownloadText extends Activity{
    public Kondownload linkurl;
    String url;
    String SERVER_URL;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
setContentView(R.layout.linkdownload);

        TextView mTextLink = (TextView) findViewById(R.id.LinkDownload);
        Bundle bundle = this.getIntent().getExtras();

        String param1 = bundle.getString("keyIdc");
        String param2 = bundle.getString("keyReference");
        linkurl = new Kondownload(this);
        SERVER_URL = linkurl.getUrl();
        SERVER_URL += "/moodledata/"+param1+"/"+param2;

        URLConnection urlConnection = null;

        try{

            URL url = new URL(SERVER_URL);

            //Opening connection of currrent url

            urlConnection = url.openConnection();
            urlConnection.connect();

            //int lenghtOfFile = urlConnection.getContentLength();


        String PATH = Environment.getExternalStorageDirectory() + "/pdf/";

        File file = new File(PATH);
        file.mkdirs();
        File outputFile = new File(file, param2);
        FileOutputStream fos = new FileOutputStream(outputFile);

        InputStream is = url.openStream();


        byte[] buffer = new byte[1024];

        int len1 = 0;

        while ((len1 = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len1);
        }

        fos.close();
        is.close();

         System.out.println("--pdf downloaded--ok--"+SERVER_URL);

        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }

        mTextLink.setText(SERVER_URL);
        Pattern pattern = Pattern.compile(SERVER_URL);

       Linkify.addLinks(mTextLink, pattern, "");

    }
}

日志

06-06 13:18:13.371: W/System.err(1056): java.io.FileNotFoundException: /mnt/sdcard/pdf/Dokumen/Dogmatika_1.pdf (No such file or directory)
06-06 13:18:13.371: W/System.err(1056):     at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
06-06 13:18:13.391: W/System.err(1056):     at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
06-06 13:18:13.391: W/System.err(1056):     at java.io.FileOutputStream.<init>(FileOutputStream.java:94)
06-06 13:18:13.402: W/System.err(1056):     at java.io.FileOutputStream.<init>(FileOutputStream.java:66)
06-06 13:18:13.402: W/System.err(1056):     at mobile.download.DownloadText.onCreate(DownloadText.java:85)
06-06 13:18:13.402: W/System.err(1056):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-06 13:18:13.402: W/System.err(1056):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-06 13:18:13.402: W/System.err(1056):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-06 13:18:13.402: W/System.err(1056):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-06 13:18:13.402: W/System.err(1056):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-06 13:18:13.402: W/System.err(1056):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-06 13:18:13.402: W/System.err(1056):     at android.os.Looper.loop(Looper.java:123)
06-06 13:18:13.402: W/System.err(1056):     at android.app.ActivityThread.main(ActivityThread.java:3683)
06-06 13:18:13.402: W/System.err(1056):     at java.lang.reflect.Method.invokeNative(Native Method)
06-06 13:18:13.411: W/System.err(1056):     at java.lang.reflect.Method.invoke(Method.java:507)
06-06 13:18:13.411: W/System.err(1056):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-06 13:18:13.411: W/System.err(1056):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-06 13:18:13.411: W/System.err(1056):     at dalvik.system.NativeStart.main(Native Method)
06-06 13:18:13.861: I/ActivityManager(61): Displayed com.karismaelearning/mobile.download.DownloadText: +649ms
06-06 13:18:15.101: I/ActivityManager(61): Starting: Intent { act=android.intent.action.VIEW dat=http://10.0.2.2/moodledata/2/Dokumen/Dogmatika_1.pdf cmp=com.android.browser/.BrowserActivity (has extras) } from pid 1056
06-06 13:18:15.831: I/ActivityManager(61): Displayed com.android.browser/.BrowserActivity: +675ms
06-06 13:18:17.271: W/InputManagerService(61): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@40554818 (uid=10020 pid=378)
06-06 13:18:17.781: D/webviewglue(378): nativeDestroy view: 0x3e4820
06-06 13:18:18.541: I/DownloadManager(218): Initiating request for download 22
06-06 13:18:19.281: W/DownloadManager(218): Aborting request for download 22: no handler found for this download type

最佳答案

检查下面的代码:它在 >= 9 Android API 中工作。

public void file_download(String uRl) {

        //uRl = ;
        File direct = new File(Environment.getExternalStorageDirectory()
                + "/dhaval_files");

        if (!direct.exists()) {
            direct.mkdirs();
        }

        DownloadManager mgr = (DownloadManager) this
                .getSystemService(Context.DOWNLOAD_SERVICE);

        Uri downloadUri = Uri.parse(uRl);
        DownloadManager.Request request = new DownloadManager.Request(
                downloadUri);

        request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_WIFI
                        | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false).setTitle("Demo")
                .setDescription("Something useful. No, really.")
                .setDestinationInExternalPublicDir("/dhaval_files", "lecture3.pdf");

        mgr.enqueue(request);

    }

调用上述方法使用:file_download("http://moss.csc.ncsu.edu/~mueller/g1/lecture3.pdf");


对于 <9 Android API 使用这种方式:

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.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockActivity;

public class MainActivity extends Activity {

    ProgressDialog mProgressDialog;

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

        mProgressDialog = new ProgressDialog(MainActivity.this);
        mProgressDialog.setMessage("A message");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        // execute this when the downloader must be fired
        DownloadFile downloadFile = new DownloadFile();
        downloadFile
                .execute("http://moss.csc.ncsu.edu/~mueller/g1/lecture3.pdf");
    }

    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();
                // 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());
                OutputStream output = new FileOutputStream("/sdcard/lecture3.pdf");

                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) {
            }
            return null;
        }

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

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            mProgressDialog.setProgress(progress[0]);
        }

    }
}

这两个代码都可以下载 PDF 文件。

Here is Best Answer

关于android - 尝试下载pdf文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953355/

相关文章:

javascript - 检查 JavaScript 文件是否已下载

python - 如何处理 balebot 中的 receipt_message

exception - exceptionCaught错误处理回写响应导致异常和infiniteLoop调用exceptionCaught

android - 处理程序与线程

java - 在 RecyclerView 中我想要 onclicklistener 操作

android - 为什么必须在 Android 中明确指定 $kotlin_version?

c++ - InternetReadFile() 似乎没有读取互联网数据

javascript - AngularJs 应用程序中的下载损坏

java - 如何在 Android 上将 POST 请求加载到带有 headers 和 body 的 Webview

android - 无法规范化 bintrayUpload 中的路径