从资产打开PDF时不存在文件或文件夹

时间:2014-07-04 05:22:37

标签: android android-intent android-assets

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

         startActivity(intent);
       } catch (Exception e) {
       WriteLogToFile.appendLog(Dashboard.this, "File", "file.txt", ActivityUtil.writeException(e));
         Intent i = new Intent(Intent.ACTION_VIEW);
         i.setData(Uri.parse("market://details?id=com.adobe.reader&hl=en"));
         startActivity(i);
       }

在某些设备上运行正常。但是在少数设备中它会给出错误,如找不到文件或文件夹请帮我解决问题

2 个答案:

答案 0 :(得分:0)

尝试将uri从file:///android_assets/重命名为file:///android_asset/

存储在assets文件夹中的文件的正确路径是file:///android_asset/xxx,没有“s”

例如:

Intent intent = new Intent(Intent.ACTION_VIEW);  
intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);  
Uri uri = Uri.fromFile(new File("file:///android_asset/abc.pdf"));  
intent.setDataAndType (uri, "application/pdf");  
this.startActivity(intent); 

答案 1 :(得分:0)

试试这个

 public class SampleActivity 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);
                }
            }

        }