Hi I am trying to send sms to different mobile numbers with different text body, my code is also sending sms more than 160 characters but it sends to only one number not to all , Now I want to send multiparttext message to all contact list.pls help
private void sendSMS()
{
if (list_phone.size()!=0){
//new AddNewCategory().execute();
for (i = 0; i < len; i++){
SmsManager sm = SmsManager.getDefault();
ArrayList<String> message_parts = sm.divideMessage(list_MESSAGE_BODY.get(i));
// Log.e("Message parts 3", message_parts.get(3));
// Log.e("Message parts 4", message_parts.get(4));
Intent iSent = new Intent();
PendingIntent piSent = PendingIntent.getBroadcast(this, 0, iSent, 0);
Intent iDel = new Intent();
PendingIntent piDel = PendingIntent.getBroadcast(this, 0, iDel, 0);
if (message_parts.size() == 1)
{
String msg = message_parts.get(0);
sm.sendTextMessage(list_phone.get(i), null, msg, piSent, piDel);
Toast.makeText(getApplicationContext(), " Message sent", Toast.LENGTH_SHORT).show();
}
else
{
ArrayList<PendingIntent> sentPis = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> delPis = new ArrayList<PendingIntent>();
int ct = message_parts.size();
for (int i = 0; i < ct; i++)
{
sentPis.add(i, piSent);
delPis.add(i, piDel);
}
//Log.e("Message Parts", message_parts+"");
Log.e("Phone list", list_phone.get(i));
Log.e("Message parts"+i, message_parts.get(i));
sm.sendMultipartTextMessage(list_phone.get(i), null, message_parts, sentPis, delPis);
Toast.makeText(getApplicationContext(), " Message sent", Toast.LENGTH_SHORT).show();
}
}
else
{
// Toast.makeText(getApplicationContext(), "Phone list is empty.. Message not sent", Toast.LENGTH_SHORT).show();
}
}
you need added ";" after each number.
I give one example , Please check it and give your problem solution.
protected void sendMsg(Context context, SmsMessage smsMessage) {
SmsManager smsMgr = SmsManager.getDefault();
ArrayList<string> smsMessageText = smsMgr.divideMessage(smsMessage.getMsgBody());
PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent("SMS_SENT"), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent("SMS_DELIVERED"), 0);
int AddresseesPerMessage = 10;
StringBuilder builder = new StringBuilder();
String delim = "";
for (ContactItem c:smsMessage.getAddresseeList()) {
// For every phone number in our list
builder.append(delim).append(c.getPhoneNumber().toString());
delim=";"; /// if have SAMSUNG devices then delim=", ";
if (((smsMessage.getAddresseeList().indexOf(c)+1) % AddresseesPerMessage) == 0 || smsMessage.getAddresseeList().indexOf(c)+1 == smsMessage.getAddresseeList().size()) {
// using +1 because index 0 mod 9 == 0
for(String text : smsMessageText){
// Send 160 bytes of the total message until all parts are sent
smsMgr.sendTextMessage(builder.toString(), null, text, sentPI, deliveredPI);
}
builder.setLength(0);
delim="";
}
}
}
Try this code
{
if (list_phone.size()!=0){
//new AddNewCategory().execute();
for (i_m = 0; i_m < len; _mi++){
SmsManager sm = SmsManager.getDefault();
ArrayList<String> message_parts = sm.divideMessage(list_MESSAGE_BODY.get(i_m));
// Log.e("Message parts 3", message_parts.get(3));
// Log.e("Message parts 4", message_parts.get(4));
Intent iSent = new Intent();
PendingIntent piSent = PendingIntent.getBroadcast(this, 0, iSent, 0);
Intent iDel = new Intent();
PendingIntent piDel = PendingIntent.getBroadcast(this, 0, iDel, 0);
if (message_parts.size() == 1)
{
String msg = message_parts.get(0);
sm.sendTextMessage(list_phone.get(i), null, msg, piSent, piDel);
Toast.makeText(getApplicationContext(), " Message sent", Toast.LENGTH_SHORT).show();
}
else
{
ArrayList<PendingIntent> sentPis = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> delPis = new ArrayList<PendingIntent>();
int ct = message_parts.size();
for (int i_t = 0; i_t < ct; i_t++)
{
sentPis.add(i_t, piSent);
delPis.add(i_t, piDel);
}
//Log.e("Message Parts", message_parts+"");
Log.e("Phone list", list_phone.get(i));
Log.e("Message parts"+i, message_parts.get(i_m));
sm.sendMultipartTextMessage(list_phone.get(i), null, message_parts, sentPis, delPis);
Toast.makeText(getApplicationContext(), " Message sent", Toast.LENGTH_SHORT).show();
}
}
else
{
// Toast.makeText(getApplicationContext(), "Phone list is empty.. Message not sent", Toast.LENGTH_SHORT).show();
}
}
Related
One Plus device Issue getting the Exception when trying the Sending SMS in grammatically getting the Exception Java.lang.Security Exception .
try {
String message=selectedContactsMap.get(mobileNumber);
/* SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(mobileNumber,null, message,
null, null);*/
SmsManager sm = SmsManager.getDefault();
ArrayList<String> parts =sm.divideMessage(message);
int numParts = parts.size();
ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>();
for (int i = 0; i < numParts; i++) {
sentIntents.add(PendingIntent.getBroadcast(context, 0, new Intent(SMS_SENT), 0));
deliveryIntents.add(PendingIntent.getBroadcast(context, 0, new Intent(SMS_DELIVERED), 0));
}
sm.sendMultipartTextMessage(mobileNumber,null, parts, sentIntents, deliveryIntents);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(Birthday.this,"Send Message Successfully",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}, 1000);
} catch (Exception e) {
// Toast.makeText(Birthday.this,"Something went
// wrong.",Toast.LENGTH_SHORT).show();
Toast.makeText(Birthday.this,"Error:-
"+e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();`enter code here`
progressDialog.dismiss();
}
All device is working the fine Only Problem is One Plus Device
I have tried Android SDK above 5.1 OS. I want to send sms using SIM selection option. I tried this Program. It's taking sim1 only. It does not take second sim.
My Program
public class MainActivity extends AppCompatActivity {
Context mContext = MainActivity.this ;
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendSMS("XXXXXXXX77","Sent by Dual Sim Support Testing");
}
public void sendSMS(final String paramString1,final String paramString2)
{
final PendingIntent localPendingIntent1 = PendingIntent.getBroadcast(mContext, 0, new Intent(this.SENT), 0);
final PendingIntent localPendingIntent2 = PendingIntent.getBroadcast(mContext, 0, new Intent(this.DELIVERED), 0);
Log.v("ppi", "DUal SIm:Build.VERSION.SDK_INT:" + Build.VERSION.SDK_INT);
if (Build.VERSION.SDK_INT >= 22)
{
SubscriptionManager localSubscriptionManager = SubscriptionManager.from(mContext);
if (localSubscriptionManager.getActiveSubscriptionInfoCount() > 1)
{
List localList = localSubscriptionManager.getActiveSubscriptionInfoList();
final String[] arrayOfString = new String[localList.size()];
int i = 0;
Iterator localIterator = localList.iterator();
while (localIterator.hasNext())
{
SubscriptionInfo localSubscriptionInfo = (SubscriptionInfo)localIterator.next();
localSubscriptionInfo.getSubscriptionId();
//log.d("22 api level ", "got dual sim: ");
int j = i + 1;
arrayOfString[i] = (localSubscriptionInfo.getCarrierName().toString() + " " + localSubscriptionInfo.getNumber());
i = j;
}
Log.v("ppi","DUal SIm:arrayOfString:"+arrayOfString.length);
for(i = 0; i < arrayOfString.length; i++ ){
Log.v("ppi","DUal SIm:arrayOfString:"+arrayOfString[i]);
}
final AlertDialog.Builder localBuilder = new AlertDialog.Builder(mContext);
localBuilder.setTitle("Choose SIM ");
localBuilder
.setCancelable(false)
.setPositiveButton("SIM1",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
SmsManager.getDefault().sendTextMessage(paramString1, null, paramString2, localPendingIntent1, localPendingIntent2);
//dialog.cancel();
}
})
.setNegativeButton("SIM2", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
SmsManager.getDefault().sendTextMessage(paramString1, null, paramString2, localPendingIntent1, localPendingIntent2);
// dialog.cancel();
}
});
localBuilder.setCancelable(false);
localBuilder.show();
}
}
SmsManager.getDefault().sendTextMessage(paramString1, null, paramString2, localPendingIntent1, localPendingIntent2);
}
}
Finally, I found exact Sim Selection Option for above android os version 5.1 and above.
public void sendDualSimSMSOption(final String ToaddrmobileNo, final String message) {
// detect os is below 22 or not
if (Build.VERSION.SDK_INT >= 22) {
final PendingIntent PendingIntent1 = PendingIntent.getBroadcast(mContext, 0, new Intent(this.SENT), 0);
final PendingIntent PendingIntent2 = PendingIntent.getBroadcast(mContext, 0, new Intent(this.DELIVERED), 0);
SubscriptionManager localSubscripManager = SubscriptionManager.from(mContext);
ArrayList<Integer> saveSubscripID = new ArrayList<Integer>();
ArrayList<String> saveSimOperatorNames = new ArrayList<String>();
ArrayList<String> saveSimSerialNumbers = new ArrayList<String>();
final int[] subscripInformationArray = new int[2];
if (localSubscripManager.getActiveSubscriptionInfoCount() > 1) {
List localList = localSubscripManager.getActivesubscripInformationList();
final String[] arrayOfStringData = new String[localList.size()];
int i = 0;
Iterator localIterator = localList.iterator();
while (localIterator.hasNext()) {
SubscriptionInfo localSubscriptionInfo = (SubscriptionInfo) localIterator.next();
localSubscriptionInfo.getSubscriptionId();
Log.v("SIM", "22 api level..got dual sim: ");
int j = i + 1;
String SimCarrierName = (localSubscriptionInfo.getCarrierName().toString().trim());
String SimDisplayName = (localSubscriptionInfo.getDisplayName().toString().trim());
String SimSerialNo = (localSubscriptionInfo.getIccId().toString().trim());
if( SimCarrierName != null && SimCarrierName.length() > 0)
{
arrayOfStringData[i] = SimCarrierName ;
Log.v('SIM', "SIM.getCarrierName:", arrayOfStringData[i]);
}
else {
arrayOfStringData[i] = SimDisplayName ;
Log.v('SIM', "SIM.SimDisplayName:", arrayOfStringData[i]);
}
i = j;
}
SubscriptionManager subscriptionManager = SubscriptionManager.from(getApplicationContext());
List<SubscriptionInfo> subscripInformationList = subscriptionManager.getActivesubscripInformationList();
for (SubscriptionInfo subscriptionInfo : subscripInformationList) {
int subscriptionId = subscriptionInfo.getSubscriptionId();
Log.v('SIM', "SIM.subscriptionId:",""+subscriptionId);
}
for (i = 0; i < subscripInformationList.size(); i++) {
Log.v("SIM", "DUal SIm:subscripInformationList:" + subscripInformationList.get(i));
Log.v("SIM", "DUal SIm:getSubscriptionId:" + subscripInformationList.get(i).getSubscriptionId());
subscripInformationArray[i] = subscripInformationList.get(i).getSubscriptionId();
saveSubscripID.add(subscripInformationList.get(i).getSubscriptionId());
saveSimSerialNumbers.add(subscripInformationList.get(i).getIccId());
}
for (i = 0; i < arrayOfStringData.length; i++) {
Log.v("SIM", "DUal SIm:arrayOfStringData:" + arrayOfStringData[i]);
Log.v("SIM", "DUal SIm:subscripInformationArray:"+ subscripInformationArray[i]);
if( arrayOfStringData[i] != null && arrayOfStringData[i].length() > 0)
{
saveSimOperatorNames.add(arrayOfStringData[i]);
}
else{
saveSimOperatorNames.add("Sim "+(i+1));
}
}
// this is the method to show sim selection dialog with above sim serials info.
SimSelection_ShowDialogBox(context, ToAddrMobNo, message,saveSubscripId, saveSimOperaNames,saveSimSerialNumbers);
}
}
else{
// else part. default sim taking to send sms
}
}
That is because you have:
SmsManager.getDefault()
which is SIM1, instead of having:
SmsManager.getSmsManagerForSubscriptionId(int subscriptionId)
when sending SMS in your dialog buttons click events.
I looked into SubscriptionManager class and found a method to get subsCription info for perticular sim slot
This worked for me:
public void sendSMS(final String number,final String text)
{
final PendingIntent localPendingIntent1 = PendingIntent.getBroadcast(mContext, 0, new Intent(this.SENT), 0);
final PendingIntent localPendingIntent2 = PendingIntent.getBroadcast(mContext, 0, new Intent(this.DELIVERED), 0);
if (Build.VERSION.SDK_INT >= 22)
{
SubscriptionManager subscriptionManager=((Activity)mContext).getSystemService(SubscriptionManager.class);
SubscriptionInfo subscriptionInfo=subscriptionManager.getActiveSubscriptionInfoForSimSlotIndex(simIndex);
SmsManager.getSmsManagerForSubscriptionId(subscriptionInfo.getSubscriptionId()).sendTextMessage(number, null, text, localPendingIntent1, localPendingIntent2);
}
SmsManager.getSmsManagerForSubscriptionId(subscriptionInfo.getSubscriptionId()).sendTextMessage(number, null, text, localPendingIntent1, localPendingIntent2);
}
Where simIndex is 0 for sim1 and 1 for sim2
I am trying to implement Broadcast receiver to implement notification pop-up upon SMS received on my Android device. However I have set a condition to detect only specific SMSs from pre-defined senders and then pop-up a notification. Here is what I have coded till now :
public class MyBroadcastReceiver extends BroadcastReceiver
{
private static final String TAG = "MyBroadCastReceiver";
String str = "";
static Context context;
String sender;
#Override
public void onReceive(Context arg0, Intent arg1)
{
// Log.i(TAG,"OnReceive ++ ");
Bundle bndl = arg1.getExtras();
SmsMessage[] msg = null;
if (null != bndl)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bndl.get("pdus");
msg = new SmsMessage[pdus.length];
if(msg[0].getOriginatingAddress().endsWith("AIRMTA") ||
msg[0].getOriginatingAddress().endsWith("ICICIB") ||
msg[0].getOriginatingAddress().endsWith("FCHRGE") ||
msg[0].getOriginatingAddress().endsWith("MYAMEX") ||
msg[0].getOriginatingAddress().endsWith("MOBIKW") ||
msg[0].getOriginatingAddress().endsWith("OLACAB") ||
msg[0].getOriginatingAddress().endsWith("HDFCB") ||
msg[0].getOriginatingAddress().endsWith("AIRMNY")
)
{
for (int i=0; i<msg.length; i++)
{
msg[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
// str += "SMS From " + msg[i].getOriginatingAddress();
sender = msg[i].getOriginatingAddress();
str += " :\r\n";
str += msg[i].getMessageBody().toString();
str += "\n";
context = arg0;
}
//---display incoming SMS as a Android Toast---
// Toast.makeText(arg0, str, Toast.LENGTH_SHORT).show();
//---Create a status bar notification for incoming sms-->
int mNotificationId = 001;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle(sender);
mBuilder.setContentText(str);
mBuilder.setTicker("New Message Alert!");
mBuilder.setSmallIcon(R.drawable.notification);
Intent resultIntent = new Intent(arg0, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(arg0, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotifyMgr = (NotificationManager) arg0.getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
MapsFragment obj = new MapsFragment();
obj.initilizeMap();
}
}
}
}
Unfortunately the application is crashing every time I receive an SMS, be it from any sender. I am not able to understand what is going wrong with the code !
Can anyone help me out on this ?
Here is the log cat error report :
Process: com.techfrk.fetchinboxsms, PID: 21956
java.lang.RuntimeException: Unable to start receiver com.techfrk.fetchinboxsms.MyBroadcastReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.telephony.SmsMessage.getOriginatingAddress()' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2616)
at android.app.ActivityThread.access$1700(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1380)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
You get a NullPointerException exception because your msg array is always empty when calling msg[0].getOriginatingAddress().endsWith().
With msg = new SmsMessage[pdus.length] you create an empty array with the size of pdus.length but this does not add any objects to it.
Instead of
if(msg[0].getOriginatingAddress().endsWith("AIRMTA") ||
msg[0].getOriginatingAddress().endsWith("ICICIB") ||
msg[0].getOriginatingAddress().endsWith("FCHRGE") ||
msg[0].getOriginatingAddress().endsWith("MYAMEX") ||
msg[0].getOriginatingAddress().endsWith("MOBIKW") ||
msg[0].getOriginatingAddress().endsWith("OLACAB") ||
msg[0].getOriginatingAddress().endsWith("HDFCB") ||
msg[0].getOriginatingAddress().endsWith("AIRMNY")
)
{
for (int i=0; i<msg.length; i++)
{
msg[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
// str += "SMS From " + msg[i].getOriginatingAddress();
sender = msg[i].getOriginatingAddress();
str += " :\r\n";
str += msg[i].getMessageBody().toString();
str += "\n";
context = arg0;
}
}
you should do something like
SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(arg1);
if(messages.length < 1) return;
SmsMessage sms = messages[0];
sender = sms.getOriginatingAddress();
str = sms.getMessageBody().toString();
if (sms.getOriginatingAddress().endsWith("AIRMTA")) { // add all your needed statements
// show your notification
}
Please keep in mind that this code is extremely simplified for a better understanding.
Hi I am trying to send sms to different mobile numbers with different text body, my code is also sending sms more than 160 characters but it sends to only one number not to all , Now I want to send multiparttext message to all contact list.pls help
private void sendSMS()
{
if (list_phone.size()!=0){
//new AddNewCategory().execute();
for (i = 0; i < len; i++){
SmsManager sm = SmsManager.getDefault();
ArrayList<String> message_parts = sm.divideMessage(list_MESSAGE_BODY.get(i));
// Log.e("Message parts 3", message_parts.get(3));
// Log.e("Message parts 4", message_parts.get(4));
Intent iSent = new Intent();
PendingIntent piSent = PendingIntent.getBroadcast(this, 0, iSent, 0);
Intent iDel = new Intent();
PendingIntent piDel = PendingIntent.getBroadcast(this, 0, iDel, 0);
if (message_parts.size() == 1)
{
String msg = message_parts.get(0);
sm.sendTextMessage(list_phone.get(i), null, msg, piSent, piDel);
Toast.makeText(getApplicationContext(), " Message sent", Toast.LENGTH_SHORT).show();
}
else
{
ArrayList<PendingIntent> sentPis = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> delPis = new ArrayList<PendingIntent>();
int ct = message_parts.size();
for (int i = 0; i < ct; i++)
{
sentPis.add(i, piSent);
delPis.add(i, piDel);
}
//Log.e("Message Parts", message_parts+"");
Log.e("Phone list", list_phone.get(i));
Log.e("Message parts"+i, message_parts.get(i));
sm.sendMultipartTextMessage(list_phone.get(i), null, message_parts, sentPis, delPis);
Toast.makeText(getApplicationContext(), " Message sent", Toast.LENGTH_SHORT).show();
}
}
else
{
// Toast.makeText(getApplicationContext(), "Phone list is empty.. Message not sent", Toast.LENGTH_SHORT).show();
}
}
Android documentation for SMSManagers sendTextMessage function
public void sendTextMessage (String destinationAddress, String scAddress, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent)
deliveryIntent if not NULL this PendingIntent is broadcast when the message is delivered to the recipient. The raw pdu of the status report is in the extended data ("pdu")
I could not understand if deliveryIntent is fired when SMS is delivered to destinationAddress or scAddress and what is the meaning of "raw pdu of the status report is in the extended data ("pdu")" and how to get that report? .
I appreciate your effort.
It is broadcast when message is delivered to destinationAddress.
The PDU may be extracted from the Intent.getExtras().get("pdu") when registered BroadcastReceiver receives the Intent broadcast you define with PendingIntent.getBroadcast(Context, int requestCode, Intent, int flags). For example:
private void sendSMS(String phoneNumber, String message) {
String DELIVERED = "DELIVERED";
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
Object pdu = arg1.getExtras().get("pdu");
... // Do something with pdu
}
},
new IntentFilter(DELIVERED));
SmsManager smsMngr = SmsManager.getDefault();
smsMngr.sendTextMessage(phoneNumber, null, message, null, deliveredPI);
}
Then you need to parse extracted PDU, SMSLib should be able to do that.
Just to build on a.ch's answer, heres how you can extract the delivery report from an intent:
public static final SmsMessage[] getMessagesFromIntent(Intent intent) {
Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
if (messages == null || messages.length == 0) {
return null;
}
byte[][] pduObjs = new byte[messages.length][];
for (int i = 0, len = messages.length; i < len; i++) {
pduObjs[i] = (byte[]) messages[i];
}
byte[][] pdus = new byte[pduObjs.length][];
SmsMessage[] msgs = new SmsMessage[pdus.length];
for (int i = 0, count = pdus.length; i < count; i++) {
pdus[i] = pduObjs[i];
msgs[i] = SmsMessage.createFromPdu(pdus[i]);
}
return msgs;
}
Full credit to the great project at: http://code.google.com/p/android-smspopup/