2012-03-18 36 views
5

thể trùng lặp:
Download PDF from url and read itTải về một tập tin pdf và lưu nó vào sdcard và sau đó đọc nó từ đó

tôi phải tải về một tập tin pdf từ một url và lưu nó vào thẻ sd và sau đó đọc nó. Tôi đột phá vòng vây nhiều mã và tôi thấy điều này

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("*url for your pdf*")); 
startActivity(browserIntent); 

nhưng làm thế nào để lưu nó trong sd thẻ trong đường dẫn mong muốn của tôi và sau đó đọc nó từ đó.

Trả lời

15

Hãy xem số link này.

Nó chứa ví dụ về yêu cầu của bạn. Dưới đây là tóm tắt thông tin trong liên kết.

bước tuyên bố persmissions đầu tiên trong AndroidManifest.xml

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

Tạo một lớp downloader

public class Downloader { 

    public static void DownloadFile(String fileURL, File directory) { 
     try { 

      FileOutputStream f = new FileOutputStream(directory); 
      URL u = new URL(fileURL); 
      HttpURLConnection c = (HttpURLConnection) u.openConnection(); 
      c.setRequestMethod("GET"); 
      c.setDoOutput(true); 
      c.connect(); 

      InputStream in = c.getInputStream(); 

      byte[] buffer = new byte[1024]; 
      int len1 = 0; 
      while ((len1 = in.read(buffer)) > 0) { 
       f.write(buffer, 0, len1); 
      } 
      f.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 
} 

Cuối cùng tạo ra một hoạt động mà tải các tập tin PDF từ internet,

public class PDFFromServerActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     String extStorageDirectory = Environment.getExternalStorageDirectory() 
     .toString(); 
     File folder = new File(extStorageDirectory, "pdf"); 
     folder.mkdir(); 
     File file = new File(folder, "Read.pdf"); 
     try { 
      file.createNewFile(); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } 
     Downloader.DownloadFile("http://www.nmu.ac.in/ejournals/aspx/courselist.pdf", file); 

     showPdf(); 
    } 
    public void showPdf() 
     { 
      File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf"); 
      PackageManager packageManager = getPackageManager(); 
      Intent testIntent = new Intent(Intent.ACTION_VIEW); 
      testIntent.setType("application/pdf"); 
      List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY); 
      Intent intent = new Intent(); 
      intent.setAction(Intent.ACTION_VIEW); 
      Uri uri = Uri.fromFile(file); 
      intent.setDataAndType(uri, "application/pdf"); 
      startActivity(intent); 
     } 
} 
Các vấn đề liên quan