I' writing an app to send phone location after receiving an SMS request. Receiving SMS's works and sending SMS works too. What to do to make it send SMS after receiving one?
MainActivity
final static String gpsLocationProvider = LocationManager.GPS_PROVIDER;
final static String networkLocationProvider = LocationManager.NETWORK_PROVIDER;
static String loc;
public LocationManager locationManager;
static TextView messageBox;
public void sendSMS(String phoneNumber, String message)
{
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageBox = (TextView)findViewById(R.id.messageBox);
locationManager =
(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLocation_byGps =
locationManager.getLastKnownLocation(gpsLocationProvider);
Location lastKnownLocation_byNetwork =
locationManager.getLastKnownLocation(networkLocationProvider);
if (lastKnownLocation_byGps != null) {
loc = "gps " + lastKnownLocation_byGps.getLatitude();
}
if (lastKnownLocation_byNetwork != null) {
loc = "net lat:" + lastKnownLocation_byNetwork.getLatitude() + " long:" + lastKnownLocation_byNetwork.getLongitude();
}
}
public static void updateMessageBox(String msg) {
messageBox.setText(msg);
}
Receiver
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle=intent.getExtras();
Object[] messages=(Object[])bundle.get("pdus");
SmsMessage[] sms=new SmsMessage[messages.length];
for(int n=0;n<messages.length;n++){
sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg:sms){
MainActivity.updateMessageBox("\nFrom: "+msg.getOriginatingAddress()+"\n"+
"Message: "+msg.getMessageBody());
}
}
Where to put sendSMS method to send SMS after receiving one?
You can call your send sms code statements at the end of onReceive method, because this method executes when you receive a sms.
Related
I cannot seem to figure out as to why whenever I try to assign an arraylist I recieved from the MainActivity to a public arraylist of a background service SensorService in the service's constructor.
This is my constructor
public SensorService(ArrayList<String> contactListNumber) {
contactNumbers=contactListNumber;
Log.d(TAG, "Inside Constructor");
Log.d(TAG, "SensorService: Phone Numbers = "+contactListNumber);
Log.d(TAG, "SensorService: Input Arraylist Size = "+contactListNumber.size());
Log.d(TAG, "SensorService: Assigned Arraylist Size = "+contactNumbers.size());
setPhoneNumberArray(contactListNumber);
}
I even tried invoking a method but it still gives me the same results where it assigns the contactNumbers correctly but when I try to invoke it inside onCreate I get an NullPointerException.
This is the MainActivity Intent where I create the service
SensorService sensorService = new SensorService(Contact_Number);
Intent intent = new Intent(this, sensorService.getClass());
if(!isMyServiceRunning(sensorService.getClass())){
startService(intent);
//intent.putExtra("ContactNumberList", Contact_Number);
Toast.makeText(this, "Starting Service", Toast.LENGTH_SHORT).show();
}
And this is my complete SensorService.
public class SensorService extends Service {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
public ArrayList<String> contactNumbers;
public SensorService() {
}
public SensorService(ArrayList<String> contactListNumber) {
contactNumbers=contactListNumber;
Log.d(TAG, "Inside Constructor");
Log.d(TAG, "SensorService: Phone Numbers = "+contactListNumber);
Log.d(TAG, "SensorService: Input Arraylist Size = "+contactListNumber.size());
Log.d(TAG, "SensorService: Assigned Arraylist Size = "+contactNumbers.size());
setPhoneNumberArray(contactListNumber);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
//contactNumbers=MainActivity.Contact_Numbers;
super.onCreate();
// start the foreground service
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
// ShakeDetector initialization
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector();
Log.d(TAG, "SensorService: Assigned Arraylist Size Outside Constructor = "+contactNumbers.size());
mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {
#SuppressLint("MissingPermission")
#Override
public void onShake(int count) {
// check if the user has shacked
// the phone for 3 time in a row
//if (count == 3)
if (count == 1) {
// vibrate the phone
vibrate();
Log.d(TAG, "onShake: Vibrate Activated");
// create FusedLocationProviderClient to get the user location
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
Log.d("Check: ", "Sending Message");
// use the PRIORITY_BALANCED_POWER_ACCURACY
// so that the service doesn't use unnecessary power via GPS
// it will only use GPS at this very moment
fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, new CancellationToken() {
#Override
public boolean isCancellationRequested() {
return false;
}
#NonNull
#Override
public CancellationToken onCanceledRequested(#NonNull OnTokenCanceledListener onTokenCanceledListener) {
return null;
}
}).addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// check if location is null
// for both the cases we will
// create different messages
Log.d("Check: ", "MESSAGE SENT");
if (location != null) {
// get the SMSManager
SmsManager smsManager = SmsManager.getDefault();
// get the list of all the contacts in Database
DatabaseHelper db = new DatabaseHelper(SensorService.this);
ArrayList<String> Contact_id, Contact_Name, Contact_Number;
ArrayList<String> phonenumber = new ArrayList<String>();
Log.d(TAG, "onSuccess: contactlistnumber size = "+contactNumbers.size());
String[] phoneNumberList = new String[contactNumbers.size()];
phoneNumberList = contactNumbers.toArray(phoneNumberList);
Log.d(TAG, "onSuccess: Item 1 = "+phoneNumberList[0]);
for(int i = 0; i < phoneNumberList.length ; i++){
Log.d("Number is",(String)phoneNumberList[i]);
}
//phonenumber = (ArrayList<String>)getIntent().getSerializableExtra("ContactNumberList");
// send SMS to each contact
for (String c : phoneNumberList) {
String message = "Hey, I am in DANGER, i need help. Please urgently reach me out. Here are my coordinates.\n " + "http://maps.google.com/?q=" + location.getLatitude() + "," + location.getLongitude();
smsManager.sendTextMessage(c, null, message, null, null);
}
} else {
String message = "I am in DANGER, i need help. Please urgently reach me out.\n" + "GPS was turned off.Couldn't find location. Call your nearest Police Station.";
SmsManager smsManager = SmsManager.getDefault();
DatabaseHelper db = new DatabaseHelper(SensorService.this);
List<ContactInfo> list = (List<ContactInfo>) db.getEveryone();
String[] phoneNumberList = new String[contactNumbers.size()];
phoneNumberList = contactNumbers.toArray(phoneNumberList);
for (String c : phoneNumberList) {
smsManager.sendTextMessage(c, null, message, null, null);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("Check: ", "OnFailure");
String message = "I am in DANGER, i need help. Please urgently reach me out.\n" + "GPS was turned off.Couldn't find location. Call your nearest Police Station.";
SmsManager smsManager = SmsManager.getDefault();
DatabaseHelper db = new DatabaseHelper(SensorService.this);
List<ContactInfo> list = (List<ContactInfo>) db.getEveryone();
String[] phoneNumberList = new String[contactNumbers.size()];
phoneNumberList = contactNumbers.toArray(phoneNumberList);
for (String c : phoneNumberList){
smsManager.sendTextMessage(c, null, message, null, null);
}
}
});
}
}
});
// register the listener
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}
// method to vibrate the phone
public void vibrate() {
final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
VibrationEffect vibEff;
// Android Q and above have some predefined vibrating patterns
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
vibEff = VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK);
vibrator.cancel();
vibrator.vibrate(vibEff);
} else {
vibrator.vibrate(500);
}
}
// For Build versions higher than Android Oreo, we launch
// a foreground service in a different way. This is due to the newly
// implemented strict notification rules, which require us to identify
// our own notification channel in order to view them correctly.
#RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground() {
String NOTIFICATION_CHANNEL_ID = "example.permanence";
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("You are protected.")
.setContentText("We are there for you")
// this is important, otherwise the notification will show the way
// you want i.e. it will show some default notification
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
#Override
public void onDestroy() {
// create an Intent to call the Broadcast receiver
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, ReactivateService.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
}
public void setPhoneNumberArray(ArrayList numbers) {
contactNumbers=numbers;
//Log.d(TAG, "setPhoneNumberArray: contactnumbers size = "+contactNumbers.size());
}
}
would really appreciate if anyone could tell me why this is happening.
I found my mistake.
For anyone else trying to do this.
I made the very shortsighted mistake of not declaring the Arraylist contactNumbers as static.
This is what it looked like before.
public ArrayList<String> contactNumbers;
In the end when I added the static keyword. such that it looks like
static public ArrayList<String> contactNumbers;.
Everything else seems to work corrrectly. Since I could now get the value of contactNumbers inside of the service.
I have java class to programatically send an SMS from an android application. I want to generate a report after sending the meesage for that i need the status of the message activity which are
sending status;
receiving status;
Both the status are displaying properly in the toast , But when i tries to set the setter for these it returns me the default values. May be because the
mContext.registerReceiver(new BroadcastReceiver() ........... is on a different thread , How i can set the setter or can fetch te sending status from this function block?
public class SMSSending
{
private String phoneNo;
private String message;
private Context mContext;
Settings.Global global;
public void setSendingStatus(String sendingStatus) {
this.sendingStatus = sendingStatus;
}
private String sendingStatus;
public void setReceivingStatus(String receivingStatus) {
this.receivingStatus = receivingStatus;
}
private String receivingStatus;
public SMSSending(String phoneNo, Context mContext, String testID)
{
this.phoneNo = phoneNo;
this.mContext = mContext;
message = "This is a test message from " + testID;
}
public String getSendingStatus()
{
return sendingStatus;
}
public String getReceivingStatus()
{
return receivingStatus;
}
public void sendingMessage()
{
try
{
sendingStatus = "Failed to send SMS message";
receivingStatus = "Failed to deliver SMS ";
String SENT = "sent";
String DELIVERED = "delivered";
PendingIntent sentPI = PendingIntent.getBroadcast(mContext, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(mContext, 0,new Intent(DELIVERED), 0);
//setSendingStatus("Transmission successful");
//Register for SMS send action
mContext.registerReceiver(new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
switch (getResultCode())
{
case Activity.RESULT_OK:
sendingStatus = "Transmission successful";
break;
default:
sendingStatus = "Transmission failure";
break;
}
// Save sendingStatus in Database as test report for sending message.
Toast.makeText(mContext, sendingStatus,Toast.LENGTH_LONG).show();
setSendingStatus(sendingStatus);
}
}, new IntentFilter(SENT));
/* Register for Delivery event */
mContext.registerReceiver(new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
receivingStatus = "SMS Delivered Succesfully";
// Save sendingStatus in Database as test report for receiving message.
// This function will only be executed if message has been successful received
Toast.makeText(mContext, receivingStatus, Toast.LENGTH_LONG).show();
setReceivingStatus(receivingStatus);
}
},new IntentFilter(DELIVERED));
enter code here
//Send SMS
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, sentPI, deliveredPI);
}
catch (Exception ex)
{
sendingStatus = "Failed to send SMS message";
receivingStatus = "Failed to deliver SMS ";
}
}
I have an SMS reader application and i am showing the senderno and message body into the Custom Listview. For the incoming messages i have registered a broadcast receiver and populating the listView.
Whenever a new message is coming in the broadcast Receiver i am able to get it but I want to this data to be passed onto the activity.
The code snippets are :
MainActvity.java
public class MainSmsActivity extends Activity{
private ListView smsList;
SmsAdapter smsAdapter;
private SmsDao smsDao;
private List<SmsDao> smsDataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_demo);
smsDataList = new ArrayList<SmsDao>();
Intent intent = new Intent();
intent.setAction("com.mobile.sms.IncomingSms");
sendBroadcast(intent);
populateSms();
}
public void populateSms(){
Uri inboxURI = Uri.parse("content://sms/inbox");
String[] reqCols = new String[] { "_id", "address", "body", "date" };
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(inboxURI, reqCols, null, null, null);
smsDataList.clear();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
smsDao = new SmsDao();
smsDao.setMessageBody(cursor.getString(1));
smsDao.setSenderNo(cursor.getString(2));
smsDao.setMessageTime(cursor.getLong(3));
smsDataList.add(smsDao);
}
smsAdapter = new SmsAdapter(this,smsDataList);
smsList.setAdapter(smsAdapter);
smsAdapter.notifyDataSetChanged();
cursor.close();
}
}
IncomingSms.Java
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
int duration = Toast.LENGTH_LONG; // HERE I WANT TO SEND MESSAGE BODY TO THE MAIN ACTIVITY CLASS
Toast toast = Toast.makeText(context,
"senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
I am able to receive all the messages intially into the list view but I want that the ListView should get automatically updated as soon as new message arrives.
In your broadcasereceiver do something like this: (use that intent)
public class SMSReceiver extends BroadcastReceiver {
public static final String NOTIFICATION = "receiver_sms";
#Override
public void onReceive(Context context, Intent intent) {
Log.i("onReceive methode", "new SMS Comming");
Bundle myBundle = intent.getExtras();
SmsMessage[] messages = null;
String strMessage = "", address = "";
abortBroadcast();
if (myBundle != null) {
// get message in pdus format(protocol description unit)
Object[] pdus = (Object[]) myBundle.get("pdus");
// create an array of messages
messages = new SmsMessage[pdus.length];
Log.i("onReceive methode", "new SMS Comming");
for (int i = 0; i < messages.length; i++) {
// Create an SmsMessage from a raw PDU.
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// get the originating address (sender) of this SMS message in
// String form or null if unavailable
address = messages[i].getOriginatingAddress();
// get the message body as a String, if it exists and is text
// based.
strMessage += messages[i].getMessageBody();
strMessage += "\n";
}
// show message in a Toast
}
// this is what you need
Intent broadcast = new Intent(NOTIFICATION);
broadcast.putExtra("data", strMessage);
LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast);
}
and then register ur receiver in ur activity
public BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(tag, "SMS Received.");
// Intent i = getIntent();
Bundle b = intent.getBundleExtra("SMS");
// String bun = b.getString("MyData");
Log.i(tag, "Bundle: " + b);
String str = intent.getStringExtra("data");
parseSMSData(str);
}
};
and then in onResume():
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter(SMSReceiver.NOTIFICATION));
}
and in onDestroy() you must unregister that receiver like this:
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onDestroy();
}
and also don't forget to add this in ur manifest file in application tag:
<receiver android:name=".SMSBroadcastReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
register your service in OnResume() then you can access easily within your class,
#Override
public void onResume()
{
super.onResume();
this.registerReceiver(this.yourservice, new IntentFilter("your service type"));
}
and unregister the service in your onpause()
#Override
public void onPause() {
super.onPause();
try
{
this.unregisterReceiver(this.your service);
}
catch(Exception e)
{
e.printStackTrace();
}
}
add the your broadcast receiver in your activity ,
private WakefulBroadcastReceiver IncomingSms = new WakefulBroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//use your receiver content
}
Put the following class in your MainSmsActivity so that you should be able to process your list.
private class IncomingSms extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("incomingSms")) {
//your impl here
}
}
}
and in onCreate() of your MainSmsActivity activity, place the following code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
IncomingSms broadcastReceiver = new IncomingSms(); // declare it outside so that it should be accessible in onDestroy()
IntentFilter intentFilter = new IntentFilter("incomingSms");
registerReceiver(broadcastReceiver , intentFilter);
}
and in onDestroy() place the following code
#Override
protected void onDestroy() {
if (broadcastReceiver != null) {
unregisterReceiver(broadcastReceiver);
}
super.onDestroy();
}
I am working on an application that needs to read an incoming message. Now, i found out that i need to use the onReceive method from the BroadcastReceiver class. Now i got to know that java does not allow extending two classes, so how do i get it working, i have been stuck on this from a long time, please help! Also if there is some other way to do this, please do quote.
public class SMS extends Activity {
Button btnSendSMS;
EditText txtPhoneNo;
EditText txtMessage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sms);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String phoneNo = txtPhoneNo.getText().toString();
if (phoneNo.length()>0)
sendSMS(phoneNo, phoneNo);
else
Toast.makeText(getBaseContext(),
"Please enter a valid Phone Number.",
Toast.LENGTH_SHORT).show();
}
});
}
private void sendSMS(String phoneNumber, String message)
{
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, SMS.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
}
Context context = getApplicationContext();
Intent intent = new Intent();
object.onReceive(context, intent); }
class SMSBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SMSBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
Toast.makeText(context, "HI", Toast.LENGTH_SHORT).show();
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
if (messages.length > -1) {
Toast.makeText(context, "Message recieved: " + messages[0].getMessageBody(), 7000).show();
}
}
}
} }
You don't need to extend two classes (which is not possible and never required in java) to achieve your goal. For getting the last message simply create a static message variable, lets say in your SMSBroadcastReceiver and set that variable to latest message received in onreceive. This static variable can be accessed throughout your app using SmsReceiver.latestmessage
I have a receiver that is called whenever an SMS is received
public class SMSReceiver extends BroadcastReceiver {
private SharedPreferences prefs;
private String prefName = "MyPref";
private static final String NUMBER_KEY = "number";
#Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
String Sender = null;
if (bundle != null) {
// ---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
Sender = msgs[i].getOriginatingAddress();
}
prefs = context
.getSharedPreferences(prefName, Context.MODE_PRIVATE);
String phoneNumber = (String) prefs.getString(NUMBER_KEY, "");
// If the sender of the SMS just received is the same as one chosen
// earlier
if (Sender.equals(phoneNumber)) {
Toast.makeText(context, "text message received",
Toast.LENGTH_LONG).show();
// ---Launch the minderActivity even when the app is not in the
// foreground---
Intent minderActivityIntent = new Intent(context, Minder.class);
minderActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(minderActivityIntent);
// ---send a broadcast intent to update the SMS received in the
// activity---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("Sender", Sender);
context.sendBroadcast(broadcastIntent);
}
}
}
}
I register the receiver in an activity called "minder" using a button
registerReceiver(intentReceiver, intentFilter);
In this "minder" activity I also have a BroadcastReceiver
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// ---gather up all the necessary user input---
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
final Button btn2 = (Button) findViewById(R.id.btnContacts);
String phoneNumber = (String) prefs.getString(NUMBER_KEY, "");
String messageChosen = (String) prefs.getString(MESSAGE_KEY, "");
String delay = (String) prefs.getString(DELAY_KEY, "");
String Sender = (String) intent.getExtras().getString("Sender");
if (Sender.equals(phoneNumber)) {
sendSMS(phoneNumber, messageChosen, delay);
}
}
};
All of the permissions are defined in the manifest.
Unfortunately when I test the receiver (i.e. send an sms to the phone, after the receiver has been registered, from the number that is defined as "phoneNumber") the app performs no action. Any ideas what is missing from my above code?