从assets文件夹获取pdf文件

时间:2014-03-25 23:51:13

标签: android

在我的Android应用程序中,我有一个名为2pg.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();
    }
   }
  });

 }

}

1 个答案:

答案 0 :(得分: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" />
清单中的