Android - No Activity found to handle Intent { act

2019-06-17 10:26发布

I searched a lot to find a solution , but still can't find any

I am trying to open a PDF file in my android application

Here is my code to do this :

try 
    {
        File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        Log.d("CheckingURI", uri.toString());
        intent.setDataAndType(uri, "application/pdf");
        startActivity(intent);
    } 
    catch (Exception e) 
    {
        Log.d("OpenPDFError", e.getMessage());
    }

The Tomcat Log implies that there is no activity to handle the intent

09-19 19:55:02.938: D/CheckingURI(30483): file:///mnt/sdcard/pdf/Read.pdf
09-19 19:55:02.948: D/OpenPDFError(30483): No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///mnt/sdcard/pdf/Read.pdf typ=application/pdf }

Is there any other way to do this or can i open the PDF file with another default PDF viewer? If yes, how?

Update : the main problem was that i did not install a PDF viewer application on my emulator ...

2条回答
做个烂人
2楼-- · 2019-06-17 11:17

You just have to popup some sort of error msg to the user if no activity was found to launch the PDF (In the error dialog you can let the user know he needs some PDF app and send him to the Play Store), though i'd suggest using this piece of code instead of the genral exception catcher you're using:

try {
    /* your code */
    ...
} catch (ActivityNotFoundException e) {
    e.printStackTrace();
}

or you can use some PDF library, like this one.

查看更多
我命由我不由天
3楼-- · 2019-06-17 11:20

Try this instead:

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

CAVEAT: The above method only work if you have a pre-installed PDF Viewer. If not, you need to install a PDF Viewer.

查看更多
登录 后发表回答