Develop simple SMS app in android studio

This is simple model of SMS app.

Here you can put number and message what you want to send.

Program in MainActivity-

public class MainActivity extends AppCompatActivity {
    EditText txtNo, txtMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtNo=(EditText)findViewById(R.id.editText);
        txtMsg=(EditText)findViewById(R.id.editText2);
    }
    public void send(View view){
        try {
            SmsManager smsManager = SmsManager.getDefault();
            String sendTo = ("" + txtNo.getText());
            String myMessage = ("" + txtMsg.getText());
            smsManager.sendTextMessage(sendTo, null, myMessage, null, null);
            setTitle("Sent");
        }
        catch (Exception ex){
            setTitle(ex.getMessage());
        }
    }
}

We have to do one more thing to give permission to this app.

we have to write program in Manifist.xml-

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

For cheaking permission through this app like that–

Here we have to add some more program in mainActivity…

 public void getPermission(View view) {
        setTitle("Clicked");
        try {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                // Show an explanation if permission has been
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS)) {
                    txt.setText("This App needs to send SMS");
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION);
                } else {
                    // No explanation needed, we can request the permission.
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION);
                }
            } else
                setTitle("Has SMS Sending Permission");
        } catch (Exception ex) {
            setTitle(ex.getMessage());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

        switch (requestCode) {
            case SEND_SMS_PERMISSION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    setTitle("Permission Given");
                } else {
                    setTitle("Permission Not Given");
                    return;
                }
            }
        }
    }
}

Leave a Reply