Open online pdf file through android intent?

前端 未结 12 1573
醉话见心
醉话见心 2020-12-04 21:53

Currently I have a pdf url, and I would like to simply using the intent to open it, however, it does not work if I put the url in intent

12条回答
  •  难免孤独
    2020-12-04 22:38

    Best practice is wrapping your Intent to Chooser before starting. It provides users with built-in application selection dialog and lets avoid ActivityNotFoundException

    Here a little example:

    Intent browserIntent = new Intent(Intent.ACTION_VIEW);
    browserIntent.setDataAndType(Uri.parse(msg.getData()), Constants.MIME_PDF);
    
    Intent chooser = Intent.createChooser(browserIntent, getString(R.string.chooser_title));
    chooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // optional
    
    startActivity(chooser);
    

    Where Constants.MIME_PDF is defined as String value "application/pdf".


    It is possible to ask PackageManager is this Intent has appropriate handling Activity or not.

    public static boolean isActivityForIntentAvailable(Context context, Intent intent) {
        final PackageManager packageManager = context.getPackageManager();
        List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }
    

提交回复
热议问题