2012-07-11 117 views
0

我想通過Android應用程序打開PDF文件。到目前爲止,我已經寫了下面的代碼:如何通過我的Android應用程序打開PDF文件?

public class PdfopenActivity extends Activity { 
    String selectedFilePath; 

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

     Button btnOpen=(Button)findViewById(R.id.button1); 

     btnOpen.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // Sample.pdf is my file name it is in /Root/Download/Sample.pdf 
       // path of the file 

       File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Sample.pdf"); 
       Intent intent = new Intent(Intent.ACTION_VIEW); 
       intent.setDataAndType(Uri.fromFile(file),"application/pdf"); 
       intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 
       startActivity(intent); 
      } 
     }); 
    } 
} 

該PDF 175kb,我可以直接打開該文件在我的銀河TAB2平板電腦,但是當我跑我的我的程序來打開它,我得到的錯誤:

An Error Occurred while opening the document.

任何人都可以告訴我我要去哪裏嗎?

+0

在這兩個設備上安裝了相同的PDF查看器? – user370305 2012-07-11 05:57:19

+0

請確保PDF位於sdcard.if中的正確位置,如果它位於任何文件夾內部,那麼它將包含在內。 – AkashG 2012-07-11 06:05:59

+0

通過編寫Environment.getExternalStorageDirectory()。getAbsolutePath()+「/ Sample.pdf」,它將顯示它是不是在任何文件夾,但在SD卡內 – AkashG 2012-07-11 06:06:56

回答

3

嘗試了這一點:

 Button btnOpen=(Button)findViewById(R.id.button1); 
     btnOpen.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       File file = new File("/sdcard/sample.pdf"); 

       if (file.exists()) { 
        Uri path = Uri.fromFile(file); 
        Intent intent = new Intent(Intent.ACTION_VIEW); 
        intent.setDataAndType(path, "application/pdf"); 
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

        try { 
         startActivity(intent); 
        } 
        catch (ActivityNotFoundException e) { 

        } 
       } 
      } 
     }); 

希望這會幫助你。

+0

謝謝你的回覆,當我把這個沒有行動時,我點擊按鈕 ? – user1508544 2012-07-11 06:09:12

+0

我已經在你的問題下發表評論看到它 – AkashG 2012-07-11 06:10:39

+0

感謝你的回覆我的pdf文件位置是/Root/sdcard/Download/sample.pdf – user1508544 2012-07-11 06:13:12

相關問題