Sitemap

Open messaging app in Android

1 min readApr 7, 2021

--

Say we need to open the default messaging app in android and want to allow user to send a particular text message to a provided number. Below is the code to achieve this:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("smsto:"+ number)); //provide a valid number
intent.putExtra("sms_body", smsBody); //provide an sms body
startActivity(intent);

The above code will open the default messaging app with the provided sms body. But there might be a situation where OS might not find proper activity to handle this implicit intent. So it might throw ActivityNotFoundException. Therefore it’s better to handle such exception by using try/catch block.

Here’s the modified code with exception handling:

try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("smsto:"+ number));
intent.putExtra("sms_body", smsBody);
startActivity(intent);
} catch (ActivityNotFoundException exception){
Toast.makeText(context, "No messaging app found", Toast.LENGTH_SHORT).show();
}

Now what if we want to let user choose the messaging app. The code looks like this:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, contentText);
startActivity(Intent.createChooser(intent, "Header message"));

The above code lets user choose among available messaging apps from the device.

Buy me a coffee

If you like this article, then you can support me by buying me a coffee here. :)

--

--

No responses yet