error when inserting data into database when multiple sms is sent - android

I have designed my own compose screen for sending sms,
in that when send button is clicked
I am sending msg to multiple recepients
sendBTN.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
avedPhoneno = "5558,5554,5556";
StringTokenizer st = new StringTokenizer(savedPhoneno, ",");
while (st.hasMoreElements()) {
tempMobileNumber = (String) st.nextElement();
System.out.println("tempMobileNumber in onclicklistener "+tempMobileNumber);
if (tempMobileNumber.length() > 0
&& encryptedText.toString().trim().length() > 0) {
sendSMS(tempMobileNumber,
base64msgString.concat(timeStamp1));
} else {
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
}
and the method for sending sms is
private void sendSMS(String edittextSmsNumber, String msg) {
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SMS_SENT), 0);
PendingIntent DeliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(SMS_DELIVERED), 0);
SmsManager sms = SmsManager.getDefault();
// short port = 8888;
sms.sendTextMessage(edittextSmsNumber, null, msg, sentPI, DeliveredPI);
}
and in the broadcast reciever i am trying to store the data into database
private BroadcastReceiver sendreceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String info = "Send information: ";
switch(getResultCode())
{
case Activity.RESULT_OK:
info += "send successful";
smsSent = true;
if (senderinfo != null && timeStamp != 0 && msgString != null) {
System.out.println("entered into database");
System.out.println("tempMobileNumber is "
+ tempMobileNumber);
outboxDatabase.open();
outboxDatabase.insertintoOutbox(msgString, key,
tempMobileNumber, timeStamp);
outboxDatabase.close();
}
//unregisterReceiver(this);
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
info += "send failed, generic failure";
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
info += "send failed, no service";
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
info += "send failed, null pdu";
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
info += "send failed, radio is off";
break;
}
Toast.makeText(getBaseContext(), info, Toast.LENGTH_SHORT).show();
}
};
but I am able to store the last number i.e., 5556 only in the database thrice.
I want to store all the three numbers into the database.
I want to store when only the msg is sent properly
i.e., when getResultCode() = Activity.RESULT_OK;
able to send to the three numbers but only not able to store in the database
how to overcome this.

Related

android - BroadcastReceiver not calling OnReceive when sending SMS

I'm creating an app where part of it will send a message if it meet a certain condition but whenever it is being sent, the receiver does not call onReceive method. I tried all the suggestions from the answered SO questions but nothing helped me fix it. I want to get the report if my SMS is sent with these codes:
BroadcastReceiver class:
public class SendSMS extends BroadcastReceiver {
public SendSMS() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
int resultCode = getResultCode();
switch (resultCode) {
case AppCompatActivity.RESULT_OK:
result = "Message sent.";
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
result = "Error. Message not sent.";
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
result = "Error: No service.";
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
result = "Error: Null PDU.";
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
result = "Error: Radio off.";
break;
}
}
}
Sending text class:
public class SMSSender {
private Context context;
private final int MAX_SMS_MESSAGE_LENGTH = 160;
private final String SMS_SENT = "sent";
private final String SMS_DELIVERED = "delivered";
public SMSSender(Context context) {
this.context = context;
}
public void sendSMS(String phoneNumber, String message) {
SendSMS brSendSMS = new SendSMS();
try {
//##### Also tried all kinds of context ###### //
PendingIntent piSend = PendingIntent.getBroadcast(context.getApplicationContext(), 0, new Intent(SMS_SENT), 0);
int length = message.length();
context.getApplicationContext().registerReceiver(brSendSMS, new IntentFilter(SMS_SENT));
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, piSend, null);
} catch (Exception ex) {
Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
} finally {
context.getApplicationContext().unregisterReceiver(brSendSMS);
}
}
}
And to test this, I placed it in button clicked method.
SMSSender smsSender = new SMSSender(this);
smsSender.sendSMS("000000", "TESTING ONLY");
What am I doing wrong here? I also learned that it uses my default sms app stating "Not sent. Tap to try again".

How do I implelment Android 6.0 Runtime Permissions On Existing App

