Send SMS won't startActivity

938 views Asked by At

I want to send SMS from my application, for which I have written below code, which is pretty simple. But the issue I am facing is, No activity is started on sending message

Method to send a message:

private void sendSMS(Context context, String phone, String msg){
    Intent smsIntent = new Intent(Intent.ACTION_VIEW);

    smsIntent.setData(Uri.parse("smsto:"));
    smsIntent.putExtra("address", phone);
    smsIntent.putExtra("sms_body", msg);
    smsIntent.setType("vnd.android-dir/mms-sms");

    try {
        startActivity(smsIntent);
        finish();
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(context, "SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
    }
}

Permission added in manifest

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

It always shows toast written in catch()

3

There are 3 answers

0
Mrinmoy On BEST ANSWER

As you are getting toast always means its entering into catch(). Catch is handling ActivityNotFoundException

Follow this link, if it helps:

https://stackoverflow.com/a/10613004/5722385

If you are working with marshmallow and above, kindly go through the below link, it is having example how to add Runtime permission

https://stackoverflow.com/a/34969604/5722385

Because Sending sms is grouped into dangerous permission so you need to handle it at Runtime also, only writing permission in menifest file is not enough.

Before adding runtime permission if you want you can enable permission from you phone follow this steps.

Goto settings --> apps --> select you app --> permissions --> enable sms permission.

You can also check this link to get list of Dangerous permissions, that should be handled at Runtime

https://developer.android.com/guide/topics/permissions/requesting.html

3
Akhil Soman On

The code you are executing is old. This is the code to send an SMS from your APP

public void sendSMSFunction(){
     SmsManager smsManager = SmsManager.getDefault();
     String messageContent = "Your Content";
     smsManager.sendTextMessage("Destination_PhoneNumber", null, messageContent, null, null);
}

And add this permission to your manifest file

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

And if you are executing this in Android Marshmallow and above you will need to ask Runtime Permission.

1
Deep Patel On

Try this one:

also there is no need for:

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

Just use this code:

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
                sendIntent.setData(Uri.parse("sms:"));
                sendIntent.putExtra("sms_body", "Check out My app for your smartphone. Download it today from https://google.com");
                try {
                    startActivity(sendIntent);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();                        
                }