I have an android app which forward sms to email. In this script i check desired phone number but it only one number. I want to receive some phone number and check this.
public class SmsReceiver extends BroadcastReceiver {
code
private static final String TAG = "SmsReceiver";
private static final String DESIRED_NUMBER = ""; // Replace with your desired sender number
public static final String SMS_MESSAGE_RECEIVED_ACTION = "SMS_MESSAGE_RECEIVED_ACTION";
public static final String SMS_MESSAGE_BODY = "SMS_MESSAGE_BODY";
@Override
public void onReceive(Context context, Intent intent) {
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.getDisplayOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
if (DESIRED_NUMBER.equals(sender)) {
Log.d(TAG, "Received SMS from " + sender + ": " + messageBody);
Toast.makeText(context, "SMS from desired sender: " + messageBody, Toast.LENGTH_SHORT).show();
// Start the EmailService to send this message via email
Intent emailIntent = new Intent(context, EmailService.class);
emailIntent.putExtra("message_body", messageBody);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(emailIntent);
} else {
context.startService(emailIntent);
}
// Send a local broadcast
Intent localIntent = new Intent(SMS_MESSAGE_RECEIVED_ACTION);
localIntent.putExtra(SMS_MESSAGE_BODY, messageBody);
LocalBroadcastManager.getInstance(context).sendBroadcast(localIntent);
}
}
}
}
}
Assistant
User
Assistant
User
What is sms_item.xml file? Explain where should it be. And rewrite MainActivity code in Kotlin
Assistant
User
How to add an app icon?
Assistant
}
To enhance your script so it can check against multiple phone numbers instead of just one, you can use a list or an array of desired numbers. Here's how you can modify your SmsReceiver class to achieve this:
Replace the single desired number with a list of desired numbers.
Check if the sender's phone number exists in this list before proceeding with forwarding the SMS.
Here is the updated code:
java
package com.example.smstoemailforwarder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.util.Arrays;
import java.util.List;
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "SmsReceiver";
// Add your desired sender numbers here
private static final List<String> DESIRED_NUMBERS = Arrays.asList(
"+1234567890", // Replace with your desired sender numbers
"+0987654321"
);
public static final String SMS_MESSAGE_RECEIVED_ACTION = "SMS_MESSAGE_RECEIVED_ACTION";
public static final String SMS_MESSAGE_BODY = "SMS_MESSAGE_BODY";
@Override
public void onReceive(Context context, Intent intent) {
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.getDisplayOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
if (DESIRED_NUMBERS.contains(sender)) {
Log.d(TAG, "Received SMS from " + sender + ": " + messageBody);
Toast.makeText(context, "SMS from desired sender: " + messageBody, Toast.LENGTH_SHORT).show();
// Start the EmailService to send this message via email
Intent emailIntent = new Intent(context, EmailService.class);
emailIntent.putExtra("message_body", messageBody);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(emailIntent);
} else {
context.startService(emailIntent);
}
// Send a local broadcast
Intent localIntent = new Intent(SMS_MESSAGE_RECEIVED_ACTION);
localIntent.putExtra(SMS_MESSAGE_BODY, messageBody);
LocalBroadcastManager.getInstance(context).sendBroadcast(localIntent);
}
}
}
}
}
}
Explanation
List of Desired Numbers: We are using Arrays.asList to create a list of desired sender phone numbers.
Checking for Multiple Numbers: The condition if (DESIRED_NUMBERS.contains(sender)) checks if the sender's number exists in the list of desired numbers.
This approach allows your app to handle multiple sender numbers effectively, ensuring more flexibility and usability. Don't forget to replace the placeholder phone numbers in the DESIRED_NUMBERS list with the actual sender phone numbers you want to check against.
How to display last 10 SMS which has been forwarded to email?
Now SmsReceiver.java file looking like that. Add interface to this android app. I want to see on screen last 10 SMS where should be a phone number, time and message
public class SmsReceiver extends BroadcastReceiver {
code
private static final String TAG = "SmsReceiver";
// private static final String DESIRED_NUMBER = ""; // Replace with your desired sender number
// Add your desired sender numbers here
private static final List DESIRED_NUMBERS = Arrays.asList(
"1", // Replace with your desired sender numbers
"2"
);
code
public static final String SMS_MESSAGE_RECEIVED_ACTION = "SMS_MESSAGE_RECEIVED_ACTION";
public static final String SMS_MESSAGE_BODY = "SMS_MESSAGE_BODY";
@Override
public void onReceive(Context context, Intent intent) {
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.getDisplayOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
if (DESIRED_NUMBERS.contains(sender)) {
Log.d(TAG, "Received SMS from " + sender + ": " + messageBody);
Toast.makeText(context, "SMS from desired sender: " + messageBody, Toast.LENGTH_SHORT).show();
// Start the EmailService to send this message via email
Intent emailIntent = new Intent(context, EmailService.class);
emailIntent.putExtra("message_body", messageBody);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(emailIntent);
} else {
context.startService(emailIntent);
}
// Send a local broadcast
Intent localIntent = new Intent(SMS_MESSAGE_RECEIVED_ACTION);
localIntent.putExtra(SMS_MESSAGE_BODY, messageBody);
LocalBroadcastManager.getInstance(context).sendBroadcast(localIntent);
}
}
}
}
}
}
To display the last 10 SMS messages that have been forwarded to email on the screen with the phone number, time, and message content, you can follow these steps:
Modify SmsReceiver to Store Messages: Store the SMS details in a shared storage (such as SharedPreferences) or in-memory list.
Create a UI for Display: Use RecyclerView to display the last 10 SMS messages in the main activity.
Update UI When New SMS is Forwarded: Update the UI using LocalBroadcastManager when a new SMS is received and forwarded.
Here's how you can achieve this:
Step 1: Modify SmsReceiver to Store Messages
First, modify the SmsReceiver to store the SMS details each time an SMS is forwarded. For simplicity, I'll show how to store the SMS in SharedPreferences.
SmsReceiver.java
java
package com.example.smstoemailforwarder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.LinkedHashSet;
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "SmsReceiver";
private static final List<String> DESIRED_NUMBERS = Arrays.asList(
"1", // Replace with your desired sender numbers
"2"
);
public static final String SMS_MESSAGE_RECEIVED_ACTION = "SMS_MESSAGE_RECEIVED_ACTION";
public static final String SMS_MESSAGE_BODY = "SMS_MESSAGE_BODY";
@Override
public void onReceive(Context context, Intent intent) {
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.getDisplayOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
if (DESIRED_NUMBERS.contains(sender)) {
Log.d(TAG, "Received SMS from " + sender + ": " + messageBody);
Toast.makeText(context, "SMS from desired sender: " + messageBody, Toast.LENGTH_SHORT).show();
// Save the message to SharedPreferences
storeMessage(context, sender, timestamp, messageBody);
// Start the EmailService to send this message via email
Intent emailIntent = new Intent(context, EmailService.class);
emailIntent.putExtra("message_body", messageBody);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(emailIntent);
} else {
context.startService(emailIntent);
}
// Send a local broadcast
Intent localIntent = new Intent(SMS_MESSAGE_RECEIVED_ACTION);
localIntent.putExtra(SMS_MESSAGE_BODY, messageBody);
LocalBroadcastManager.getInstance(context).sendBroadcast(localIntent);
}
}
}
}
}
private void storeMessage(Context context, String sender, String timestamp, String messageBody) {
SharedPreferences prefs = context.getSharedPreferences("sms_prefs", Context.MODE_PRIVATE);
Set<String> messages = prefs.getStringSet("messages", new LinkedHashSet<>());
// Add new message
messages.add(String.format("%s|%s|%s", sender, timestamp, messageBody));
// Keep only the last 10 messages
while (messages.size() > 10) {
String first = messages.iterator().next();
messages.remove(first);
}
prefs.edit().putStringSet("messages", messages).apply();
}
}
Step 2: Create a UI for Display
Next, create the MainActivity with a RecyclerView to display the last 10 SMS messages.
Finally, update your MainActivity to load and display the list of SMS messages when the app starts and when a new SMS is received.
MainActivity.java
java
package com.example.smstoemailforwarder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private SmsAdapter adapter;
private List<String> smsList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
loadMessages();
adapter = new SmsAdapter(smsList);
recyclerView.setAdapter(adapter);
// Register a local broadcast receiver to update the list when a new SMS is forwarded
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
loadMessages();
adapter.notifyDataSetChanged();
}
}, new IntentFilter(SmsReceiver.SMS_MESSAGE_RECEIVED_ACTION));
}
private void loadMessages() {
SharedPreferences prefs = getSharedPreferences("sms_prefs", MODE_PRIVATE);
Set<String> messages = prefs.getStringSet("messages", new LinkedHashSet<>());
smsList = new ArrayList<>(messages);
}
}
With these changes, your app will now display the last 10 SMS messages, including the phone number, time, and message body, in a RecyclerView in the MainActivity. When a new SMS is received and forwarded, the list will automatically update to include the new message.
The sms_item.xml file is a layout XML file that defines the structure of a single item in the RecyclerView. Each row in the RecyclerView uses this layout to display the sender, timestamp, and message body of each SMS.
Typically, this file should be placed in the res/layout directory of your Android project.
Step-by-Step Guide
Create sms_item.xml Layout File:
Navigate to res/layout in your project directory.
Right-click on layout and select New > Layout resource file.
Let's rewrite the MainActivity in Kotlin. You need to make sure you have a Kotlin-compatible project. If you're using Java and want to add Kotlin, follow the official documentation to include Kotlin support.
MainActivity.kt
kotlin
package com.example.smstoemailforwarder
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.ArrayList
import java.util.LinkedHashSet
class MainActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: SmsAdapter
private var smsList: MutableList<String> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
loadMessages()
adapter = SmsAdapter(smsList)
recyclerView.adapter = adapter
// Register a local broadcast receiver to update the list when a new SMS is forwarded
LocalBroadcastManager.getInstance(this).registerReceiver(object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
loadMessages()
adapter.notifyDataSetChanged()
}
}, IntentFilter(SmsReceiver.SMS_MESSAGE_RECEIVED_ACTION))
}
private fun loadMessages() {
val prefs: SharedPreferences = getSharedPreferences("sms_prefs", Context.MODE_PRIVATE)
val messages: Set<String>? = prefs.getStringSet("messages", LinkedHashSet())
smsList = ArrayList(messages ?: emptySet())
}
}
SmsAdapter.kt
Here is the Kotlin version of your SmsAdapter:
kotlin
package com.example.smstoemailforwarder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class SmsAdapter(private val smsList: List<String>) : RecyclerView.Adapter<SmsAdapter.ViewHolder>() {
class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
val sender: TextView = v.findViewById(R.id.sender)
val timestamp: TextView = v.findViewById(R.id.timestamp)
val message: TextView = v.findViewById(R.id.message)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.sms_item, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val parts = smsList[position].split("|")
holder.sender.text = parts[0]
holder.timestamp.text = parts[1]
holder.message.text = parts[2]
}
override fun getItemCount(): Int {
return smsList.size
}
}
With these steps, your application will now display the last 10 forwarded SMS messages in a RecyclerView on the main screen, complete with the sender's phone number, timestamp, and message content. This should be a good starting point for monitoring and displaying your SMS-forwarding activities in your Android application.
Adding an app icon to your Android application is an essential step to give your app a unique identity. Here’s how you can add an app icon to your Android project:
Step-by-Step Guide
Prepare Your App Icon:
You'll need your app icon in multiple sizes to support different screen densities. Typically, you should prepare icons in the following sizes:
48x48 px (mdpi)
72x72 px (hdpi)
96x96 px (xhdpi)
144x144 px (xxhdpi)
192x192 px (xxxhdpi)
Add the Icons to Your Project:
Navigate to the res directory in your project.
Inside the res directory, find the following directories: mipmap-mdpi, mipmap-hdpi, mipmap-xhdpi, mipmap-xxhdpi, mipmap-xxxhdpi.
Place the corresponding icon in each of these directories.
Using Android Studio's Image Asset Tool
Android Studio provides a built-in tool to generate the necessary icon resources for you. Here’s how to use it:
Open Android Studio and right-click the res folder.
Select New > Image Asset.
Configure the Image Asset:
Icon Type: Select Launcher Icons (Adaptive and Legacy).
Name: Leave it as ic_launcher.
Source Asset:
Select the path of your icon image file.
Adjust the settings as necessary, including the padding and background styling.
Generate Icons:
Click Next and then Finish. Android Studio will generate the app icon in all the necessary sizes and place them correctly in the mipmap directories.
Update the Manifest File
Ensure that your AndroidManifest.xml file is using the new app icon. This file is typically located in the app/src/main directory of your project.
Open AndroidManifest.xml and make sure the application tag includes android:icon attribute pointing to the new icon, like so:
xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!-- Your activities and other components -->
</application>
Final Steps
Rebuild Your Project to ensure the app icon is correctly integrated. You can do this by clicking Build > Rebuild Project in the Android Studio menu.
Run Your App to check if the icon is appearing correctly on the device or emulator.
That’s it! You’ve successfully added an app icon to your Android project. By following these steps, your app will have a distinct icon, making it easily recognizable on users' devices.