0

I am trying to send an SMS from my android app. Every time I click on my button, it goes to catch part rather then try.

Here is my method:

Button sms = (Button)findViewById(R.id.button2);
    sms.setOnClickListener(
            new View.OnClickListener()
            {
                public void onClick(View view)
                {

                    Log.i("Send SMS", "");
                    Intent sms = new Intent(Intent.ACTION_VIEW);
                    sms.setData(Uri.parse("smsto:"));
                    sms.setType("vnd.android-dir/mms-sms");
                    sms.putExtra("address", new String(con));
                    sms.putExtra("sms_body", "Test SMS to Angilla");

                    try {
                        startActivity(sms);
                        finish();
                        Log.i("Finished sending SMS...", "");
                    }
                    catch (android.content.ActivityNotFoundException ex) {
                        Toast.makeText(DetailActivity.this,
                                "SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
                    }

                }
            });
Marko Popovic
  • 3,999
  • 3
  • 22
  • 37
SajaWal NaWaz
  • 115
  • 1
  • 3
  • 13

2 Answers2

1

You can send sms two ways: 1. SMS Manager 2. Built in app

Both ways need permissions in manifest

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

Example with sms manager:

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

Example with built-in app:

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content"); 
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
Alexander
  • 497
  • 6
  • 19
  • 1
    Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setData(Uri.parse("smsto:" + Uri.encode(phoneNumber))); startActivity(intent); – Alexander Apr 08 '16 at 07:47
  • It's working (with built-in app), but this is not working "Uri.encode(phoneNumber)" i also tried "intent.setData(Uri.parse("smsto:" + con)); – SajaWal NaWaz Apr 08 '16 at 08:00
1

This is working for me :

Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
sendIntent.setData(Uri.parse("smsto:"));
sendIntent.putExtra("sms_body", "Your message");

try {
    startActivity(sendIntent);
} catch (android.content.ActivityNotFoundException ex) {
    ex.printStackTrace();
}