2015-06-19 67 views
1

你最近怎麼樣? 我正在申請一個應用程序,我想單擊一個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) 

回答

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

因爲您沒有提供錯誤訊息,我認爲您忘了添加

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

到AndroidManifest.xml
請添加一條錯誤消息:)

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

當您訪問MainUIThread上的Internet(網絡)時,會發生這種情況。只需一個單獨的線程

運行你的網絡的事情,我會做這樣的:

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(""); 
    } 
}); 
+0

我有上網權限。但是,我現在會添加錯誤 – ama989

+0

請不要在Android上使用原始線程,它只是乞求泄漏。 –

+0

好的,我更新了它。我希望是對的 – Bennik2000

相關問題