在Android中启动SMS意图的防错方法 [英] Error-proof way of starting SMS intent in Android

查看:116
本文介绍了在Android中启动SMS意图的防错方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Android应用程序中,我使用以下代码启动消息传递应用程序并填写短信的默认文本:

In my Android application, I use the following code to start the messaging app and fill in a default text for a text message:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("sms:"+USERS_PHONE_NUMBER));
intent.putExtra("sms_body", "DUMMY TEXT");
startActivity(intent);

这在大多数情况下都有效.但不幸的是,在某些设备上,我收到以下错误消息:

This works in most cases. But unfortunately, on some devices I get the following error message:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=sms:+XXXXXXXXXX (has extras) }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1510)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1384)
at android.app.Activity.startActivityForResult(Activity.java:3131)
at android.app.Activity.startActivity(Activity.java:3237)

很明显,我创建的意图无法得到处理.

Obviously, the intent that I created cannot be handled.

  • 我的短信意图代码是否有错误?
  • 如果无法处理意图,如何防止应用程序崩溃?
  • Is there any mistake in my SMS intent code?
  • How can I prevent the application from crashing if the intent cannot be handled?

我应该使用PackageManager.queryIntentActivities()还是解决该问题的另一种方法?

Should I use PackageManager.queryIntentActivities() or is there another way of solving this problem?

提前谢谢!

推荐答案

我没有专门尝试过此意图,但是最简单的方法可能是添加try and catch块

I haven't tried this intent specifically, but the simplest way will probably be to add try and catch block

try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Display some sort of error message here.
}

由于您不能依靠特定的Android设备来安装Messaging应用程序(例如,某些平板电脑没有电话服务),因此您必须做好准备.

Since you can't count on the specific Android device to have the Messaging app (some tablets for example don't have telephony services), you have to be ready.

通常,当您开始进行外部活动时,这是一个好习惯,以避免应用程序崩溃.

It is a good practice in general when you're starting external activities, to avoid crashes in your app.

这篇关于在Android中启动SMS意图的防错方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