Problem:
I have an existing app that I would like to implement Android 6.0's Runtime Permissions on. I have read a lot of different things on Runtime Permissions, but I just can't seem to wrap my head around all the different snippets. Nothing I have found actually shows how to implement this into an existing Activity.
Other Points
When I run my existing application targeting SDK v23 I get the permission error as expected, but the permission error I get is not even a permission that I am requesting. I have the SEND_SMS permission in the Manifest file, but the error I am getting is for READ_SMS. My app runs fine on pre 6.0 without READ_SMS.
I would like the my app to ask for permission as soon as the app is launched because the sole purpose of the app is the send an SMS message, so without that permission there is no other use for the app.
Questions:
How would I implement Runtime Permissions for SEND_SMS into my existing Activity as soon as the app is launched?
Does the handling of these permission need to run in a background thread?
Do I also need permissions for READ_SMS since that is the permission error that it is giving (even though that permission has never been used on my app)?
My Existing Activity:
public class MainActivity extends Activity implements OnClickListener {
SimpleCursorAdapter mAdapter;
AutoCompleteTextView txtContract;
EditText txtTrip;
EditText txtDate;
Button btnSend;
Button btnUpdate;
String today;
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
private static final String API_KEY = "abcxyz";
private static final String CONTRACT_REGEX = "^([a-zA-Z0-9_-]){5}$";
private static final String TRIP_REGEX = "^([a-zA-Z0-9_-]){1,10}$";
private static final String DATE_REGEX = "^\\d{2}\\/\\d{2}\\/\\d{4}$";
private static final String PHONE_NUMBER = "1234567890";
private static final String DATE_FORMAT = "MM/dd/yyyy";
private BroadcastReceiver sendBroadcastReceiver;
private BroadcastReceiver deliveryBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// TODO - IMPLEMENT RUNTIME PERMISSIONS FOR ANDROID >= 6.0
try {
// Initialize Views
txtContract = (AutoCompleteTextView) findViewById(R.id.txtContract);
txtTrip = (EditText) findViewById(R.id.txtTrip);
txtDate = (EditText) findViewById(R.id.txtDate);
btnSend = (Button) findViewById(R.id.btnSend);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
// Set Listeners
txtDate.setOnClickListener(this);
btnSend.setOnClickListener(this);
btnUpdate.setOnClickListener(this);
// Set Date To Today And Format
final Calendar td = Calendar.getInstance();
int tYear = td.get(Calendar.YEAR);
int tMonth = td.get(Calendar.MONTH);
int tDay = td.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
td.set(tYear, tMonth, tDay);
today = sdf.format(td.getTime());
txtDate.setText(today);
// Check If Device Is Capable Of Sending SMS
PackageManager pm = this.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) &&
!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
Toast.makeText(this, "Sorry, your device probably can't send SMS...",
Toast.LENGTH_SHORT).show();
}
// Send Receiver
sendBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Requesting trip...", 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;
}
}
};
// Delivery Receiver
deliveryBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Trip request successful.", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "Trip request failed.", Toast.LENGTH_SHORT).show();
break;
}
}
};
// Register Receivers
registerReceiver(deliveryBroadcastReceiver, new IntentFilter(DELIVERED));
registerReceiver(sendBroadcastReceiver , new IntentFilter(SENT));
// Set Up Adapter For Autocomplete
initializeAutoCompleteAdapter();
}
catch (Exception ex) {
Toast.makeText(this, "Error in MainActivity.onCreate: " + ex.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDestroy() {
unregisterReceiver(sendBroadcastReceiver);
unregisterReceiver(deliveryBroadcastReceiver);
super.onDestroy();
}
// Auto Complete Adapter
public void initializeAutoCompleteAdapter() {
// Set Database Handler
final DBHelper DBHelper = new DBHelper(getBaseContext());
// Set Up Adapter For Autocomplete (This does not run on the main UI thread)
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null,
new String[] { "contract" },
new int[] {android.R.id.text1},
0);
txtContract.setAdapter(mAdapter);
mAdapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
#Override
public CharSequence convertToString(Cursor cursor) {
final int colIndex = cursor.getColumnIndexOrThrow("contract");
return cursor.getString(colIndex);
}
});
mAdapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence description) {
String strContract = txtContract.getText().toString();
return DBHelper.getContract(strContract);
}
});
}
// OnClickListener Handler
#Override
public void onClick(View v) {
// Handle Clicked View
switch (v.getId()) {
// Date Field
case R.id.txtDate:
// Get Current Date
final Calendar c = Calendar.getInstance();
c.set(c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH),0,0,0);
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
// Set Up DatePicker Dialog
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
// Define A New Calendar For Formatting
final Calendar cf = Calendar.getInstance();
// Format Selected Date
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
cf.set(year,month,day);
String selectedDate = sdf.format(cf.getTime());
// Add Selected Date To EditText Field
txtDate.setText(selectedDate);
}
}, mYear, mMonth, mDay);
// Set Max Date
c.add(Calendar.DATE, 2);
c.add(Calendar.SECOND, -1);
datePickerDialog.getDatePicker().setMaxDate(c.getTimeInMillis());
// Set Min Date
c.add(Calendar.DAY_OF_MONTH,-5);
c.add(Calendar.SECOND, 1);
datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());
// Display DatePicker
datePickerDialog.show();
break;
// Submit Button
case R.id.btnSend:
Boolean rval = true;
if (!Validation.isValid(txtContract, CONTRACT_REGEX, "Invalid Contract #", true)) rval = false;
if (!Validation.isValid(txtTrip, TRIP_REGEX, "Invalid Trip #", true)) rval = false;
if (!Validation.isValid(txtDate, DATE_REGEX, "Invalid Date", true)) rval = false;
if(rval) {
new ValidateAndSend(this).execute();
}
break;
// Update Contract DB
case R.id.btnUpdate:
TelephonyManager tMgr = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
new POSTAsync(this).execute(API_KEY, mPhoneNumber);
break;
}
}
// Validate And Send
class ValidateAndSend extends AsyncTask<String, String, Boolean>{
private final WeakReference<MainActivity> MainActivityWeakRef;
public ValidateAndSend(MainActivity mainActivity) {
super();
this.MainActivityWeakRef = new WeakReference<>(mainActivity);
}
// Define Variables
String strContract = txtContract.getText().toString();
String strTrip = txtTrip.getText().toString();
String strDate = txtDate.getText().toString();
String strMessage = strContract.concat("|").concat(strTrip).concat("|").concat(strDate);
Boolean rval = true;
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(String... contract) {
DBHelper DBHelper = new DBHelper(MainActivity.this);
if (DBHelper.validateContract(strContract) < 1) rval = false;
return rval;
}
#Override
protected void onPostExecute(Boolean rval){
if(rval){
// Hide Keyboard
View view = MainActivity.this.getCurrentFocus();
if(view != null){
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
if (MainActivityWeakRef.get() != null && !MainActivityWeakRef.get().isFinishing()) {
// Confirm Details
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Confirm Trip");
alert.setMessage("CONTRACT: " + strContract + "\nTRIP: " + strTrip + "\nDATE: " + strDate);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Send SMS
sendSMS(PHONE_NUMBER, strMessage);
// Clear Fields
txtContract.setText("");
txtTrip.setText("");
txtDate.setText(today);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Cancelled
}
});
// Show Alert
alert.show();
}
}
else{
txtContract.setError("Invalid contract #");
Toast.makeText(MainActivity.this, "You may need to update contracts.",
Toast.LENGTH_LONG).show();
}
}
}
// Send SMS
private void sendSMS(String phoneNumber, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
}
The runtime permission model for Android 6.0 is mainly divided into part
1. Checking Permission
2. Requesting Permission
you can create two method for this thing in your activity, As follow
Check Permission
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
Request Permission
private void requestPermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,Manifest.permission.READ_SMS)){
Toast.makeText(context,"Read Sms Allowed.",Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.READ_SMS},PERMISSION_REQUEST_CODE);
}
}
Last but not least you need to override the onRequestPermissionsResult method
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Snackbar.make(view,"Permission Granted, Now you can access SMS.",Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(view,"Permission Denied, You cannot access SMS.",Snackbar.LENGTH_LONG).show();
}
break;
}
}
as you asked do i need to run this in thread .. answer is No Just do this in main thread
If you want to do less code then, please use Dexter is an Android library that simplifies the process of requesting permissions at runtime.

