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?!!!
Related
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 have successfully monitor incoming SMS and sent it to database for viewing later. I have read about monitor outgoing sms and I don't really understand how it works. Can someone guide me how to code to monitor outgoing sms by using ContentObserver? I will post all my current codes for incoming sms.need guide from where I should start.
smsReceiver.java
package terima.sms.inbox;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import java.net.*;
import java.io.*;
#SuppressWarnings("deprecation")
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage SMS[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
SMS[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
String member_id = "1";
inbox(SMS[0].getOriginatingAddress(), SMS[0].getMessageBody(), member_id);
}
public static Boolean inbox(String telefon, String message, String member_id){
String mesej = "";
for(int i = 0; i < message.length(); i++)
{
if(message.charAt(i) == ' ' || message.charAt(i) == '+')
{
if(message.charAt(i) == ' ')
mesej += "%20";
else
mesej += "%2B";
}
else
{
mesej += message.charAt(i);
}
}
try
{
URL oracle = new URL("http://192.168.1.111/inbox.php?message=" + mesej + "&telefon=" + telefon + "&member=" + member_id);
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String fetch, total = "";
while ((fetch = in.readLine()) != null)
total += fetch;
in.close();
if(total.equals("1"))
return true;
return false;
}
catch(Exception e)
{
return false;
}
}
}
thanks in advance.
To catch outgoing SMS you should use a ContentObserver coupled with a ContentResolver. Here is the code I use in the ContentObserver:
public class SmsObserver extends ContentObserver{
int smsCount;
public SmsObserver(Context context) {
super(new Handler());
smsCount = 0;
}
public void onChange(boolean selfChange){
super.onChange(selfChange);
readSms();
}
private void readSms(){
Uri uriSMS = Uri.parse("content://sms");
Cursor cur = context.getContentResolver().query(uriSMS, null, null, null, "_id");
cur.moveToLast();
int id = Integer.parseInt(cur.getString(cur.getColumnIndex("_id")));
if(cur != null && id != smsCount && id>0){
smsCount = id;
int type = Integer.parseInt(cur.getString(cur.getColumnIndex("type")));
if(type == 1){
// handle the received sms
}
else{
// handle the sent sms
}
}
cur.close();
}
}
After that you should create an instance of SmsOberver and register it on "content://sms". It will be triggered more often than when you send or receive a new message, so this is why I have a smsCount field.
I am creating an application which receives and parses SMS then sends data to another class.
So, for that I create a broadcast receiver but problem is that after receiving and parsing SMS, I cant call my class whom I have to send data.
Anyone have any idea how to implement the SMS receiver, and after receiving the SMS parse it and send data to another class which extends to activity ?
Receiver:
public class SmsReceiver extends BroadcastReceiver
{
int flag1=0,flag2=0,xyz=0;
public String data = "",Lat="", Long="";
SmsMessage[] msgs = null;
Bundle bundle;
Context con;
#Override
public void onReceive(Context context, Intent intent)
{
con = context;
//---get the SMS message passed in---
bundle = intent.getExtras();
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]);
//data += "SMS from " + msgs[i].getOriginatingAddress();
//data += " :";
data += msgs[i].getMessageBody().toString();
//data += "\n";
}*/
data = "Lalazar Ave Hayatabad Pakistan;lat:33.978410 long:71.430398,T:2011-02-25\n19:37,speed:0";
//---display the new SMS message---
Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
Exract_Langitude_And_Latitude();
}
}
public void Exract_Langitude_And_Latitude()
{
Toast.makeText(con, "Getting Latitude & Longitude", Toast.LENGTH_SHORT).show();
for ( int i = 0; i < data.length(); ++i )
{
char c = data.charAt(i);
String s = Character.toString(c);
///finding latitude
if (s.equals(";"))
{
Toast.makeText(con, "Getting Latitude", Toast.LENGTH_SHORT).show();
flag1=1;
String str="";
str = data;
for (int j= i+5;j<str.length();j++)
{
char ch = str.charAt(j);
String l = Character.toString(ch);
Lat+=l;
int k = j+6;
char ch1 = str.charAt(k);
String m = Character.toString(ch1);
if (m.equals(":"))
{
xyz = k;
break;
}
}
Toast.makeText(con, "Latitude = "+ Lat, Toast.LENGTH_SHORT).show();
}
///finding longitude
if (s.equals(":") && i == xyz )
{
Toast.makeText(con, "Getting Longitude", Toast.LENGTH_SHORT).show();
flag2=1;
//System.out.println("found at i = "+i);
String str="";
str = data;
for (int j = i+1;j<str.length();j++)
{
char ch = str.charAt(j);
String l = Character.toString(ch);
Long+=l;
int k = j+1;
char ch1 = str.charAt(k);
String m = Character.toString(ch1);
if (m.equals(","))
break;
}
Toast.makeText(con, "Longitude = " + Long, Toast.LENGTH_SHORT).show();
}
if (flag1==1 && flag2==1)
{
Toast.makeText(con, "Forget You", Toast.LENGTH_SHORT).show();
// Intent serviceIntent = new Intent().setClassName(con, Post.class.getName());
//con.startService(serviceIntent);
//con.startActivity(serviceIntent);
/* Intent in = new Intent(SmsReceiver.this,Post.class);
in.startActivity();*/
break;
}
}///end of main for loop
}
}
Activity:
package com.sms;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class smsMessaging extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
/* SmsReceiver obj = new SmsReceiver();
String a = obj.Lat;
String b = obj.Long;
Toast.makeText(smsMessaging.this, "Latitude = "+ a +" "+ "Longitude = "+ b, Toast.LENGTH_SHORT).show();
*/
/* Intent intent = new Intent (this,Post.class);
startActivity(intent);*/
}
}
Mudasar,
Assuming you intend to launch smsMessaging from the BroadcastReceiver you will want to do something like this:
Intent i = new Intent(con, smsMessaging.class);
con.startActivity(i);
If you need to send any information to the smsMessaging Activity. You can use i.putExtra() before your call to startActivity(i).
You must also make sure you've added the smsMessaging Activity to your AndroidManifest.xml
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();
}
}
}