如何点击下载文件

ama989

你好吗 ?我正在制作一个应用程序,在该应用程序中,我想单击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)
ama989

这是解决方案:

            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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章