SMS GENERIC FAILURE in Dual Sim phones Android

I am using the SMS Manager class to send SMS through my code. The code works well in single sim phones but in some dual SIM phones, it returns me GENERIC FAILURE. I search a lot for this but found no proper solution for this. Please help me out. my code is as,
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
"MY_SMS_SENT"), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent("MY_SMS_DELIVERED"), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, messageBody, sentPI, deliveredPI);
and my receiver is as,
#Override
public void onReceive(Context context, Intent intent) {
//errorCode
if(intent.getAction().equals("MY_SMS_SENT")) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
TelephonyInfo telephonyInfo = TelephonyInfo.getInstance(context);
boolean isSIM1Ready = telephonyInfo.isSIM1Ready();
boolean isSIM2Ready = telephonyInfo.isSIM2Ready();
boolean isDualSIM = telephonyInfo.isDualSIM();
Log.e("IS DUAL SIM", "" + isDualSIM);
Log.e("isSIM1Ready", "" + isSIM1Ready);
Log.e("isSIM2Ready", "" + isSIM2Ready);
if(isDualSIM) {
if(isSIM1Ready || isSIM2Ready) {
Toast.makeText(context, "An Unexpected failure occured while sending SMS. Please check whether you have working SMS plan and try again later.",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "Please activate atleast one SIM for sending SMS and retry.",
Toast.LENGTH_LONG).show();
}
}
else {
if(!isSIM1Ready) {
Toast.makeText(context, "No SIM detected to perform this action.",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "An Unexpected failure occured while sending SMS. Please check whether you have working SMS plan and try again later.",
Toast.LENGTH_LONG).show();
}
}
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(context, "No service available. Please try again later.",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(context, "SMS not sent. Please try again later.",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(context, "SMS Not Sent. Please try again later.",
Toast.LENGTH_SHORT).show();
break;
}
}
else if(intent.getAction().equals("MY_SMS_DELIVERED")) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Log.d("SMS STATUS", "SMS delivered");
/* Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();*/
break;
case Activity.RESULT_CANCELED:
Log.d("SMS STATUS", "SMS not delivered");
/*Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();*/
break;
}
}
}

