broadcast receiver in android - android

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

Related

Intent to google map not working

I have a BroadCastReciver in my app which listen for incoming sms.
I want to when sms receive, application open the google map via intent. This is my code but I don't know where is my mistake.
Thank's for any help.
BroadcastReciver.class:
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
startAct(message, context);
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
private void startAct(String message, Context con) {
double Mylatitude = 12;
double Mylongitude = 11;
GPSTracker tracker = new GPSTracker(con);
if (tracker.canGetLocation()) {
Mylatitude = tracker.getLatitude();
Mylongitude = tracker.getLongitude();
}
String location = message;
String ACC_lat = location.substring(0, location.indexOf(","));
String ACC_lang = location.substring(location.indexOf(",") + 1, location.length());
Toast.makeText(con, ACC_lang + " ^ " + ACC_lat, Toast.LENGTH_LONG).show();
Intent mapIntent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=" + Mylatitude + "," + Mylongitude + "&daddr=" + ACC_lat + "," + ACC_lang));
con.startActivity(mapIntent);
}
I also added it in manifest.xml file
You need to split URI into two parts, use one in costructor of Intent and other as package. Here is more details, how to send intents.
Sample:
Uri gmmIntentUri = Uri.parse("geo:37.7749,-122.4194");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}

Start an Application on recieving a Text Message

I have done a small app that locks the screen. But this happens only when i open the app and click my lock button.
I want to do that by sending a TextMessage. That is if I send a txt "Lock" from a pre stored number It should do the the wokr of my buttons OnClick Listener
Can Anyone guide me how to start off with it ?
being new to android I have no idea how to start off with this
Try this Code:
public class SmsReceiver extends BroadcastReceiver
{
String message ;
boolean check_message ;
String senderNUM ;
static String H ;
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
senderNUM = senderNum ;
message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
H = currentMessage.getMessageBody();
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
if(i==0)
H = currentMessage.getMessageBody();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
check_message = message_checked(H) ;
//---display the new SMS message---
if(check_message)
{
abortBroadcast();
Intent intentHome = new Intent(context,MainActivity.class);
intentHome.putExtra("msgContent", message);
intentHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentHome);
}
else
System.exit(0);
}
public boolean message_checked(String the_message)
{
String Code = new String("*%#&");
String four_char = "" ;
for(int i = 0 ; i<4 ; i++)
{
four_char += the_message.charAt(i) ;
}
if(four_char.equals(Code))
{
return true;
}
else
return false ;
}
}

How to receive SMS in Android foreground Activity and in background?

I am receiving SMS.I want ListView to be updated as soon as SMS is received or when Activity is in the foreground.I have done this successfully as I have registered and unregistered receiver in OnResume and OnPause respectively as shown in the Code.:
BroadcastReceiver IncomingSMS = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try {
final Bundle bundle = intent.getExtras();
if (bundle != null) {
//—retrieve the SMS message received—
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
timestamp = smsMessage[n].getTimestampMillis();
number = smsMessage[n].getOriginatingAddress();
body += smsMessage[n].getDisplayMessageBody();
display_name = Util.getContactName(context, number);
DBmanager = new DbManager(context);
cursor = DBmanager.Return_All_Contacts();
String [] contactArr = showcontactsInfo(cursor);
Toast.makeText(context, contactArr[0]+"", 3000).show();
if(contactArr.length==0)
{}
else{
for(int i= 0;i<=contactArr.length;i++)
{
abortBroadcast();
}
blockMessage(context);
}
}
}
}
catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(IncomingSMS);
}
#Override
protected void onResume() {
//registerReceiver(IncomingSMS, null);
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(IncomingSMS, filter);
updateList();
}
I have also registered Receiver in the Manifest file to receive SMS when Activity is in the background.If Activity is in the background and I switch to that Activity then ListView is updated normally but if Activity is in the foreground then ListView has updated data twice. Its most probably that when Activity is in foreground two Receivers are triggered i.e the one in the foreground and second that in the manifest. How can I handle it ???? I want foreground Activity to update to receive SMS only once.
This is how I have registered Receiver in manifest and utilized in java class :
public class IncomingSMS extends BroadcastReceiver {
Context context;
DbManager DBmanager;
private long timestamp;
private String number;
static String body = "";
String msg="";
Cursor cursor;
String display_name;
String flag;
ChatActivity obj_chat;
#Override
public void onReceive(Context context, Intent intent) {
try {
final Bundle bundle = intent.getExtras();
if (bundle != null) {
//—retrieve the SMS message received—
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
timestamp = smsMessage[n].getTimestampMillis();
number = smsMessage[n].getOriginatingAddress();
body += smsMessage[n].getDisplayMessageBody();
display_name = Util.getContactName(context, number);
DBmanager = new DbManager(context);
cursor = DBmanager.Return_All_Contacts();
String [] contactArr = showcontactsInfo(cursor);
Toast.makeText(context, contactArr[0]+"", 3000).show();
if(contactArr.length==0)
{}
else{
for(int i= 0;i<=contactArr.length;i++)
{
abortBroadcast();
}
blockMessage(context);
}
}
}
}
catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
} // end for loop
// bundle is null
private String[] showcontactsInfo(Cursor cursor) {
String[] contact = new String [cursor.getCount()];
int i= 0;
while(cursor.moveToNext()){
contact[i] = cursor.getString(1);
i++;
}
return contact;
}
private void blockMessage(Context context) {
// instantiate DbMNager object to insert sms in database
//formating receiving time:
//SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d HH:mm:ss a");
String formatedTime = formatter.format(timestamp);
flag = "0";
DBmanager= new DbManager(context);
DBmanager.open();
DBmanager.Insert_sms_data(formatedTime ,display_name,body,flag);
DBmanager.close();
obj_chat = new ChatActivity();
obj_chat.updateList();
msg+= "SMS from " + number + " \n";
msg += body + " \n";
msg += formatedTime + " \n";
msg += flag + " \n";
Log.i("SmsReceiver", "senderNum: "+ display_name + "; message: " + body);
Toast.makeText(context,msg, Toast.LENGTH_LONG).show();
//Toast.makeText(context, "New message received in Discrete", Toast.LENGTH_LONG).show();
}
}

How to receive sms from a special phone number?

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?!!!

ContentObserver in Android

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.

Categories

Resources