I'm trying to develop an android application that sends GPS coordinates via SMS with given time interval.
So I set up my main activity allowing the user to input a specific time in minutes. Transfer it to a alarmReceiver. Every alarm will request a locationupdate. And onlocationChanged will save it to the database before sending it via sms. I save it to the database before sending so that i will not lost any data if sending fails. I'm sending a message like this :
dbcon = new SQLController(ctx);
dbcon.open();
String SENT = "SMS_SENT";
final Cursor C = dbcon.readData_Location();
if(C.moveToFirst()){
getid = C.getString(0);
getLongitude = C.getString(1);
getLatitude = C.getString(2);
getTime = C.getString(3);
int id = Integer.valueOf(getid);
String phoneNo = "09061265887";
String msg = getLongitude +","+getLatitude+","+getTime;
Intent sendIntent = new Intent(SENT);
sendIntent.putExtra("loc_id", id);
PendingIntent sentPI = PendingIntent.getBroadcast(ctx, 0, sendIntent,0);
MainActivity.sendTextMessage(phoneNo, null, msg, sentPI, null);
}while(C.moveToNext());
The problem here is, it will send all the saved locations from the database continuously.
My plan is if the first sending fails, the sending using do-while loop must be stop.
I need to wait and check the result of sending process before sending another one. Im stock here and i dont know that to do. please help
MainActivity
public class MainActivity extends ActionBarActivity {
EditText et_timeinterval;
Button start,stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_timeinterval= (EditText) findViewById(R.id.editText1);
start = (Button) findViewById(R.id.button1);
stop = (Button) findViewById(R.id.button2);
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int timeinminute = Integer.valueOf(et_timeinterval.getText().tostring());
Intent intent = new Intent(getBaseContext(),alarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), timeinminute * 60 * 1000, pendingIntent);
Toast.makeText(ctx, "Alarm Started", Toast.LENGTH_SHORT).show();
}
});
}
public static void sendSMS(String phoneNumber,String message) {
SmsManager smsManager = SmsManager.getDefault();
String SENT = "SMS_SENT";
PendingIntent sentPI = PendingIntent.getBroadcast(basecontext, 0, new Intent(SENT), 0);
// ---when the SMS has been sent---
basecontext.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(basecontext, "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(basecontext, "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(basecontext,"No Service",Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(basecontext, "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(basecontext, "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
// ---when the SMS has been delivered---
smsManager.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
}
alarmReceiver.java
public class alarmReceiver extends BroadcastReceiver implements LocationListener{
private LocationManager locationManager;
private Context ctx;
SQLController dbcon;
String latitude,longitude,time;
#Override
public void onReceive(Context context, Intent arg1) {
// TODO Auto-generated method stub
ctx =context;
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1,1,this);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Time currentTime = new Time(Time.getCurrentTimezone());
currentTime.setToNow();
String latitude = ""+location.getLatitude();
String longitude = ""+location.getLongitude();
String time = currentTime.format("%k:%M:%S");
//inserting to database
dbcon= new SQLController(ctx);
dbcon.open();
dbcon.insertData(latitude, longitude, time);
//sending
String SENT = "SMS_SENT";
Cursor C = dbcon.readData_Location();
if(C.moveToFirst()){
String getid = C.getString(0);
String getLongitude = C.getString(1);
String getLatitude = C.getString(2);
String getTime = C.getString(3);
int id = Integer.valueOf(getid);
String phoneNo = "09061265887";
String msg = getLongitude +","+getLatitude+","+getTime;
MainActivity.sendSMS(phoneNo,msg);
}while(C.moveToNext());
locationManager.removeUpdates(this);
dbcon.close();
}
I want to do something like this
int result_code; //i want to get the resultcode from getResultCode()
C.moveToFirst();
do{
sendSMS(phonenum,sms);
//check first if sendSMS sending process is done before the next loop
}while(C.moveToNext() && result_code==0)
// result code 0 = send success 1=generic failure etc etc
This is not a simple problem. First, since you will want to wait, you need to do this on a background thread (using AsyncTask or a simple thread). Second, if you want it to continue trying/operating after the user exits the activity, you will need a service.
That said, you already have the code in place to check for the "sent" PendingIntent for the message. You need your thread/service to wait for the broadcast receiver responde from the sent message to get a response.
In your "sendSMS" method, you are registering a broadcast receiver to listen for the status of the SMS send. It will tell you whether the send was successful or not, and then you can either continue sending location updates, try again or whatever.
Like this:
basecontext.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(basecontext, "SMS sent",
Toast.LENGTH_SHORT).show();
// add code here to send next message
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(basecontext, "Generic failure",
Toast.LENGTH_SHORT).show();
// add code here to try again or wait
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(basecontext,"No Service",Toast.LENGTH_SHORT).show();
// add code here to try again or wait
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(basecontext, "Null PDU",
Toast.LENGTH_SHORT).show();
// add code here to try again or wait
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(basecontext, "Radio off",
Toast.LENGTH_SHORT).show();
// add code here to try again or wait
break;
}
}
}, new IntentFilter(SENT + someMessageId));
Your intent filter also needs to identify the message (where I added "someMessageId") if you send more than one SMS before waiting for the receiver to respond.
Related
I'm working on a feature in my app that moves a marker to a certain latlng when the user exits the geofence.
Send the broadcast received data to any activity
public class GeofenceBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "GeofenceBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// Toast.makeText(context, "Geofence triggered...", Toast.LENGTH_SHORT).show();
NotificationHelper notificationHelper = new NotificationHelper(context);
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
Log.d(TAG, "onReceive: Error receiving geofence event...");
return;
}
List<Geofence> geofenceList = geofencingEvent.getTriggeringGeofences();
for (Geofence geofence: geofenceList) {
Log.d(TAG, "onReceive: " + geofence.getRequestId());
}
// Location location = geofencingEvent.getTriggeringLocation();
int transitionType = geofencingEvent.getGeofenceTransition();
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
Toast.makeText(context, "You are near the drop off location.", Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("You are near the drop off location", "", Home.class);
break;
case Geofence.GEOFENCE_TRANSITION_DWELL:
Toast.makeText(context, "Pickup/Drop off Location reached.", Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("Pickup/Drop off Location reached.", "", Home.class);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
Toast.makeText(context, "Leaving Pickup/Drop off point.", Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("Leaving Pickup/Drop off point.", "", Home.class);
break;
}
}
}
I tried using intents but failed due to me being a beginner.
Using LocalBroadcastManager, we may transfer data from onReceive to another activity.
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
Intent intent = new Intent("broadCastName"); //new Intent(context, ReceiveText.class);
// Data you need to pass to another activity
intent .putExtra("message", extras.getString(Config.MESSAGE_KEY));
context.sendBroadcast(intent );
}
I'm developing android application which is suppose to send SMS. When first SMS is sent, the onReceive method of Broadcast Receiver shows the status of SMS as SMS Sent and SMS Delievered or Generic Failure depending upon the response received. But when again SMS is sent then onReceiver first shows the status of previous sent messsage and then newer message. Means everytime onReceiver is called it shows the status of every previous sent message. The following class is written by extending Worker so activity life cycle methods like onStop and onResume can't be overridden here.
Any help is appreciated. Code is given below.
PendingIntent sentPI = PendingIntent.getBroadcast(getApplicationContext(), 0,
new Intent(SENT), PendingIntent.FLAG_ONE_SHOT);
PendingIntent deliveredPI = PendingIntent.getBroadcast(getApplicationContext(), 0,
new Intent(DELIVERED), PendingIntent.FLAG_ONE_SHOT);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
status = sms_id + " : SMS Sent";
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
status = sms_id + " : Generic failure ";
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
status = sms_id + " : No service ";
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
status = sms_id + " : Null PDU ";
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
status = sms_id + " : Radio off ";
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
break;
}
}
};
IntentFilter filter = new IntentFilter(SENT);
getApplicationContext().registerReceiver(broadcastReceiver, filter);
//---when the SMS has been delivered---
BroadcastReceiver broadcastReceiver1 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
receiverStatus = sms_id + " : SMS delivered ";
Toast.makeText(context, receiverStatus, Toast.LENGTH_SHORT).show();
addItem(receiverStatus);
break;
case Activity.RESULT_CANCELED:
receiverStatus = sms_id + " : SMS not delivered ";
Toast.makeText(context, receiverStatus, Toast.LENGTH_SHORT).show();
addItem(receiverStatus);
break;
}
}
};
IntentFilter filter1 = new IntentFilter(DELIVERED);
getApplicationContext().registerReceiver(broadcastReceiver1, filter1);
try {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
handler.post(() -> Toast.makeText(getApplicationContext(), " Do Work", Toast.LENGTH_SHORT).show());
return Result.success();
} catch (Exception e) {
handler.post(() -> Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show());
return Result.retry();
}
You are doing plenty of wrong things here. First of all Broadcast Receiver should never be called inside Worker Thread. It always work on UI Thread. So whenever you will create a Work Request Broadcast Receiver is registered and hence will be registered as many times as work request is created. And you are not unregistering it any where.
So it will be executed multiple times.
You should register Broadcast Receiver inside onCreate and unregister it in onStop/onResume. So that they would not be registered twice.
Hope it Helps ;).
I'm trying to develop a basic SMS app, but i'm got a NullPointerException problem.
Well, there is the code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btnSendSMS;
EditText txtPhoneNo;
EditText txtMessage;
sendSMS sendSMS=new sendSMS();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) findViewById(R.id.txtMessage);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},1);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
if (phoneNo.length()>0 && message.length()>0) {
sendSMS.sendSMS(phoneNo, message,getApplicationContext());
}
else
Toast.makeText(getApplicationContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
});
}}
And there is the sendSMS class:
public class sendSMS extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
//---sends an SMS message to another device---
public void sendSMS(String phoneNumber, String message,Context context)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(context, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}}
And there is the log about the error:
FATAL EXCEPTION: main
Process: com.example.lcssgml.appsmsmms, PID: 5861
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Context.registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter)' on a null object reference
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:586)
at com.example.lcssgml.appsmsmms.sendSMS.sendSMS(sendSMS.java:41)
at com.example.lcssgml.appsmsmms.MainActivity$1.onClick(MainActivity.java:46)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22260)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
I can't figure it out the problem. I hope you can help me! Thx
You've made your sendSMS class an Activity subclass, presumably so that the registerReceiver() methods would resolve. You cannot instantiate an Activity with new and have it work correctly. The Context member it keeps will never be properly initialized, which is why you're getting the NullPointerException.
You're already passing a Context into the sendSMS() method, so you can just call registerReceiver() on that.
context.registerReceiver(...);
Furthermore, the sendSMS class should not be an Activity subclass, so you should remove the extends Activity, and the onCreate() override. Also, the sendSMS() method can now be static, so you don't need to create an instance of the class to use it, and can just call the method directly on the class. I would also mention that class names in Java should begin with capital letters.
public class SendSMS {
public static void sendSMS(...) {
...
}
...
}
To call it:
SendSMS.sendSMS(...);
It would be advisable to unregister the Receivers when you're done with them, using Context#unregisterReceiver(). You might find it easier to do this by not using anonymous BroadcastReceiver instances.
I should also point out that the SmsManager#sendTextMessage() method will usually fail silently if you send a message that exceeds the character limit for a single-part message in the alphabet you're using.
My application has the following modules,
To collect users CB location code.
To save that in a database of user's choice, say for example my CB code is 465783 and I can save that as 'College' in my database.
To provide alarm feature, in this module I can give a text input say I give it as 'College' and when the Cell Broadcast is updated if the value college matches alarm is given out.
Now, in my below code I've achieved first 2 modules and also the required database entries, databases search etc, I'm not able to read the updated CB location value.
public class Alarm extends MainActivity {
public String str;
public void onReceive(Context context, Intent intent) {
//---get the CB message passed in---
Bundle bundle = intent.getExtras();
SmsCbMessage[] msgs = null;
str = "";
if (bundle != null) {
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsCbMessage[pdus.length];
for (int i=0; i<msgs.length; i++) {
msgs[i] = SmsCbMessage.createFromPdu((byte[])pdus[i]);
str += "CB " + msgs[i].getGeographicalScope() + msgs[i].getMessageCode() + msgs[i].getMessageIdentifier() + msgs[i].getUpdateNumber();
str += " :";
str += "\n";
}
}
}
EditText user_value;
Button startalarm;
Button stopalarm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
startalarm = (Button) findViewById(R.id.startalarm);
stopalarm = (Button) findViewById(R.id.stopalarm);
user_value = (EditText) findViewById(R.id.user_value);
final Ringtone ringtone;
ringtone = RingtoneManager.getRingtone(getBaseContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
startalarm.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(user_value.length()==0)
{
Toast.makeText(getBaseContext(), "Please enter a value.", Toast.LENGTH_LONG).show();
}
Toast.makeText(getApplicationContext(), "alarm set", Toast.LENGTH_LONG).show();
//I want my alarm event to be started from here whenever a new CB sms arrives.
SQLiteDatabase aa = openOrCreateDatabase("MLIdata", MODE_WORLD_READABLE, null);
Cursor c = aa.rawQuery("SELECT CblocationName FROM MLITable WHERE CblocationCode = '"+str+"'", null);
c.moveToFirst();
c.getString(c.getColumnIndex("CblocationName"));
String sas = user_value.getText().toString();
if(sas.equals(c.getString(c.getColumnIndex("CblocationName"))))
{
//here comes the alarm code
if(ringtone == null)
{
Log.d("Debug", "ringtone is null");
}
else
{
ringtone.play();
}
}
}
});
stopalarm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
ringtone.stop();
}
});
}
}
Detailed Explanation : whenever a user enters a new tower location he gets the updated Cell Broadcast message from the tower, so when this cbsms arrives I need to start my event of retrieving the CB area code and compare it with my database of area codes (which obviously have corresponding area code names set by the user) and when there is a match between the user given area name's corresponding area code with my current area code an alarm needs to be started, here I'm not able to do detect the arrival of updated location.
If further explanation is required of my problem statement, please comment.
From the comments received below, I've deduced that I'd need a receiver class, I've created one for my widget which does the same function (Displays the Cb location code on the widget), Now I do not how to activate that in my app.
My WidgetReceiver.java
public class CbReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent) {
//---get the CB message passed in---
Bundle bundle = intent.getExtras();
SmsCbMessage[] msgs = null;
String str = "";
if (bundle != null) {
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsCbMessage[pdus.length];
for (int i=0; i<msgs.length; i++) {
msgs[i] = SmsCbMessage.createFromPdu((byte[])pdus[i]);
str += "CB " + msgs[i].getGeographicalScope() + msgs[i].getMessageCode() + msgs[i].getMessageIdentifier() + msgs[i].getUpdateNumber();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
abortBroadcast();
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget);
ComponentName thisWidget = new ComponentName(context,MyWidget.class);
remoteViews.setTextViewText(R.id.update,str);
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
}}
}
Help required.
Thank you.
Start your activity from your receiver on tower change. Use Intents to start your activity from receivers.
Ex: Refer this alarm example for above point, Alarm Example
Register your receiver in Android Manifest.xml.
Send a broadcast message from your receiver class also update your DB inside your receiver.
Catch the same in your activity. You can use Custom Broadcast for this.
Now activate your alarm in activity.
Hope these steps will help you. Refer the example I have mentioned.
I have a question about an SMS app i am creating (learning purposes).
On sending an SMS i would like to have a toast message appear once it has been deleivered (or not)
Problem is once i have hit send i would like to close the activity but still have the toast message (in this case) appear giving me the info.
As i am new to this i am not sure how to go about this. All i have done is wait for the information to come through, set up the message then close the activity.
private void sendSMS() {
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), PendingIntent.FLAG_NO_CREATE);
deliverActivity = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_LONG).show();
finishActivity();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_LONG).show();
finishActivity();
break;
}
}
};
registerReceiver(deliverActivity, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(toNo, null, toSend.getText().toString(), deliveredPI, null);
ContentValues values = new ContentValues();
values.put("address", toNo);
values.put("body", toSend.getText().toString());
this.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
}
private void finishActivity() {
unregisterReceiver(deliverActivity);
Intent intent = new Intent();
setResult(123, intent);
finish();
}
Im sure this is possible somehow, even to pass it possibly to another activity.
It probably sounds a bit pedantic but it allows me to learn new ways of doing things... so if anyone can point me in the right direction that'd be great.
Thanks!
There are ways to show the toast after an activity is closed, for example see this question:
Android: Show toast after finishing application / activity
See this as well.