javaandroidsmssmsmanager

How do I send a text message in Android?


How do I send a text message? It seems simple but it doesn't work for me.

I have the permission in the manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.healthapp.healthapp">

<uses-permission android:name="android.permission.SEND_SMS"/>

<application   ...

I then have this code in my onClick:

SmsManager smsManager = SmsManager.getDefault();

smsManager.sendTextMessage("07123456789", null, "Hello there!", null, null);

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
                            startActivity(sendIntent);

But when I run this I get "Unfortunately App has stopped."

And the error message of:

FATAL EXCEPTION: main
Process: com.healthapp.healthapp, PID: 13477
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW typ=vnd.android-dir/mms-sms (has extras) }

Solution

  • You've got two different methods of sending SMS in your code. If you want to use SmsManager, then you don't need the Intent/startActivity() method, which attempts to open another app to handle the SMS.

    You can just remove everything after the smsManager.sendTextMessage() line, and you won't get that Exception anymore.

    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage("07123456789", null, "Hello there!", null, null);