0% found this document useful (0 votes)
26 views16 pages

Views

The document provides an overview of SMS messaging in Android, detailing the built-in messaging app, SMS APIs for developers, and the necessary permissions for sending and receiving messages. It includes code examples for sending SMS programmatically and using implicit intents, as well as instructions for receiving SMS with a BroadcastReceiver. Additionally, it discusses best practices, security considerations, and how to send emails using the JavaMail API in Android applications.

Uploaded by

INDHU MATHI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views16 pages

Views

The document provides an overview of SMS messaging in Android, detailing the built-in messaging app, SMS APIs for developers, and the necessary permissions for sending and receiving messages. It includes code examples for sending SMS programmatically and using implicit intents, as well as instructions for receiving SMS with a BroadcastReceiver. Additionally, it discusses best practices, security considerations, and how to send emails using the JavaMail API in Android applications.

Uploaded by

INDHU MATHI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

CHAPTER 9: MESSAGING

In Android, SMS messaging is a core feature of the operating system, allowing users to send and
receive text messages using the built-in messaging app or third-party messaging apps available on
the Google Play Store. Here's a brief overview of SMS messaging on Android:

1.Messaging App: Android devices typically come pre-installed with a messaging app that allows
users to compose, send, and receive SMS messages. This app may vary slightly depending on the
manufacturer or version of Android, but it generally provides basic messaging functionality such as
text input, message threading, and contact management.

2.SMS APIs: Android provides developers with APIs (Application Programming Interfaces) for
interacting with SMS messaging functionality within their apps. Developers can use these APIs to
send SMS messages programmatically from their apps, monitor incoming messages, and perform
other tasks related to SMS communication.

3.Permissions: To access SMS messaging features on Android, apps typically require the appropriate
permissions. For example, an app that sends SMS messages on behalf of the user would need the
SEND_SMS permission, while an app that reads incoming SMS messages would need the READ_SMS
permission.

4.Default SMS App: Android allows users to set a default SMS app, which is the app that handles all
SMS-related tasks by default. When a user receives an SMS message, it's the default SMS app that
processes and displays the message. Users can change their default SMS app in the system settings.

5.Integration with Other Services: Android apps can integrate SMS messaging functionality with
other services and features of the device. For example, an app might use SMS for two-factor
authentication, verification codes, or notifications.

6.Enhanced Messaging Features: Some Android devices and messaging apps support enhanced
messaging features such as RCS (Rich Communication Services). RCS builds upon the traditional SMS
protocol to offer features similar to those found in internet-based messaging apps, such as group
chats, high-resolution images, read receipts, and typing indicators.

Sending SMS Message Programmatically


To send SMS messages programmatically in an Android app, you can use the
SmsManager class provided by the Android SDK. Here's a basic example of how you can
send an SMS message:

JAVA CODE :

import android.telephony.SmsManager;

import android.app.PendingIntent;

import android.content.Intent;
import android.content.Context;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Your message content and destination phone number

String message = "Hello, this is a test message!";

String phoneNumber = "1234567890";

// Check if app has permission to send SMS

