reading file in assets or raw folder in Android

2019-03-01 02:26发布

问题:

I have to ship pdf files along with my application and display them as list and when clicked each one should open in Adobe reader. I have tried placing the pdf files in /assets folder also in /res/raw folder. But in either case I am encountering ActivityNotFound Exception. The code and the exception message are below.

Placing file in /assets/pdf folder

try {
            files = amanager.list("pdf");
            //AssetFileDescriptor fd = amanager.openFd(files[0]);
            Uri path = Uri.parse("android.resource://com.csg.android.myproject/assets/pdf/csgsample")  ;
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setPackage("com.adobe.reader");
            intent.setDataAndType(path, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            try {
                startActivity(intent);
            }
            catch (ActivityNotFoundException e){
                Toast.makeText(FirstTab.this, "NO Viewer", Toast.LENGTH_SHORT).show();
            }


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Placing file in /res/raw folder

Uri.parse("android.resource://com.csg.android.myproject/raw/csgsample")  ;

Exception:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=android.resource://com.csg.android.myproject/assets/pdf/csgsample typ=application/pdf flg=0x4000000 pkg=com.adobe.reader }

Any help would be greatly appreciated.

Thanks in Advance, Navin

回答1:

If you get an ActivityNotFoundException is because there are no application to handle that kind of content. So, in that case, I'm sure the the Adobe Reader is installed.

Also, I think you must copy the file to the SDCard for other apps to access it. They cannot access your private data directly for security reasons.



回答2:

I think assets and raw files are only viewable by your application. 3rd party applications (bundled or not) cannot access these files. You should first put your files in the device's sdcard before opening them.



回答3:

I have the same problem, but I should note that this is how I open by resource id

Uri.parse("android.resource://com.csg.android.myproject/" + R.raw.csgsample);