Android : Schedule SMS at Alarm Manager

I am writing app to schedule SMS from alarm Manager. It works for me only one time and second time onwards it generate the multiple SMS.
Times are saved in SQL LITE and after send a SMS from Broadcast receiver read the DB and set the next alarm.
if 1 SMS has sent, second time it sends 2 SMS. next time 3 sms, and so on. I am using AmarmManager array and PendingIntents array to set alarm.
here is my coding... Please elp me... i am spending fer day for this taks..
public void SetAlarm(MessageInfo info, long delay, int amcount)
{
try
{
AlarmMSGInfo = info;
SaveMSGINFOPreference();
//Save Sent Status to Preference..
//savePreferences("SENT", old);
// register the alarm broadcast here
AMCount = amcount;
registerReceiver(mReceiver, new IntentFilter("com.rememberme.rm") );
//pendingIntent = PendingIntent.getBroadcast( this, 0, new Intent("com.techblogon.alarmexample"),0 );
pendingIntent[amcount] = PendingIntent.getBroadcast( RememberMe.this,amcount, new Intent("com.rememberme.rm"),PendingIntent.FLAG_ONE_SHOT );
alarmManager[amcount] = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
alarmManager[amcount].set( AlarmManager.RTC_WAKEUP, delay , pendingIntent[amcount] );
}
catch(Exception e)
{
//Toast.makeText(RememberMe.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(RememberMe.this, "Alarm cannot be set...", Toast.LENGTH_LONG).show();
}
}
This is my Broadcast receiver ..
private void RegisterAlarmBroadcast()
{
//This is the call back function(BroadcastReceiver) which will be call when your
//alarm time will reached.
mReceiver = new BroadcastReceiver()
{
private static final String TAG = "Alarm Example Receiver";
#Override
public void onReceive(Context context, Intent intent)
{
String s = intent.getAction().toString();
if(intent.getAction() != null )
{
Log.i(TAG,"BroadcastReceiver::OnReceive() >>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
//Toast.makeText(context, "Congrats!. Your Alarm time has been reached", Toast.LENGTH_LONG).show();
MessageInfo temp= LoadMSGINFOPreference();
if(temp == null )
{
}
else
{
String snt = loadSavedPreferences("SENT");
if(snt== "")
Sent = 0;
else
Sent = Integer.valueOf(snt);
int status = 0;
if(Sent == 0)
{
//MessageInfo SentInfo = dbHandler.Get_MessageInfo(Sent);
//status = SentInfo.getStatus();
//}
//Toast.makeText(RememberMe.this, String.valueOf(msgType) , Toast.LENGTH_LONG).show();
//if(status == 0)
//{
if(temp.getMSGType() == 1)
{
_Recipients = ReadPhoneNumbers(temp.getRecipients());
_Message = temp.getMessage();
for(String number:_Recipients)
{
try
{
String num = number;
//Toast.makeText(context, "Congrats!. Your Alarm time has been reached : " + num + ":", Toast.LENGTH_LONG).show();
sendSMS(num, _Message);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(),"SMS faild, please try again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
alarmManager[AMCount].cancel(pendingIntent[AMCount]);
}
//Updaate te record to set status = 1...(SEND)
temp.setStatus(1);
dbHandler.Update_MessageInfo(temp);
savePreferences("SENT", String.valueOf(temp.getID()));
//take nearest Record from da DB.
MessageInfo minfo = new MessageInfo();
ArrayList<MessageInfo> msgInfo_array_from_db = dbHandler.Get_MessageInfos();
if(msgInfo_array_from_db.size() > 0)
{
minfo = GetLatestMSGInfo(msgInfo_array_from_db);
//Set tat record to alarm manager...
SetAlarm(minfo, minfo.getDelay(), temp.getID());
}
//}
}
}
};
}
private void SaveMSGINFOPreference()
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor prefsEditor = sp.edit();
Gson gson = new Gson();
String json = gson.toJson(AlarmMSGInfo);
prefsEditor.putString("AlarmMSGInfo", json);
prefsEditor.commit();
}

Which request is my onReceive answering to?

I have an ArrayList of contacts that contains a phone number and a status field. I want to update the status field on a successful send result.
I even tried passing the index of the ArrayList item in to the Pending Intent with contacts.indexOf(c.getPhoneNumber()) as the int requestCode. I just cant' figure out how to tell which message is reporting back as successful and update my contact item.
package com.example.SMS;
public class SendSMSActivity extends SMSActivity {
private EditText smsMessageBody;
private Button send_button;
private SmsManager sms;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sendsmsactivity);
setupViews();
}
private void setupViews() {
smsMessageBody = (EditText) findViewById(R.id.smsText_editText1);
broadcast_button = (Button) findViewById(R.id.sendsms_button);
send_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (smsMessageBody.getText().toString().length() > 0 ) {
if (!getSendSMSApplication().getCurrentContacts().isEmpty()) {
sendSMSLoop();
Toast.makeText(getBaseContext(), R.string.messages_sent, Toast.LENGTH_SHORT).show();
getSendSMSApplication().setCurrentContacts(null); // Clear existing contacts after send
finish();
} else {
Toast.makeText(getBaseContext(), R.string.error_no_numbers, Toast.LENGTH_SHORT).show();
} // there are phone numbers to send to?
} else {
Toast.makeText(getBaseContext(), R.string.error_no_message, Toast.LENGTH_SHORT).show();
} // user entered a message?
}
});
}
protected void sendSMSLoop() {
ArrayList<ContactItem> contacts = getSendSMSApplication().getCurrentContacts();
for (ContactItem c:contacts) {
sendSMS(c.getPhoneNumber().toString(), smsMessageBody.getText().toString(), contacts.indexOf(c.getPhoneNumber()));
}
}
public void sendSMS(String phoneNumber, String message, int messageIndex)
{
String SENT = "SMS_SENT";
PendingIntent sentPI = PendingIntent.getBroadcast(this, messageIndex, new Intent(SENT), 0);
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), R.string.sms_sent, Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
}
I am trying to do this myself at the moment. I guess you have got the same problem as me and if you are sending more than 1 message, they are all returning the same sent code for all 3 messages. I think the trick here is to 'thread' each message so that each 'thread' will have a different return code. I can't guarantee this is the solution but it is the path I am next going to go down for solving this issue.
Hope this helps, if you work it out please let me know too.
This is some code taken from my actual code:
public void onReceive(Context context, Intent intent) {
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) {
//The 2 variables you need (from and body)
messages[0].getOriginatingAddress();
messages[0].getMessageBody();
...
Try passing the received/delivered intent to this function (complete the function to add the functionality you need), I will be trying it in a few weeks time so let me know how it goes if you beat me to it.
Just re-looked over your code...
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
My code looks more like:
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
You need to add the extra intent to work with the pdus, as far as I am aware.

Categories

Resources