This question already has answers here:
Get number of unread sms
(2 answers)
Closed 9 years ago.
Can you please tell me how can i query the number of unread SMS in android programmically?
How can I implement the SMS unread count like this link:
The API Docs show a constant that you should be able to look for to figure out which messages are received and unread.
This article shows somebody interacting with the SmsMessage class, which might give you some pointers.
Here is a code snippet that lets you read messages as they arrive.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Bundle myBundle = intent.getExtras();
SmsMessage [] messages = null;
String strMessage = "";
if (myBundle != null)
{
Object [] pdus = (Object[]) myBundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++)
{
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
strMessage += "SMS From: " + messages[i].getOriginatingAddress();
strMessage += " : ";
strMessage += messages[i].getMessageBody();
strMessage += "\n";
}
Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
}
}
}
Related
I am developing an android app which gets the SMS using broadcast receiver when its comes. Here is the code:
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs;
if (bundle != null) {
//---retrieve the SMS message received---
try {
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]);
String address = msgs[i].getOriginatingAddress();
String body = msgs[i].getMessageBody();
}
} catch(Exception e) {
Log.d("Exception caught",e.getMessage());
}
}
}
Problem is that few messages I receive comes in two or three parts. I don't know how to join these parts of messages. How can I detect that the first part of message needed to be combined with the next part message.
First Part: Your airtel mobile ********** online recharge txn ID ************ o
Second Part: f Rs *** has been initiated. Please keep the txn id for future refe
Third Part: rence.
You need to add message body(parts).
change this
String body = msgs[i].getMessageBody();
to
String body += msgs[i].getMessageBody();
The problem is inside your loop try this out, you should be fine
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
// Retrieve the SMS Messages received
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
// For every SMS message received
for (int i=0; i < msgs.length; i++) {
// Convert Object array
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// Sender's phone number
str += "SMS from " + msgs[i].getOriginatingAddress() + " : ";
// Fetch the text message
str += msgs[i].getMessageBody().toString();
str += "\n";
}
// Display the entire SMS Message
Log.d(TAG, str);
}
I have built an SMS messaging app, which both sends and receives text messages. In MainActivity, I have a two-dimensional array of people's names and phone numbers, and in my sending class, I have a for loop which sends the same message to all of the recipients by going through each of the numbers:
for (i=0; i<names.length; i++) {
phoneNo = names[i][2] + names[i][3];
sendMessage(phoneNo, message);
}
private void sendMessage(String phoneNo, String message) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS failed. Please try again!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
When I send a message through the app, I can see very clearly from my own Samsung messaging app that the same message gets sent to each of the numbers in the list, which is perfect.
This is my shortened receiver class:
public class Receiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
SmsMessage[] smgs = null;
String infoSender = "";
String infoSMS = "";
if (extras != null) {
// Retrieve the sms message received
Object[] pdus = (Object[]) extras.get("pdus");
smgs = new SmsMessage[pdus.length];
for (int i = 0; i < smgs.length; i++) {
smgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
infoSender += smgs[i].getOriginatingAddress();
infoSMS += smgs[i].getMessageBody().toString();
}
}
I have found that despite the message being sent out once to each recipient, some recipients (with this app) receive it more than once consecutively. Hence, I suspected that there was something wrong with my receiver code, which is seemingly treating one received message as several consecutive received messages. This is not a consistent problem, as different people receive the consecutive messages at different times.
However, what I've also found is that if I hardcode phoneNo in the sending class to just one phone number, or if I have only one phone number in the array in MainActivity, then this problem doesn't occur. The message still gets sent out once to that one phone number only, but the receiver will always receive it just once as intended.
I am so confused by this now, so can somebody please give some suggestions as to what I could try? Literally in the last minute, I thought that it could be a problem with createFromPdu being deprecated? If so, please advise how to change my receiver code, as I couldn't find anything which resembles my current code too much.
Many thanks in advance:-)
Do like this you are making mistake check below code.
if (bundle != null) {
// get sms objects
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus.length == 0) {
return;
}
// large message might be broken into many
SmsMessage[] messages = new SmsMessage[pdus.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
sb.append(messages[i].getMessageBody());
}
senderNum = messages[0].getOriginatingAddress();
message = sb.toString();
}
Update: To check default app
public class Receiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
final String myPackageName = context.getPackageName();
if (Telephony.Sms.getDefaultSmsPackage(context).equals(
myPackageName)) {
// you are default
Bundle extras = intent.getExtras();
SmsMessage[] smgs = null;
String infoSender = "";
String infoSMS = "";
if (extras != null) {
// Retrieve the sms message received
Object[] pdus = (Object[]) extras.get("pdus");
smgs = new SmsMessage[pdus.length];
for (int i = 0; i < smgs.length; i++) {
smgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
infoSender += smgs[i].getOriginatingAddress();
infoSMS += smgs[i].getMessageBody().toString();
}
}
} else {
// you are not ignore
}
} else {
// for below KitKat do like normal
Bundle extras = intent.getExtras();
SmsMessage[] smgs = null;
String infoSender = "";
String infoSMS = "";
if (extras != null) {
// Retrieve the sms message received
Object[] pdus = (Object[]) extras.get("pdus");
smgs = new SmsMessage[pdus.length];
for (int i = 0; i < smgs.length; i++) {
smgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
infoSender += smgs[i].getOriginatingAddress();
infoSMS += smgs[i].getMessageBody().toString();
}
}
}
}
}
i hope this modication of your code base will help solve your problem
public class Receiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
SmsMessage[] smgs = null;
String infoSender = "";
String infoSMS = "";
if (extras != null) {
try{
// Retrieve the sms message received
Object[] pdus = (Object[]) extras.get("pdus");
if(pdus.length==0){return;}
smgs = new SmsMessage[pdus.length];
for (int i = 0; i < smgs.length; i++) {
smgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
infoSMS += smgs[i].getMessageBody();
}
infoSender = smgs[0].getOriginatingAddress();
}catch(Exception e){
e.printStackTrace ();
}
}
}
}
I wrote send and receive program in android. when sms received from special number, sms go to my program and body of sms , show in text. but for received sms from other phone number, sms go to inbox of phone and program isn't opened.
Now in my program , for every received sms, program is opened and body of sms is shown in textview.
if condition didn't work!!!
i put my code, please check my code.
SmsReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
public String str = "";
static final String ACTION =
"android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION)) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null) {
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]);
String msg_from = msgs[i].getOriginatingAddress();
if(msg_from.equals("+9891--------"))
{
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
}
Intent act = new Intent(context, MainActivity.class);
act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.putExtra("message", str);
context.startActivity(act);
}
abortBroadcast();
}
}
}
You should do the context.startActivity(act); in the if condition. I think you mistakenly put it out of the if condition.
Also the abortBroadcast() should be in if condition coz that makes sense, if the msg is not from the special number it should go to the inbox....RIGHT :)
Edited:
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION)) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null) {
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]);
String msg_from = msgs[i].getOriginatingAddress();
if (msg_from.equals("+9891--------")) {
String str = "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
Intent act = new Intent(context, MainActivity.class);
act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.putExtra("message", str);
context.startActivity(act);
abortBroadcast();
}
}
}
}
}
I wrote a send and receive sms in android successfully.
I want my program to be able to receive sms from a special number("+9856874236"). But, if the SMS is from any other number, it should go to the phone's message inbox and not to my application.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
public class SmsReceiver extends BroadcastReceiver {
public String str = "";
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage[] msgs = null;
if (bundle != null)
{
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
String msg_from="";
for (int n = 0; n < messages.length; n++)
{
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
msg_from += msgs[n].getOriginatingAddress();
}
String receivedMessage = smsMessage[0].getMessageBody().toString().toUpperCase();
if(msg_from .equals("+989124236870"))
{
for (int n = 0; n < messages.length; n++)
{
smsMessage[n] = SmsMessage.createFromPdu((byte[]) pdus[n]);
str += "SMS from " + msgs[n].getOriginatingAddress();
str += " :";
//str += "sms az shomare makhsus";
str += msgs[n].getMessageBody().toString();
str += "\n";
abortBroadcast();
}
Intent act = new Intent(context, MainActivity.class);
act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.putExtra("message", str);
context.startActivity(act);
}
}
}
}
Why are you appending the msg_from parameter in for loop?
msg_from += msgs[n].getOriginatingAddress();
Shouldn't it just be :
msg_from[n] = msgs[n].getOriginatingAddress();
Basically have an array for msg_from[n] and put each originating address into it for every message.
Then check this for every message by looping through the msg_from array?
You can move the check for origin inside the for loop as follows:
for (int n = 0; n < messages.length; n++) {
if(msg_from[n].equals("+9856874236")){
smsMessage[n] = SmsMessage.createFromPdu((byte[]) pdus[n]);
str += "SMS from " + msg_from[n];
str += " :";
//str += "sms az shomare makhsus";
str += msgs[n].getMessageBody().toString();
str += "\n";
abortBroadcast();
}else{
//Do something else
}
}
use this sample and customize it:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SrvSmsListener extends Service {
private BroadcastReceiver IncomingSMSReceiver = new BroadcastReceiver() {
private static final String SMS_RECEIVED =
"android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context _context, Intent _intent) {
if (_intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = _intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++)
messages[i] = SmsMessage
.createFromPdu((byte[]) pdus[i]);
for (SmsMessage message : messages) {
String strPhoneNo = message.getOriginatingAddress();
String msg = message.getMessageBody();
if (msg.startsWith("my text"))
{
// this stops notifications to others
this.abortBroadcast();
}
}
}
}
}
};
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
IntentFilter filter = new IntentFilter(SMS_RECEIVED);
BroadcastReceiver receiver = IncomingSMSReceiver;
registerReceiver(receiver, filter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
if (IncomingSMSReceiver != null)
{
unregisterReceiver(IncomingSMSReceiver);
}
}
}
i had this problem too.now i use this code and it works properly:
`enter code here`
if ( extras != null ) {
// get array data from SMS
Object[] smsExtra = (Object[]) extras.get( "pdus" ); // "pdus" is the key
for ( int i = 0; i < smsExtra.length; ++i ) {
// get sms message
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
// get content and number
String body = sms.getMessageBody();
String address = sms.getOriginatingAddress();
// create display message
if( address.contains("5558")){
messages += "SMS from " + address + " :\n";
messages += body + "\n";
// notify new arriving message
Toast.makeText( context, messages, Toast.LENGTH_LONG ).show();
this.abortBroadcast();
}
}
and also don't forget use this code to your manifest:
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
.....
<receiver android:name=".SmsReceiver" android:exported="true" >
<intent-filter android:priority="1">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
this program receive only from port="5558"(in emulators) and store other msg in your inbox.
is it(09124236870) your own phone number?!!!
Anyone know how to send non-printing characters via SMS in Android?
I tried the following code but it does not work...The recipient will not receive the correct string.
String msg = "Testing special char" +(char) 3;
sendSMS(num,msg);//defined method
Or is there any other way to insert some kind of tags into a SMS, so that the recipient can perform some actions accordingly?
By default you send sms text messages in ascii format. Try to send binary SMS.
As there is an Android tag on the question, here is what I found while researching the topic (code from codetheory.in).
Send:
// Get the default instance of SmsManager
SmsManager smsManager = SmsManager.getDefault();
String phoneNumber = "9999999999";
byte[] smsBody = "Let me know if you get this SMS".getBytes();
short port = 6734;
// Send a text based SMS
smsManager.sendDataMessage(phoneNumber, null, port, smsBody, null, null);
Receive:
public class SmsReceiver extends BroadcastReceiver {
private String TAG = SmsReceiver.class.getSimpleName();
public SmsReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
// Get the data (SMS data) bound to intent
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null){
// Retrieve the Binary SMS data
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
// For every SMS message received (although multipart is not supported with binary)
for (int i=0; i<msgs.length; i++) {
byte[] data = null;
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
str += "Binary SMS from " + msgs[i].getOriginatingAddress() + " :";
str += "\nBINARY MESSAGE: ";
// Return the User Data section minus the
// User Data Header (UDH) (if there is any UDH at all)
data = msgs[i].getUserData();
// Generally you can do away with this for loop
// You'll just need the next for loop
for (int index=0; index < data.length; index++) {
str += Byte.toString(data[index]);
}
str += "\nTEXT MESSAGE (FROM BINARY): ";
for (int index=0; index < data.length; index++) {
str += Character.toString((char) data[index]);
}
str += "\n";
}
// Dump the entire message
// Toast.makeText(context, str, Toast.LENGTH_LONG).show();
Log.d(TAG, str);
}
}
}