0% found this document useful (0 votes)
12 views

Android

Uploaded by

mariaombo123
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Android

Uploaded by

mariaombo123
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

To create an Android app that can send messages (SMS), you need to use the `SmsManager` class.

Here is a simple example of how to send an SMS from an Android app using Java in Android Studio:

### Steps:

1. **Set up your project**: Open Android Studio and create a new project with an empty activity.

2. **Permissions**: Add the necessary permissions in the `AndroidManifest.xml` to send SMS.

### `AndroidManifest.xml`:

You need to request permission to send SMS from your app. Add this permission in your manifest:

```xml

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

<uses-permission android:name=”android.permission.READ_SMS”/>

<uses-permission android:name=”android.permission.INTERNET”/>

```

### MainActivity.java:

This is the activity where the user can input a phone number and a message, and then send the
message.

```java

Package com.example.sendsmsapp;

Import androidx.appcompat.app.AppCompatActivity;

Import android.os.Bundle;

Import android.telephony.SmsManager;

Import android.view.View;

Import android.widget.Button;

Import android.widget.EditText;

Import android.widget.Toast;

Public class MainActivity extends AppCompatActivity {


Private EditText phoneNumberEditText, messageEditText;

Private Button sendButton;

@Override

Protected void onCreate(Bundle savedInstanceState) {

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize UI components

phoneNumberEditText = findViewById(R.id.phoneNumberEditText);

messageEditText = findViewById(R.id.messageEditText);

sendButton = findViewById(R.id.sendButton);

// Set click listener for the send button

sendButton.setOnClickListener(new View.OnClickListener() {

@Override

Public void onClick(View v) {

String phoneNumber = phoneNumberEditText.getText().toString();

String message = messageEditText.getText().toString();

If (!phoneNumber.isEmpty() && !message.isEmpty()) {

sendSMS(phoneNumber, message);

} else {

Toast.makeText(MainActivity.this, “Please fill in both fields.”,


Toast.LENGTH_SHORT).show();

});

}
Private void sendSMS(String phoneNumber, String message) {

Try {

// Get the SmsManager system service

SmsManager smsManager = SmsManager.getDefault();

// Send the SMS

smsManager.sendTextMessage(phoneNumber, null, message, null, null);

// Display a success message

Toast.makeText(MainActivity.this, “Message Sent!”, Toast.LENGTH_SHORT).show();

} catch (Exception e) {

// Display an error message

Toast.makeText(MainActivity.this, “Failed to send message.”, Toast.LENGTH_SHORT).show();

e.printStackTrace();

```

### activity_main.xml:

This is the layout file for the user interface where the user can input the phone number and
message.

```xml

<?xml version=”1.0” encoding=”utf-8”?>

<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android

Android:layout_width=”match_parent”

Android:layout_height=”match_parent”

Android:orientation=”vertical”

Android:padding=”16dp”>
<!—Phone Number Input 

<EditText

Android:id=”@+id/phoneNumberEditText”

Android:layout_width=”match_parent”

Android:layout_height=”wrap_content”

Android:hint=”Phone Number”

Android:inputType=”phone” />

<!—Message Input 

<EditText

Android:id=”@+id/messageEditText”

Android:layout_width=”match_parent”

Android:layout_height=”wrap_content”

Android:hint=”Message”

Android:inputType=”textMultiLine”

Android:lines=”4” />

<!—Send Button 

<Button

Android:id=”@+id/sendButton”

Android:layout_width=”match_parent”

Android:layout_height=”wrap_content”

Android:text=”Send Message” />

</LinearLayout>

```

### Key Points:

1. **Permissions**: The app needs the `SEND_SMS` permission in the manifest to send SMS.

2. **SmsManager**: The `SmsManager` class is used to send the SMS in the `sendSMS()` method.

3. **Toast Messages**: After sending an SMS, a toast message appears to notify the user of success
or failure.
### Handling Runtime Permissions (For Android 6.0+):

For devices running Android 6.0 (API level 23) or higher, you need to request permissions at runtime.
Below is how you can handle runtime permission for sending SMS.

Add this code to your `MainActivity.java`:

```java

Import android.Manifest;

Import android.content.pm.PackageManager;

Import androidx.core.app.ActivityCompat;

Import androidx.core.content.ContextCompat;

// In onCreate method, check for permissions

If (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) !=
PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, 1);

```

Override `onRequestPermissionsResult` to handle the user’s response:

```java

@Override

Public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

Super.onRequestPermissionsResult(requestCode, permissions, grantResults);

If (requestCode == 1) {

If (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

Toast.makeText(this, “Permission Granted”, Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(this, “Permission Denied”, Toast.LENGTH_SHORT).show();

}
}

```

### Testing:

- Ensure your app runs on a physical device, as SMS functionality doesn’t work on the emulator
unless configured properly.

- Test the app by entering a valid phone number and message, then press the “Send Message”
button to send the SMS.

This basic example allows users to send SMS messages directly from the app. Depending on the
app’s complexity, you might want to add additional features like handling delivery reports or
managing outgoing messages.

You might also like