Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error-proof way of starting SMS intent in 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?

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

Thanks in advance!

like image 363
caw Avatar asked Feb 29 '12 22:02

caw


2 Answers

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.

like image 146
Talihawk Avatar answered Nov 06 '22 06:11

Talihawk


Here is the code that will open the SMS activity pre-populated with the phone number to which the SMS has to be sent. This works fine on emulator as well as the device.

Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
smsIntent.addCategory(Intent.CATEGORY_DEFAULT);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.setData(Uri.parse("sms:" + phoneNumber); 
like image 45
JaydeepW Avatar answered Nov 06 '22 05:11

JaydeepW