没有安装 csv 查看器的设备时没有 ActivityNotFoundException

No ActivityNotFoundException when device with no csv viewer installed in it

当 phone 中安装了 csv 查看器时,我想在查看器中显示 csv 文件。否则我需要显示祝酒消息 "There is no CSV viewer installed"。

就我而言,当我在未安装 csv 查看器的设备中测试以下代码时。

我没有收到 ActivityNotFoundException。结果,我的 toast 消息没有显示。你能帮忙吗

            Uri uri = Uri.parse(pdfUrl);
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "text/csv");
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getActivity(), "There is no CSV viewer installed", Toast.LENGTH_SHORT).show();
            }

吐司显示长度错误:

Toast.makeText(getActivity(), "There is no CSV viewer installed", Toast.LENGTH_SHORT).show();

您必须使用 Toast.LENGTH_SHORT 而不是 Toast.short

您可以打开意向选择器,其中包含处理 CSV 文件的应用程序。

startActivity(Intent.createChooser(intent, "Select Application"));

如果没有安装处理 CSV 文件的应用程序,它将显示没有安装应用程序。

使用 this SO answer,您可以经历不同的行为:

与其尝试启动 activity 并捕获 ANF 异常(这可能有问题,因为有些流不会抛出该异常),您可以提前检查是否会处理意图.

使用此 Java 代码:(假设 this 继承自 Activity

Activity activity = this; // change this line if calling from other places (a fragment etc)
Uri uri = Uri.parse(pdfUrl);
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/csv");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

if (intent.resolveActivity(activity.getPackageManager()) == null) {
    // No Activity found that can handle this intent.
    Toast.makeText(activity, "There is no CSV viewer installed", Toast.LENGTH_SHORT).show();
}
else{
    // There is an activity which can handle this intent.
    activity.startActivity(intent);
}