Why is my SMS Application not sending to the right number?

I'm inputting an 11 number phone number and i'm having trouble because it is not sending to the right number and I don't know why. Can you guys help me? Here is my code I don't really know the problem with it and I hope you guys can try to help me here

public class MainActivity extends Activity {

    private final static int SEND_SMS_PERMISSION_REQUEST_CODE = 111;
    private Button sendMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendMessage = findViewById(R.id.send_message);
        final EditText phone = findViewById(R.id.phone_no);
        final EditText message = findViewById(R.id.message);
        sendMessage.setEnabled(false);

        if (checkPermission(Manifest.permission.SEND_SMS)) {
            sendMessage.setEnabled(true);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);
        }

        sendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = message.getText().toString();
                String phonenumber = phone.getText().toString();

                if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {

                    if (checkPermission(Manifest.permission.SEND_SMS)) {
                        SmsManager smsManager = SmsManager.getDefault();
                        smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
                    } else {
                        Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private boolean checkPermission(String permission) {
        int checkPermission = ContextCompat.checkSelfPermission(this, permission);
        return checkPermission == PackageManager.PERMISSION_GRANTED;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case SEND_SMS_PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    sendMessage.setEnabled(true);
                }

                break;
        }
    }
}

1 answer

  • answered 2019-02-10 14:21 Lighteninger

    To send the message,try this code, but first ask/check for SMS permissions:

    SmsManager manager = SmsManager. getDefault(); 
    manager.sendTextMessage(phonenumber, null, message, null, null); 
    

    Reference