Android – Error-proof way of starting SMS intent in Android

androidandroid-intentsms

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?

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

Thanks in advance!

Best Answer

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.
}

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.

Related Topic