Ex 6
Ex 6
<EditText
android:id="@+id/messageText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your message"
android:layout_marginTop="16dp" />
<Button
android:id="@+id/sendSmsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send SMS"
android:layout_marginTop="24dp" />
</LinearLayout>
Step 3: Add Permissions to Send SMS
In order to send an SMS, we need to request the necessary permissions. Open the AndroidManifest.xml file
and add the following permission:
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendSmsButton.setOnClickListener(v -> {
String phone = phoneNumber.getText().toString();
String message = messageText.getText().toString();
if (phone.isEmpty() || message.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter all fields", Toast.LENGTH_SHORT).show();
return;
}
// Create an Intent to send SMS
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("sms:" + phone));
intent.putExtra("sms_body", message);
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "SMS sending failed", Toast.LENGTH_SHORT).show();
}
});
}
}
If the user doesn't enter a phone number or a message and clicks the "Send SMS" button,
The app will display
Please enter all fields