2014-03-25 119 views
0

在我的android應用程序中,我有一個名爲2pg.pdf的pdf文件,我似乎無法在我的設備的本地應用程序中打開此pdf,我從來沒有之前從資產文件夾中獲得了一個文件,你能告訴我我應該添加到下面的類中嗎?從資產文件夾中獲取pdf文件

public class FullscreenActivity extends Activity { 

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

    Button button = (Button) findViewById(R.id.bPressMe); 

    button.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 


     File pdfFile = new File(Environment 
          .getExternalStorageDirectory(), "/assets/2pg.pdf"); 
    try { 
    if (pdfFile.exists()) { 
     Uri path = Uri.fromFile(pdfFile); 
     Intent objIntent = new Intent(Intent.ACTION_VIEW); 
     objIntent.setDataAndType(path, "application/pdf"); 
     objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     startActivity(objIntent); 
    } else { 
     Toast.makeText(FullscreenActivity.this, "File NotFound", 
     Toast.LENGTH_SHORT).show(); 
    } 
    } catch (ActivityNotFoundException e) { 
    Toast.makeText(FullscreenActivity.this, 
     "No Viewer Application Found", Toast.LENGTH_SHORT) 
     .show(); 
    } catch (Exception e) { 
    e.printStackTrace(); 
    } 
    } 
    }); 

} 

} 

回答

2

這爲我工作作爲從PDF(活性)讀取文件,你可以簡單地使用我的方法在你的onClick事件,希望這幫助。

public class ResumeActivity extends Activity 
{ 

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

    } 

    private void CopyReadAssets() 
    { 
     AssetManager assetManager = getAssets(); 

     InputStream in = null; 
     OutputStream out = null; 
     File file = new File(getFilesDir(), "abc.pdf"); 
     try 
     { 
      in = assetManager.open("abc.pdf"); 
      out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE); 

      copyFile(in, out); 
      in.close(); 
      in = null; 
      out.flush(); 
      out.close(); 
      out = null; 
     } catch (Exception e) 
     { 
      Log.e("tag", e.getMessage()); 
     } 

     Intent intent = new Intent(Intent.ACTION_VIEW); 
     intent.setDataAndType(
       Uri.parse("file://" + getFilesDir() + "/abc.pdf"), 
       "application/pdf"); 

     startActivity(intent); 
    } 

    private void copyFile(InputStream in, OutputStream out) throws IOException 
    { 
     byte[] buffer = new byte[1024]; 
     int read; 
     while ((read = in.read(buffer)) != -1) 
     { 
      out.write(buffer, 0, read); 
     } 
    } 

} 

確保包括

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
清單中

相關問題