如何通过点击下载文件

时间:2015-06-19 19:24:02

标签: android android-fragments

你好吗? 我正在创建一个应用程序,在应用程序中我想单击一个listView,我的应用程序开始下载链接。我已经有了链接。我使用了以下代码但是,我的应用程序崩溃了:

以下是处理点击的监听器:

mListViewMagazine.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            DownloadFromUrl(mMagazine_title[position]);


        }
    });

DownloadFromUrl函数如下:

public void DownloadFromUrl( String fileName) {  //this is the downloader method
    try {
        URL url = new URL("http://themwl.org/web/sites/default/files/584_0.pdf");
                File file = new File(fileName);

        long startTime = System.currentTimeMillis();
        Log.d("ImageManager", "download begining");
        Log.d("ImageManager", "download url:" + url);
        Log.d("ImageManager", "downloaded file name:" + fileName);
                    /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();

                    /*
                     * Define InputStreams to read from the URLConnection.
                     */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

                    /*
                     * Read bytes to the Buffer until there is nothing more to read(-1).
                     */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

                    /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();
        Log.d("ImageManager", "download ready in"
                + ((System.currentTimeMillis() - startTime) / 1000)
                + " sec");

    } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);
    }

}

错误讯息:

 06-19 22:32:01.585  12336-12336/alahdal.amjad.mwlapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: alahdal.amjad.mwlapplication, PID: 12336
android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
        at java.net.InetAddress.getAllByName(InetAddress.java:215)
        at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
        at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
        at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
        at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
        at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
        at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
        at alahdal.amjad.mwlapplication.PublicationsFragment.DownloadFromUrl(PublicationsFragment.java:98)
        at alahdal.amjad.mwlapplication.PublicationsFragment$1.onItemClick(PublicationsFragment.java:75)
        at android.widget.AdapterView.performItemClick(AdapterView.java:300)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1143)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3044)
        at android.widget.AbsListView$3.run(AbsListView.java:3833)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

2 个答案:

答案 0 :(得分:1)

因为您没有提供错误消息,我认为您忘了添加

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

到你的AndroidManifest.xml
请添加错误消息:)

-------------更新-------------

当您访问MainUIThread上的互联网(网络)时会发生这种情况。只需在单独的线程上运行您的网络内容

我会这样做:

mListViewMagazine.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        AsyncTask thread = new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                DownloadFromUrl(mMagazine_title[position]);
                return "Finish";
            }
        };
        thread.execute("");
    }
});

答案 1 :(得分:1)

这是解决方案:

            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(files_url[position]));
            request.setTitle("File Downloading");
            request.setDescription("File is being Downloaded...");
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            String File_name = URLUtil.guessFileName(files_url[position],null, MimeTypeMap.getFileExtensionFromUrl(files_url[position]));
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,File_name)  ;
            DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);
            Toast.makeText(getActivity(),"Downloading",Toast.LENGTH_LONG).show();