I am sending perhaps 100-200 SMS messages
The DELIVERED status comes back in dribs and drabs so
I need to get the recipient address to see which message it refers to.
I see whilst debugging the data I can see it there in
message.mWrappedSMSMessage.recipientAddress.address the value is correct but how can I read this??
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
Bundle bundle = arg1.getExtras();
if (bundle != null){
Object pdu = (Object) bundle.get("pdu");
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
String str = message.getServiceCenterAddress();
String str = message.getOriginatingAddress();
//---retrieve the SMS message received---
switch (getResultCode())
{
case Activity.RESULT_OK:
sms_log(str+ " SMS delivered");
break;
case Activity.RESULT_CANCELED:
sms_log(str+ " SMS not delivered");
break;
}
}
}
}, new IntentFilter(DELIVERED));
the above code allows access to
message.getServiceCenterAddress() and message.getOriginatingAddress() but how do I get the message recipient address.
I see whilst debugging the data is there in
message.mWrappedSMSMessage.recipientAddress.address the value is correct but how can I read this??
Steve
Related
I want to open incoming sms from notification directly to my application's intent , Please help I tried following code to read sms from inbox
public class SmsReceiver extends BroadcastReceiver
{
public static String BODY = "Test";
public static String ADDRESS = "5556";
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
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]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
ADDRESS=msgs[i].getOriginatingAddress();
BODY=str;
}
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
When a new SMS is received by your device, the android creates a intent and broadcasts the SMS_RECEIVED_ACTION. What you are going to do is create an Intent Filter for the activity of your application that handles the SMS that the phone receives.
When the phone gets a new SMS message and the user clicks on the notification, she is presented with a dialog of apps that can handle this action*****. Your app should be there, and when she decides that she wants your app to handle the incoming message then you can use the getMessagesFromIntent method in order to extract the message (you use that method inside your app).
PS: You cannot set your app as the default message app, which you probably need to do. The user has to explicitly choose your app to open the message, and if she wants it to be the default messaging app (by ticking the set as default checkbox).
Note: It looks like you have to create a broadcast receiver that receives the SMS_RECEIVED_ACTION which you can use prior to API 19 as a constant at android.provider.Telephony.SMS_RECEIVED and launch your own notifications in which you direct the user directly to the application of yours. Unfortunately it seems that the default messaging app will still issue notifications.
Credit: #Mike M.
I want to send to multiple number of recepients.
I also want to use the built in SMS mechanism without being prompt for a required App (Whatsapp, etc.)
In order to acomplish this, I am using Android's SmsManager.
The for loop iterates through the mobileList array of mobile numbers and send SMS to each one of them, one by one.
The indication for delivered SMS is retrieved by the BroadcastReceiver for the deliveredActionIntent intent.
I am popping a toast with the word "Delivered" and the index number of the message being delivered.
My questions are:
The actual index (idx) is not shown. I get for all toasts the same index number which is the number of mobileList items.
Why is this happening? I expected the index for each mobile by itself.
Is the number of mobileList items limited? Can I have 200 people for instance?
I tested this on a list of 4 mobile numbers but then I got 8-10 toasts. I expected one toast for one mobile delivery.
What is wrong here?
How can I get a notification when all SMSs are delivered? I guess this should be a background action like AsyncTask.
Can someone please show me how to do this?
The code of the SmsManager is shown below.
SmsManager smsManager = SmsManager.getDefault();
for(idx = 0; idx < mobileList.length; idx++) {
String toNumber = mobileList[idx];
String sms = message;
// SMS sent pending intent
Intent sentActionIntent = new Intent(SENT_ACTION);
sentActionIntent.putExtra(EXTRA_IDX, idx);
sentActionIntent.putExtra(EXTRA_TONUMBER, toNumber);
sentActionIntent.putExtra(EXTRA_SMS, sms);
PendingIntent sentPendingIntent = PendingIntent.getBroadcast(this, 0, sentActionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
/* Register for SMS send action */
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String result = "";
switch (getResultCode()) {
case Activity.RESULT_OK:
result = "Transmission successful";
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
result = "Transmission failed";
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
result = "Radio off";
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
result = "No PDU defined";
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
result = "No service";
break;
}
// Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}, new IntentFilter(SENT_ACTION));
// SMS delivered pending intent
Intent deliveredActionIntent = new Intent(DELIVERED_ACTION);
deliveredActionIntent.putExtra(EXTRA_IDX, idx);
deliveredActionIntent.putExtra(EXTRA_TONUMBER, toNumber);
deliveredActionIntent.putExtra(EXTRA_SMS, sms);
PendingIntent deliveredPendingIntent = PendingIntent.getBroadcast(this, 0, deliveredActionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
/* Register for Delivery event */
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "Deliverd " + Integer.toString(idx), Toast.LENGTH_SHORT).show();
}
}, new IntentFilter(DELIVERED_ACTION));
//send
smsManager.sendTextMessage(toNumber, null, sms, sentPendingIntent, deliveredPendingIntent);
}
1) idx changes as you run through the for-loop. Thus, each time you toast, you're showing the current value for idx, which is the number of messages being shown. Since you've packed it in your intent, you can simply show the text "Delivered" + intent.getIntExtra(EXTRA_IDX, -1) in your onReceive method.
2) I'm not sure what you're asking.
3) I'm not sure off-hand, and can't currently debug.
4) You're going to have to keep track of which indices you've received. A HashSet<Integer> should do the trick.
Above your for loop, add this:
final HashSet<Integer> undelivered = new HashSet<Integer>();
In your for loop, add this:
undelivered.add(idx);
To answer your questions for 1, 3, and 4 at once, change your onReceived body to this:
// Get the index from the intent
int idx = intent.getIntExtra(EXTRA_IDX, -1);
if (undelivered.contains(idx)) {
// This index is now delivered. We remove it from the undelivered set, and Toast that it was delivered.
undelivered.remove(idx);
Toast.makeText(getApplicationContext(), "Delivered " + idx, Toast.LENGTH_SHORT).show();
if (undelivered.isEmpty() {
// We've delivered all of the messages ...
Toast.makeText(getApplicationContext(), "All messages were delivered.", Toast.LENGTH_SHORT).show();
}
}
I am creating an application for android OS, which allows user to send encrypted SMS to other users. But my application has only interface for sending an SMS, not for showing it. When application receives an SMS, I wan't to decrypt it and then somehow to show the decrypted SMS through the bult-in SMS Application. Is there a way to accomplish that? For now my receiver just shows the SMS using Toast.
Here is Receiver's code (It is not full but you will get the idea):
public class SMSReceiver extends BroadcastReceiver{
private static final byte HANDSHAKE_ID = (byte) 120;
private static final byte ENCRYPTED_ID = (byte) 125;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle pudsBundle = intent.getExtras();
Object[] pdus = (Object[]) pudsBundle.get("pdus");
SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[0]);
Log.i("Message: ", messages.getMessageBody());
String msgBody = messages.getDisplayMessageBody();
byte[] msgBytes = msgBody.getBytes();
if ( msgBytes[0] == HANDSHAKE_ID ) {
//Obtain secret key from message
//TO-DO
Toast.makeText(context, "Received a secret key from: " + messages.getOriginatingAddress(), Toast.LENGTH_LONG).show();
} else if ( msgBytes[0] == ENCRYPTED_ID ) {
//Obtain encrypted message
//TO-DO
Toast.makeText(context, plainText, Toast.LENGTH_LONG).show();
}
}
Also if it is possible I want to prevent other Apps to see(receive) the message if first byte of the message is one of following constants: HANDSHAKE_ID or ENCRYPTED_ID and visible after decryption? But the main problem that I wan't to solve is how to show plaintext with Android's Built-In SMS Application. Thanks!
My application receives SMS and changes to activity to display an alert dialog box in my app. Toast is working well, but it will not change the activity. onReceive() takes SMS that contain email and depending upon that email id my app searches the associated contact number and sends it back in a reply message.
public void onReceive( Context context, Intent intent )
{
// Get SMS map from Intent
Bundle extras = intent.getExtras();
String messages = "";
if ( extras != null )
{
// Get received SMS array
Object[] smsExtra = (Object[]) extras.get( "pdus" );
// Get ContentResolver object for pushing encrypted SMS to incoming folder
//ContentResolver contentResolver = context.getContentResolver();
for ( int i = 0; i < smsExtra.length; ++i )
{
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
String body = sms.getMessageBody().toString();
String address = sms.getOriginatingAddress();
messages += "SMS from " + address + " :\n";
messages += body + "\n";
// Here you can add any your code to work with incoming SMS
// I added encrypting of all received SMS
}
// Display SMS message
Toast.makeText( context, messages, Toast.LENGTH_SHORT ).show();
Intent i=new Intent(context,AlertActivity.class);
// context.startActivity(i);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
you are adding addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) after starting AlertActivity Activity. use this way :
Intent i=new Intent(context,AlertActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
So i have tried for a long time to find a way to make a app that can send and receive sms in android. That works fine. Here is the code:
For sending:
#SuppressWarnings("deprecation")
public void sendSMS(String phoneNumber, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
int unq = 0;
Intent sent = new Intent(SENT);
sent.putExtra("unq", unq);
Intent delivered = new Intent(DELIVERED);
delivered.putExtra("unq", unq);
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sent, 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,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();
smsstatus = "0";
smserror = "noError";
//sendSmsStatus();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
setSmsstatus("1");
setSmserror("Generic failure");
sendSmsStatus("Generic failure");
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
setSmsstatus("2");
setSmserror("No service");
sendSmsStatus("No service");
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
setSmsstatus("3");
setSmserror("Null PDU");
sendSmsStatus("Null PDU");
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
setSmsstatus("4");
setSmserror("Radio off");
sendSmsStatus("Radio off");
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);
}
For receiving:
public class SmsReceiver extends BroadcastReceiver {
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
Object sms = "";
ArrayList<String> s = new ArrayList<String>();
Manager m = Factory.getInstance().getManager();
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]);
str += " SMS fra " + msgs[i].getOriginatingAddress() + "\n";
str += " Besked: ";
str += msgs[i].getMessageBody().toString();
str += "\n";
sms = "SMS = "+msgs[i].getOriginatingAddress()+","+msgs[i].getMessageBody().toString();
s.add(msgs[i].getOriginatingAddress());
s.add(msgs[i].getMessageBody().toString());
}
// ---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
Manager.toastIt(context, str);
// Send the sms to the server
//Connection.send(new Transmit("SmsReceived",s));
}
}
}
This works great!.
And here comes the question. Is it posible to refactore my code to achive the following:
Have a unique indentifier/flag on my send sms so i can make sure which sms i receive a status on. As you can see i have already tried to put extra on my 2 intents, and maybe that is the right way, but not only do i not now how to check/receive/extract the flag for the status, but also the flag really "unique" right now.
Its nice that I can revieve a sms, but when its more than 160 chars it only shows me the first 160 chars. I had looked at how GTalkSMS does it, but was hoping my code could just be refactored a bit :)
The last problem is, a mix of the 2 above. I cant send a sms thats more than 160 char. I know i have to use sendMultipartTextMessage, but i dont know how. My thought is that i could devide the "String message" by 100 to a Array but i dont know.
So feel free to refactore the code. I'm looking forward to see your replies! :D
Please ask if you need anything explained better or more code! :)
Not Android specific, but read about the "Concatenated SMS" standard. Basically it's multiple messages that each specify they go with the previous one, but it goes over the air as entirely independent SMS.
Most phones hide this fact from the user, of course, but if you're directly receiving SMS it's likely you'll need to deal with it yourself - sending and receiving. Assuming Android uses this standard, which seems like a safe bet.
Since it's so common, I'm sure you can find a library that somebody's already written.
http://en.wikipedia.org/wiki/Concatenated_SMS
Everything you asked for is in the GTalkSMS code (seems you have missed it). :-) But I will point you to the right snippets.
In order to use sendMultipartTextMessage() and distinguish the different sent/delivered notification intents you need first to split the message string via SmsManager.divideMessage(message) and create two, one for sent notifications and one for the delivered notifications, PendingIntents ArrayLists, where, and this is the important part, every PendingIntent has to be created with a a unique request int:
PendingIntent.getBroadcast(context, UNIQUE_ID, deliveredIntent, PendingIntent.FLAG_ONE_SHOT)
This assures that andoird will broadcast an unique intent for every sent delivered notification. You can also add some extras to the intent, which could later tell you for which SMS the notification was.
Code snippets can be found here: sendSMSByPhoneNumber()
Make sure that your SmsReceiver is aware that an incoming intent can contain more that one SMS for multiple senders, but a maximum of nbfOfpdus different senders. The GTalkSMS receiver will sure help you understand how to get this going. :)