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.
Should I use PackageManager.queryIntentActivities() or is there another way of solving this problem?
Thanks in advance!
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With