2012-12-06 87 views
3
後打開

我試圖從互聯網下載pdf文檔,然後在下載結束時,通過一個包自動打開它。android:下載pdf文件並在

我發現一些解決方案可以通過DownloadManager進行下載,但沒有答案打開它之後。一個我測試過的代碼是:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    BroadcastReceiver receiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { 
       long downloadId = intent.getLongExtra(
         DownloadManager.EXTRA_DOWNLOAD_ID, 0); 
       Query query = new Query(); 
       query.setFilterById(enqueue); 
       Cursor c = dm.query(query); 
       if (c.moveToFirst()) { 
        int columnIndex = c 
          .getColumnIndex(DownloadManager.COLUMN_STATUS); 
        if (DownloadManager.STATUS_SUCCESSFUL == c 
          .getInt(columnIndex)) { 

         String uriString = c 
           .getString(c 
             .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); 
         Uri uri = Uri.parse(uriString); 

         intent = new Intent(); 
         intent.setAction(Intent.ACTION_VIEW); 

         intent.setDataAndType(uri, "application/pdf"); 
         startActivity(intent); 



        } 
       } 
      } 
     } 
    }; 

    registerReceiver(receiver, new IntentFilter(
      DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 
} 

public void onClick(View view) { 
    dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); 
    Request request = new Request(
      Uri.parse("http://www.xxxxxxx.org/directory/abc.pdf")); 
    enqueue = dm.enqueue(request); 

} 

但是當下載成功結束,包沒有找到該文件。

我需要你的幫助。我花了兩週的時間通過谷歌和安卓書籍尋找解決方案,但沒有成功。

謝謝。

+0

對於臨時解決方案,在手機中安裝adode閱讀器並將其重新安裝:http://stackoverflow.com/questions/6488265/show-pdf-in-android-application – deepak825

回答

1

創建此方法,並調用它在你的代碼

public void showPdf() { 
    try { 
     File file = new File(Environment.getExternalStorageDirectory() 
       + "/Download/" + name + "CV.pdf");//name here is the name of any string you want to pass to the method 
     if (!file.isDirectory()) 
      file.mkdir(); 
     Intent testIntent = new Intent("com.adobe.reader"); 
     testIntent.setType("application/pdf"); 
     testIntent.setAction(Intent.ACTION_VIEW); 
     Uri uri = Uri.fromFile(file); 
     testIntent.setDataAndType(uri, "application/pdf"); 
     startActivity(testIntent); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

要不然,你可以在這裏參考我的答案。

How to use Asynchronous task for download progress dialog in fragment?

其用於下載文件和顯示進度diolog.Here我使用非同步task.Call上述方法在onPOST等()非同步任務的方法。 希望它可以幫助你