if (checkSelfPermission(Manifest.permission.SEND_SMS) ==
PackageManager.PERMISSION_GRANTED) {

// If permission is granted, send the SMS

sendSMS(phoneNumber, message);

} else {

// If permission is not granted, request it from the user

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

// Method to send SMS message

private void sendSMS(String phoneNumber, String message) {

// Get the default instance of SmsManager

SmsManager smsManager = SmsManager.getDefault();


// Create a PendingIntent to track the sent SMS

PendingIntent sentIntent = PendingIntent.getBroadcast(this, 0, new


Intent("SMS_SENT"), 0);

// Send the SMS message

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

// Handle permission request result

@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) {

// If permission is granted, send the SMS

sendSMS(phoneNumber, message);

} else {

// If permission is denied, inform the user

Toast.makeText(this, "SMS permission denied", Toast.LENGTH_SHORT).show();

Make sure to add the necessary permissions to your AndroidManifest.xml file:

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

In this example, the sendSMS() method sends an SMS message with the specified content
(message) to the specified phone number (phoneNumber). Before sending the SMS, the app
checks if it has the necessary permission to send SMS messages. If permission is granted, the
SMS is sent; otherwise, the app requests permission from the user.

This is a basic example to get you started. Depending on your requirements, you may need
to handle additional scenarios, such as handling delivery reports, checking for network
connectivity, and handling errors.

SMS Message Using an Implicit Intent in Android


you can also send an SMS message using an implicit intent in Android. Here's how you can
do it:

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Your message content and destination phone number

String message = "Hello, this is a test message!";

String phoneNumber = "1234567890";

// Create an intent with action ACTION_SENDTO

Intent intent = new Intent(Intent.ACTION_SENDTO);

// Set the data (URI) for the intent


Uri uri = Uri.parse("smsto:" + phoneNumber); // "smsto:" for sending SMS

intent.setData(uri);

// Set the message content

intent.putExtra("sms_body", message);

// Check if there's an activity that can handle the intent

if (intent.resolveActivity(getPackageManager()) != null) {

// Start the activity (SMS app) to send the message

startActivity(intent);

} else {

// Handle case where no SMS app is available

// You may inform the user to install a messaging app

// or provide an alternative method for sending messages

RECEIVING SMS MESSAGES


To receive SMS messages in an Android app, you can use a `BroadcastReceiver` to listen for
incoming SMS messages. Here's an example of how you can implement this:

1. Create a BroadcastReceiver:

First, create a class that extends `BroadcastReceiver` and override the `onReceive` method
to handle incoming SMS messages. Here's an example:

```java

import android.content.BroadcastReceiver;

import android.content.Context;
import android.content.Intent;

import android.telephony.SmsMessage;

import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

if (intent.getAction() != null &&


intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {

Bundle bundle = intent.getExtras();

if (bundle != null) {

Object[] pdus = (Object[]) bundle.get("pdus");

if (pdus != null) {

for (Object pdu : pdus) {

SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);

String sender = smsMessage.getOriginatingAddress();

String messageBody = smsMessage.getMessageBody();

// Handle the received SMS message here

Toast.makeText(context, "SMS received from: " + sender + "\nMessage: " +


messageBody, Toast.LENGTH_LONG).show();

}
}

```

2. Register the BroadcastReceiver in AndroidManifest.xml:

Add the following lines to your AndroidManifest.xml file to register the `SmsReceiver`:

```xml

<receiver android:name=".SmsReceiver">

<intent-filter>

<action android:name="android.provider.Telephony.SMS_RECEIVED" />

</intent-filter>

</receiver>

```

3. Request Permissions (Android 6.0+):

If your app targets Android 6.0 (API level 23) or higher, request the `RECEIVE_SMS`
permission in your AndroidManifest.xml file:

```xml

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

```

4. Handle SMS in MainActivity (Optional):

If you want to perform additional actions or update the UI based on received SMS
messages, you can do so in your MainActivity or any relevant activity. For example:

```java
public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

@Override

protected void onResume() {

super.onResume();

// Register the BroadcastReceiver dynamically if needed

IntentFilter intentFilter = new


IntentFilter("android.provider.Telephony.SMS_RECEIVED");

registerReceiver(new SmsReceiver(), intentFilter);

@Override

protected void onPause() {

super.onPause();

// Unregister the BroadcastReceiver when not needed

unregisterReceiver(new SmsReceiver());

```
In this setup:

- The `SmsReceiver` class listens for incoming SMS messages and displays a toast with the
sender's number and message body.

- Register the `SmsReceiver` in the AndroidManifest.xml file to ensure it receives SMS


broadcasts.

- Request the `RECEIVE_SMS` permission if targeting Android 6.0 or higher.

- Optionally, dynamically register and unregister the `SmsReceiver` in your activity's lifecycle
if needed.

Remember to handle permissions, especially if your app targets newer Android versions,
and consider the appropriate actions to take when receiving SMS messages based on your
app's requirements.

CAVEATS AND WARNINGS


When working with SMS messaging in Android, there are several caveats, best practices,
and considerations to keep in mind:

1. Permission Handling:

- Request Permissions: Always request the necessary permissions (`SEND_SMS`,


`RECEIVE_SMS`, etc.) in your AndroidManifest.xml file and handle permission requests at
runtime, especially for Android 6.0 (API level 23) and higher.

- Permission Check: Before sending or receiving SMS messages, check if the required
permissions are granted.

2.Security Considerations:

- Sensitive Information: Be cautious with handling sensitive information such as phone


numbers and message content. Avoid storing sensitive data insecurely.

- SMS Authentication: SMS messages are not completely secure for authentication
purposes due to potential vulnerabilities like SIM swapping. Consider using more secure
methods such as OTP tokens or app-based authentication.

- Sender Verification: When receiving SMS messages, verify the sender's identity to
prevent spoofing and phishing attacks.
3. BroadcastReceiver Registration:

- Intent Filters: Register your BroadcastReceiver with appropriate intent filters in the
AndroidManifest.xml file to receive SMS-related broadcasts
(`"android.provider.Telephony.SMS_RECEIVED"`).

- Dynamic Registration: If needed, dynamically register and unregister your


BroadcastReceiver in the activity's lifecycle (e.g., in onResume and onPause) to receive SMS
broadcasts only when the activity is active.

4. Handling SMS Content:

- Message Parsing: When parsing SMS content, handle different formats and languages
gracefully to ensure compatibility across devices and regions.

- Message Length: SMS messages have length limitations (e.g., 160 characters for standard
SMS). Handle long messages by splitting or concatenating them as needed.

5. User Experience:

- Toast Notifications: Use toast notifications (or log messages for debugging) judiciously
when processing SMS messages to avoid overwhelming the user with frequent notifications.

- Background Processing: Consider handling SMS processing tasks in a background service


if they require substantial processing or network operations to avoid blocking the main UI
thread.

6. Testing and Error Handling:

- Test Scenarios: Test your SMS-related functionalities across different devices, Android
versions, and network conditions to ensure reliability and compatibility.

- Error Handling: Implement robust error handling and logging mechanisms to handle
exceptions, network errors, and unexpected scenarios gracefully.

7. Compliance and Regulations:


- Compliance: Ensure your app complies with applicable regulations, such as SMS
permissions policies, data privacy laws, and carrier guidelines.

- User Consent: Obtain explicit user consent for sending SMS messages from their device
and adhere to spam regulations and guidelines.

By following these best practices and considering the caveats mentioned above, you can
develop SMS messaging functionalities in your Android app effectively and responsibly.

SENDING EMAIL
Sending emails in Android involves using the JavaMail API or a third-party library like
JavaMail-Android or Apache Commons Email. Here's a basic example using JavaMail API to
send an email in an Android app:

1. Add Dependencies:

Include the JavaMail API dependencies in your project. For example, if you're using Gradle,
add the following dependencies in your module's build.gradle file:

```gradle

dependencies {

implementation 'com.sun.mail:android-mail:1.6.7'

implementation 'com.sun.mail:android-activation:1.6.7'

```

2. Create Email Sending Function:

Create a function to send an email. Make sure to handle network operations on a


background thread to avoid blocking the main UI thread. Here's an example
implementation:
```java

import android.os.AsyncTask;

import android.util.Log;

import java.util.Properties;

import javax.mail.Authenticator;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

public class EmailSender extends AsyncTask<Void, Void, Void> {

private final String username;

private final String password;

private final String recipientEmail;

private final String subject;

private final String messageBody;

public EmailSender(String username, String password, String recipientEmail,

String subject, String messageBody) {

this.username = username;
this.password = password;

this.recipientEmail = recipientEmail;

this.subject = subject;

this.messageBody = messageBody;

@Override

protected Void doInBackground(Void... voids) {

Properties properties = new Properties();

properties.put("mail.smtp.auth", "true");

properties.put("mail.smtp.starttls.enable", "true");

properties.put("mail.smtp.host", "smtp.gmail.com");

properties.put("mail.smtp.port", "587");

Session session = Session.getInstance(properties,

new Authenticator() {

@Override

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(username, password);

});

try {

MimeMessage mimeMessage = new MimeMessage(session);

mimeMessage.setFrom(new InternetAddress(username));
mimeMessage.addRecipient(Message.RecipientType.TO, new
InternetAddress(recipientEmail));

mimeMessage.setSubject(subject);

mimeMessage.setText(messageBody);

Transport.send(mimeMessage);

} catch (MessagingException e) {

Log.e("EmailSender", "Error sending email", e);

return null;

```

3. Usage in Activity or Fragment:

In your activity or fragment, create an instance of `EmailSender` and execute it to send the
email. For example:

```java

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Example usage to send email


String username = "[email protected]";

String password = "your_password";

String recipientEmail = "[email protected]";

String subject = "Test Email";

String messageBody = "Hello from my Android app!";

EmailSender emailSender = new EmailSender(username, password, recipientEmail,


subject, messageBody);

emailSender.execute();

```

Replace `"[email protected]"` and `"your_password"` with your actual email


credentials. Keep in mind that using JavaMail to send emails may require enabling less
secure app access in your email account settings or using OAuth2 authentication for more
secure access.

SUMMARY
Sure, here's a summary of how to send an email in an Android app using the JavaMail API:

1. Dependencies:

- Include the JavaMail API dependencies in your project, such as `com.sun.mail:android-


mail` and `com.sun.mail:android-activation`.

2. Email Sending Function:

- Create a class (e.g., `EmailSender`) that extends `AsyncTask<Void, Void, Void>` to


perform email sending in the background.

- Configure properties for the email server (e.g., SMTP settings for Gmail).
- Implement a `doInBackground` method that sets up the email message and sends it using
the JavaMail API's `Transport.send` method.

3. Usage:

- In your activity or fragment, create an instance of `EmailSender` with the sender's email
credentials, recipient's email, subject, and message body.

- Execute the `EmailSender` instance using `execute()` to send the email in the
background.

4. Important Considerations:

- Ensure proper permission handling and network operations on a background thread to


avoid UI blocking.

- Use real email credentials for authentication (`username` and `password`).

- Handle potential exceptions (e.g., `MessagingException`) when sending the email.

- Consider security measures, such as enabling less secure app access or using OAuth2
authentication for email access.

By following these steps and considerations, you can implement email sending functionality
in your Android app using the JavaMail API.

You might also like