ContentObserver in Android - 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.

Related

Let listview know that contentprovider is updated

I'm having a listview that shows my model items that I filled with the contentprovider (inbox). Now when I'm in my broadcastreceiver and I get an update I would like to let the listview know that he must update his List off models and show it.
I've seen that you can do this with notifyChanged but I can't find a good example.
Can someone help me out on this?
EDIT:
SMSBroadcastReceiver:
Object[] pdus = (Object[]) bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
if (messages.length < 0) {
return;
}
SmsMessage sms = messages[0];
String body = "";
String sender = sms.getOriginatingAddress().toString();
Long time_rcv = sms.getTimestampMillis();
try {
if (messages.length == 1 || sms.isReplace()) {
body = sms.getDisplayMessageBody();
} else {
StringBuilder bodyText = new StringBuilder();
for (int i = 0; i < messages.length; i++) {
bodyText.append(messages[i].getMessageBody());
}
body = bodyText.toString();
}
} catch (Exception e) {
}
ContentValues smsValues = new ContentValues();
smsValues.put("address", sender);
smsValues.put("body", body);
smsValues.put("date_sent", time_rcv);
context.getContentResolver().insert(BlacklistConstants.smsInboxUri, smsValues);
From here I want to the let my fragment know that there is a new sms added.
Thats the .insert gives me back.
This is the fragment this function fills my smsList that contains my models.
private void fetchBox(Conversations smsConversation, String thread_id, Uri threadUri) {
//Cursor smsInThreads = getActivity().getContentResolver().query(threadUri, null, "thread_id = ?", new String[]{thread_id}, null);
CursorLoader cursorLoader = new CursorLoader(getActivity(), threadUri,
null, // the columns to retrieve (all)
"thread_id = ?", // the selection criteria (none)
new String[]{thread_id}, // the selection args (none)
null // the sort order (default)
);
Cursor smsInThreads = cursorLoader.loadInBackground();
if (smsInThreads.moveToFirst()) {
smsConversation.setNumber(smsInThreads.getString(smsInThreads.getColumnIndexOrThrow("address")));
for (int x = 0; x < smsInThreads.getCount(); x++) {
smsObjects msg = new smsObjects();
msg.setBody(smsInThreads.getString(smsInThreads.getColumnIndexOrThrow("body")));
msg.setNumber(smsInThreads.getString(smsInThreads.getColumnIndexOrThrow("address")));
msg.setId(smsInThreads.getString(smsInThreads.getColumnIndexOrThrow("_id")));
msg.setTimeStampReceived(smsInThreads.getString(smsInThreads.getColumnIndexOrThrow("date_sent")));
smsConversation.addTextMessage(msg);
smsInThreads.moveToNext();
}
}
//smsList.add(smsConversation);
smsInThreads.close();
}
And finally this is my custom adapter:
public class ListAdapter extends ArrayAdapter<Conversations> {
private String TAG = ListAdapter.class.getName();
private final Context context;
private final List<Conversations> smsList;
public ListAdapter(Context context, List<Conversations> smsList) {
super(context, R.layout.sms_inbox, smsList);
this.context = context;
this.smsList = smsList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.sms_inbox, parent, false);
holder = new ViewHolder();
holder.senderNumber = (TextView) convertView.findViewById(R.id.smsNumberText);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.senderNumber.setText(smsList.get(position).getNumber());
return convertView;
}
private static class ViewHolder
{
public TextView senderNumber;
}
#Override
public int getCount() {
return smsList != null ? smsList.size() : 0;
}
}
Now I don't know how to easy let the fragment know that there is a new insert and that the listview needs to update his model and show it.
I did this in the past like this:
Uri newSms = context.getContentResolver().insert(BlacklistConstants.smsInboxUri, smsValues);
Log.d(TAG,newSms.toString());
Intent smsReceiveIntent = new Intent(BlacklistConstants.smsFilter);
smsReceiveIntent.putExtra("newSMS",newSms);
context.sendBroadcast(smsReceiveIntent);
And then on my fragment I listened to that intent and added it to the smsList and then did notifyDataChanged. But I think there is a better way not?
I solved this by starting an intent in the onreceive and then in the main listen to that intent and update the list.
In the onreceive:
Intent smsReceiveIntent = new Intent(BlacklistConstants.smsFilter);
smsReceiveIntent.putExtra("newSMS",newSms.toString());
context.sendBroadcast(smsReceiveIntent);
and in the activity where you can update the listview:
// Sets up the smsreceiver broadcastreceiver
private void setupSmsReceiver() {
smsReceiver = new BroadcastReceiver() {
public void onReceive(Context context, final Intent intent) {
Log.d(TAG, "onReceive smsReceiver");
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "runOnUiThread");
String uri = intent.getStringExtra("newSMS");
addToList(uri);
smsAdapter.notifyDataSetChanged();
}
});
}
}
};
getActivity().registerReceiver(smsReceiver, new IntentFilter(BlacklistConstants.smsFilter));
}
What I do is to use a ContentObserver in the class that hosts the list, like this
(NOTE: this code goes inside a fragment)
private static final int REFRESH_PAGES = 1;
private static final int CHANGE_CURRENT_SET = 2;
private myCustomObserver mContentObserver;
//utility function to set de observer
// register a un content observer to know that the content has changed
private void registerContentObserver(int myId) {
Log.v(DEBUG_TAG, "registerContentObserver, myId=" + myId);
if (mContentObserver != null) {
getActivity().getContentResolver().unregisterContentObserver(
mContentObserver);
}
mContentObserver = new MyCustomObserver (mHandler);
getActivity().getContentResolver().registerContentObserver(
yourUri, true,
mContentObserver);
}
...... this is the content observer
class MyCustomObserver extends ContentObserver {
public MyCustomObserver(Handler handler) {
super(handler);
Log.v(DEBUG_TAG, "MyCustomObserver");
}
#Override
public void onChange(boolean selfChange) {
Log.i(DEBUG_TAG, "onChange, selfChange==" + selfChange);
super.onChange(selfChange);
Message msg = mHandler.obtainMessage(REFRESH_PAGES);
mHandler.sendMessage(msg);
};
#SuppressLint("NewApi")
#Override
public void onChange(boolean selfChange, Uri uri) {
Log.v(DEBUG_TAG, "onChange, selfChange==" + selfChange + ", uri=="
+ uri.toString());
final Message msg = mHandler.obtainMessage(REFRESH_PAGES);
mHandler.sendMessage(msg);
super.onChange(selfChange, uri);
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
}
I also need a handler :
public Handler mHandler = new Handler() {
#Override
public void handleMessage(android.os.Message msg) {
Log.v(DEBUG_TAG, "mHandler");
if (isAdded()) {//IMPORTANT if you are in a fragment
switch (msg.what) {
case REFRESH_PAGES:
getLoaderManager().getLoader(0).forceLoad();
break;
case CHANGE_CURRENT_SET:
firstTime = true;
doYourStaff();
break;
}
}
};
};
in the Content Provider you need something like :
getContext().getContentResolver()
.notifyChange(yourUri, null);
e voilà ...

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

Best Method to store sms data in DataBase on OnReceive Method of BroadcastReceiver and then Activities get updated

I have near about six Activities and a service class with BroadcastReceiver that run in background for receiving SMS. I receive SMS on OnReceive Method of BroadcastReceiver now I would like to store incomming sms data in database for that I have made a SMSSync Class for smsProcess which pass data to dbase now I call this smsProcess on OnReceive method this work fine but I think when more sms received at same time the I got found problem I think it was due to database. Sir please tell me what is best method to store sms data after receiving it On receive and then show in activities. Sory for my bad English or if not understand. Thanks in advance sir pl revert back answer I will wait for..I tag code for On Receive method
thanks
Om Parkash Kaushik
public SMSReceiver(Context ctx){
this.context = ctx;
sync = new SMSSync(context);
dba = new DataBaseAdapter(ctx);
}
#Override
public void onReceive(Context context,final Intent intents){
if (intents.getAction().equals(ConstantClass.SMS_RECEIVED)) {
try{
Bundle bundle = intents.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]);
String msg=null;
String temp = null;
for (SmsMessage message : messages) {
msg = message.getMessageBody();
temp = message.getOriginatingAddress();
}
if(msg.length()>5 && msg.startsWith("<") && msg.contains(">")){
String len = msg.substring(1, 3);
int tl = temp.length();
int l = tl - no;
address = temp.substring(l,tl);
int value =Integer.valueOf(len, 16).intValue();
int index = msg.indexOf(">");
if(value == index+1){
dba.Open();
int id = dba.getCordiId(address);
Cursor cur = dba.getCoord(id);
if(cur!=null)
cur.moveToFirst();
final String Phnumber = cur.getString(cur.getColumnIndex(DataBaseAdapter.Key_MbNo));
if(Phnumber.equals(address)){
int count = dba.getDeviceCount(ConstantClass.dbName[1]);
if(count<=0){
dba.InsertCurrentCoord(id,id);
}else{
Strsql = new String("UPDATE " + ConstantClass.dbName[1] + " SET " + DataBaseAdapter.Key_ReceiverCoord + " = " +
Integer.toString(id) + " WHERE " + DataBaseAdapter.Key_ID + " = ?");
dba.UpdateQuery(Strsql, Integer.toString(1));
}
dba.Close();
sync.smsProcess(msg);
abortBroadcast();
/************Now deleting the SMS from the Inbox*********************/
removeMessage(SMSReceiver.this.context, Phnumber);
if(msg.substring(3, 4).equals("2"))
ConstantClass.isAuditrequestSend = false;
/*******after receiving the sms opening the Main Screen.*****************/
if(ConstantClass.Clear_Main_Screen==true){
Intent intent = new Intent(context,ZigbeeActivity.class);
context.startActivity(intent);
}
}else{
Toast.makeText(SMSReceiver.this.context, address, Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(SMSReceiver.this.context, "message Corrupt" + address, Toast.LENGTH_LONG).show();
}
}
}
}catch(Exception e){
dlg = new ExceptionDialog(SMSReceiver.this.context,"On Sms Receiver" + address ,e.getMessage());
dlg.show();
}
}
}
I have done the same application related to yours. But instead of saving all received sms i want to save only bank transaction related sms. I hope the following code will helps you..
ReceiveSms.java
if(smsg.contains("credit") /***********/ || msg.contains("amount"))
{
Toast.makeText(context, "message related to transcation", Toast.LENGTH_SHORT).show();
dbh.smsservice(smsg);
}
DbHandler.java
public void smsservice(String sms)
{
// TODO Auto-generated method stub
String smessg="INSERT INTO SMSDETAILS(SMSMESS) VALUES('"+sms+"') ";
sdb.execSQL(smessg);
System.out.println("values of sms inserted"+smessg);
}

broadcast receiver in 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

Categories

Resources