I realized,there're some questions here, but i think my code is really different from them (i'm a beginner) and i can't understand their answers!
So i want to refresh my ListView everytime i receive a SMS, i tried to use cursor.requery(); and some methods which i found on google but it's still not working.
This is my code :
public class SMSActivity extends Activity implements OnItemClickListener {
ArrayList<String> smsList = new ArrayList<String>();
// String ADDRESS[];
// int total = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://sms/inbox"), null, null,
null, null);
int indexBody = cursor.getColumnIndex("body");
int indexAddr = cursor.getColumnIndex("address");
if (indexBody < 0 || !cursor.moveToFirst())
return;
smsList.clear();
do {
String str = "Sender : " + cursor.getString(indexAddr) + "\n"
+ cursor.getString(indexBody);
smsList.add(str);
// ADDRESS[total] = cursor.getString(indexAddr);
// total++;
} while (cursor.moveToNext());
ListView lvSms = (ListView) findViewById(R.id.SMSList);
lvSms.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, smsList));
// cursor.requery();
lvSms.setOnItemClickListener(this);
}
EDITED :
And this is the Class where i extends it with BroadcastReceiver :
public class SMSReceiver extends BroadcastReceiver {
private static final int NOTIF_ID = 0;
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Bundle bundle = arg1.getExtras();
SmsMessage[] msgs = null;
String str = "";
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]);
str += "You Get New SMS from " + msgs[i].getOriginatingAddress();
str += " :"; str += msgs[i].getMessageBody().toString();
str += "\n";
Toast.makeText(arg0, str, Toast.LENGTH_SHORT).show();
NotificationManager nm = (NotificationManager) arg0.getSystemService(Context.NOTIFICATION_SERVICE);
String tickerText = str;
Notification notif = new Notification(R.drawable.ic_launcher, tickerText, System.currentTimeMillis());
notif.flags = Notification.FLAG_AUTO_CANCEL;
String contentTitle = msgs[i].getOriginatingAddress();
String contentText = msgs[i].getMessageBody().toString();
Intent intent = new Intent(arg0, SMSReply.class);
PendingIntent pi = PendingIntent.getActivity(arg0, 0, intent, 0);
notif.setLatestEventInfo(arg0, contentTitle, contentText, pi);
notif.defaults = Notification.DEFAULT_ALL;
nm.notify(NOTIF_ID, notif);
String tempSMS = msgs[i].getOriginatingAddress();
Intent pass = new Intent();
Bundle bundlePass = new Bundle();
bundlePass.putString("key", tempSMS);
pass.putExtras(bundlePass);
}
}
}
I don't understand how to link those two Class so everytime the BroadcastReceiver works(new SMS come) my ListView will be updated(just like the SMS app in your phone)
Thanks All.
Define adapter as global public variable,
ArrayAdapter<String> adapter;
inside onCreate() assign it,
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, smsList));
in your BroadcastReceiver access the smsList and add to it the new sms,
then access your adapter this way,
adapter.notifyDataSetChanged();
this function will notify the adapter that smsList values have been changed and will update the list.
You can create a BroadcastReceiver class with an abstract method, like this:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
...
do your stuff here
...
myAbsMethod(newSms);
}
public abstract void myAbsMethod(String sms);
}
Then, in your activity you do something like this:
public class MyActivity extends Activity {
private final MyReceiver myReceiver;
private ArrayList<String> smsList = new ArrayList<String>();
...
public MyActivity() {
myReceiver = new MyReceiver() {
#Override
public void myAbsMethod(String sms) {
smsList.add(sms);
}
};
}
#Override
public void onCreate(Bundle savedInstanceState) {
...
IntentFilter filterState = new IntentFilter(YOUR_SMS_ACTION);
registerReceiver(myReceiver, filterState)
}
...
#Override
public void onDestroy() {
...
unregisterReceiver(myReceiver);
}
}
So, basically, you're registering this receiver inside your activity class, then whenever you receive this broadcast, your activity will listen, and you can do whatever you want in this overridden abstract method.
Related
I have a listview and it automatically filter all sim messages from mobile then I highlighted the items on the listview through clicking and it works, but the problem is when there's new message all of the highlighted item gone.Is theres any solution to remain the highlighted item when new message arrived? I use the following code. Thanks I appreciate your response.
layout : activitymain.xml
<ListView
android:id="#+id/textlistview"
android:layout_width="match_parent"
android:choiceMode="multipleChoice"
android:listSelector="#drawable/default_color"
android:layout_height="match_parent" />
Broadcast Receiver : SMSReceiver.java
public class SMSReceiver extends BroadcastReceiver {
public static final String SMS_BUNDLE = "pdus";
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(intent.getAction().equalsIgnoreCase("android.provider.Telephony.SMS_RECEIVED")) {
if (bundle != null) {
Object[] sms = (Object[]) bundle.get(SMS_BUNDLE);
String smsMsg = "";
SmsMessage smsMessage;
for (int i = 0; i < sms.length; i++) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
String format = bundle.getString("format");
smsMessage = SmsMessage.createFromPdu((byte[]) sms[i], format);
}
else {
smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
}
String msgBody = smsMessage.getMessageBody().toString();
smsMsg +=msgBody;
}
text_message inst = text_message.Instance();
inst.receive_data(smsMsg);
}
}
}}
MainActivity : text_message.java
public void receive_data (final String smsMsg) {
arrayAdapter = new ArrayAdapter(this,R.layout.list_item, list_items);
text_listview.setAdapter(arrayAdapter);
arrayAdapter.add(smsMsg);
arrayAdapter.notifyDataSetChanged();
}
Filter messages : text_message.java
public void refreshInbox(){
arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list_items);
ContentResolver cResolver = getContentResolver();
Cursor smsInboxCursor = cResolver.query(Uri.parse("content://sms/inbox"),null,null,null,null);
int indexBody = smsInboxCursor.getColumnIndex("body");
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
do{
str = smsInboxCursor.getString(indexBody) ;
arrayAdapter.add(str);
}while (smsInboxCursor.moveToNext());
}
Create a global array called isSelected like this
private boolean[] isSelected;
Then assign your array with the size like this
isSelected=new boolean[arrayAdapter.getCount()]; // Do this after setting adapter
and .setOnItemClickListener on listview and when the click happens to make sure selected of that index is set to true like this
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
isSelected[position]=!isSelected[position];
}
});
And in receive_data() select those selected positions again
public void receive_data (final String smsMsg) {
arrayAdapter = new ArrayAdapter(this,R.layout.list_item, list_items);
text_listview.setAdapter(arrayAdapter);
arrayAdapter.add(smsMsg);
arrayAdapter.notifyDataSetChanged();
boolean[] tempSelected=new boolean[arrayAdapter.getCount()];
for(int i=0;i<isSelected.length;i++)
{
tempSelected[i]=isSelected[i];
if(tempSelected[i])
{
text_listview.setItemChecked(i,true);
}
}
isSelected=tempSelected;
}
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à ...
i developing an application where i want to block SMS of some specific numbers.for this purpose i have one an Activity and Second is BroadcastReceiver class. in Activity i have a list where User will enter a number that he want to block. but i don't how will List number will be Access in BroadcastReceiver class to block it. i Access An ArrayAdapter in BroadcastReceiver class but it does not perform to block a call. Any one help me..thanks in advance..
SmsLock.java
public class SmsLock extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
String phoneNumber;
String senderNum;
NumberListActivity ma = new NumberListActivity();
NumberListActivity num = new NumberListActivity();
String[] number = new String[] { "+923327765798", "+923219750751",
"+923445508726" };
#Override
public void onReceive(Context context, Intent intent) {
ArrayAdapter<String> adapter = ma.getArrayAdapter();
// 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]);
phoneNumber = currentMessage.getDisplayOriginatingAddress();
senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
}
for (int i = 0; i < adapter.getCount(); i++) {
if (senderNum.contains(adapter.getItem(i))) {
abortBroadcast();
}
}
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
}
NumberListActivity.java
public class NumberListActivity extends Activity {
SharedPreferences preferences1;
SharedPreferences.Editor spEditor1;
int count1 = 0;
ListView numList1;
Button btnAdd1;
ArrayList<String> list1 = new ArrayList<String>();
ArrayAdapter<String> adapter1;
public static final String Place1 = "placeKey";
SmsLock brd = new SmsLock();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_list);
preferences1 = getSharedPreferences("Place1", Context.MODE_PRIVATE);
spEditor1 = preferences1.edit();
count1 = preferences1.getInt("count1", 0);
if (count1 > 0) {
for (int i = 0; i < count1; i++) {
list1.add(preferences1.getString("Value1[" + i + "]", ""));
}
}
final EditText edit = (EditText) findViewById(R.id.Item);
numList1 = (ListView) findViewById(R.id.Smslist);
btnAdd1 = (Button) findViewById(R.id.Add);
adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list1);
numList1.setAdapter(adapter1);
numList1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
/*
* list.remove(position); //preferences.edit().clear().commit();
* preferences.edit().remove("Value["+position+"]").commit();
* //count-=1; // adapter.remove(adapter.getItem(position));
*/
count1 = preferences1.getInt("count1", 0);
// if (count > 0) {
for (int i = position; i < count1; i++) {
// list.add();
if (i < count1)
spEditor1.putString(
"Value1[" + i + "]",
preferences1.getString("Value1[" + (i + 1)
+ "]", ""));
spEditor1.commit();
}
// }
list1.remove(position);
count1 -= 1;
spEditor1.putInt("count1", count1);
spEditor1.commit();
// preferences.edit().remove(position);
adapter1.notifyDataSetChanged();
}
});
btnAdd1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// EditText edit = (EditText) findViewById(R.id.txtItem);
spEditor1.putString("Value1[" + count1 + "]", edit.getText()
.toString());
spEditor1.commit();
list1.add(preferences1.getString("Value1[" + count1 + "]", ""));
count1 += 1;
spEditor1.putInt("count1", count1);
spEditor1.commit();
adapter1.notifyDataSetChanged();
}
});
}
public ArrayAdapter<String> getArrayAdapter() {
return adapter1;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent int1 = new Intent(NumberListActivity.this, Main.class);
startActivity(int1);
finish();
}
}
In your broadCast receiver, I assume you have successfully extracted the incoming SMS's phone number and the list of Numbers that are blocked. Then this code is iterating through the list of blocked numbers and entering the if-block, appropriately.
for (int i = 0; i < adapter.getCount(); i++) {
if (senderNum.contains(adapter.getItem(i))) {
abortBroadcast();
}
}
If you are sure above flow is working fine and still you are not able to block the SMS being received, then one following might be the cause:
Priotity: In your manifest file you set a priority for for your application to receive the SMS_RECEIVED intent. Suppose, that your app has a priority 10 and the OS's default SMS app has priority 20, then your app is getting a chance to respond to SMS_RECEIVED intent only after the defaul SMS app. This explains why the abortBroadcast() does not seem to work in above code.
I suggest you set the highest priority possible for your broadCastReceiver in the manifest, so that you get the first chance to handle SMS_RECEIVED intent.
From API 19 and above, there can be only one SMS application on a device. If there are 2 or more apps that have a permission to intercept SMS then user has to specify which one of the availaible applications should serve as the defult SMS app. Then the chosen default SMS app will only have the permission to respond to SMS_RECEIVED intent and other applications will not get a chance to receive SMS_RECEIVED intent.
So you also need to set your target SDK to 18 or below to use the SMS interception normally or you need to read some documentation if you want your app to be compatible with API 19.
In order to access the numbers from which sms you want to block first you need to store all the numbers either in your SQlite database or in preferences so that they can be accessed in broadcast receivers then use
abortBroadcast();
to prevent messages to go into inbox.
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();
}
}
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