如何处理ActivityNotFoundException?

时间:2011-12-06 11:19:41

标签: android android-activity

在我的应用程序中,我需要使用startActivity来查看文件的内容,或者使用默认的应用程序来打开某个文件,但有时android系统可能无法安装所需的应用程序。

我的问题是如何处理此异常。我想要祝酒,而不是FC ..

任何建议? THX

4 个答案:

答案 0 :(得分:13)

只需在清单文件中添加该活动即可

喜欢,

<activity android:name=".ActivityName"
                  android:label="@string/app_name">
        </activity>

修改

现在抓住ActivityNOtFoundException放入你的代码,

try {

  // Your startActivity code wich throws exception  
} catch (ActivityNotFoundException activityNotFound) {

    // Now, You can catch the exception here and do what you want
}

注意:当您发现 ActivityNotFound 异常时要小心,但是您无法将清单文件修改为运行时,这意味着一旦遇到异常并且您想在运行时添加此活动标记那么你不能。

答案 1 :(得分:10)

您可以使用resolveActivity方法

    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }else {
        Toast.makeText(this,"No suitable app found!",Toast.LENGTH_SHORT).show();
    }

答案 2 :(得分:2)

我认为你的问题更多:“我怎样才能抓住某个例外并防止力量崩溃”。 这是你在代码中的方式:

try {
    // here is your code that can potentially throw the exception and the force crash
} catch (ActivityNotFoundException activityNotFound) {
    Toast.makeText(this, "your error message", Toast.LENGTH_SHORT).show();
    // maybe also log the exception, for future debugging?
}

警告,不要滥用这个:“静默吞下”异常是危险的,可能会使您的应用程序不稳定并引入奇怪且难以调试的行为。

答案 3 :(得分:1)

如果您想将错误显示为吐司,那么

try {
    startActivity(intent);

} catch (ActivityNotFoundException e) {
    // TODO: handle exception
    //Show Toast...
}

发生错误是因为清单文件中未提及该活动。

<activity android:name=".yourActivity"
      android:label="@string/app_name">
</activity>