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.
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 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 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);
}
I'll tell you the aim of this part of my app. I've got a SQLite dB which has 3 columns. First is "Quantity", Second is "Product" and third is "Price". Well, what i want to do is to get the whole dB and send it by email.
This is what i have right now:
public class Visual extends Activity {
TextView tv;
Button sqlGetInfo;
long l ;
long b=1;
int c,i;
String returnedQuantity ,returnedProduct ,returnedPrice;
String[] filas;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.visual);
tv = (TextView) findViewById(R.id.tvSQLinfo);
sqlGetInfo = (Button) findViewById(R.id.EnviarPedido);
SQLManager info = new SQLManager(this);
info.open();
String data= info.getData();
info.close();
tv.setText(data);
Up to here, my code works fine, it displays the data in the textView. Here is the problem. My dB has a maximum of 15 rows. What i want to do is to store each row in a position of a string array (filas). First row = filas(0), second row = filas(1)...in order to be able to pass this array to another activity. If the array has less than 15 rows i think it would give an exception. So it's the time to open the other activity.
final SQLManager hon = new SQLManager(this);
sqlGetInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (i = 1; i < 15; i++) {
try{
l = (long) i;
hon.open();
returnedQuantity = hon.getQuantity(l);
returnedProduct = hon.getProduct(l);
returnedPrice = hon.getPrice(l);
hon.close();
c=(int)(l-b);
filas[c]="" + returnedQuantity+" "+ returnedProduct+" "+ returnedPrice + "\n";
}catch (Exception e){
i = 16;
l = (long) i;
Intent abrePedidos = new Intent(Visual.this, Pedidos.class);
abrePedidos.putExtra("pedidoCompleto", filas);
startActivity(abrePedidos);
}
}
}
});
}
}
The other activity is this:
public class Pedidos extends Activity {
String[] filas;
long numProd;
boolean end;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
filas=getIntent().getStringArrayExtra("pedidoCompleto");
String subject = "Pedido a Domicilio";
String cabecera = "Unid. Producto Precio\n\n";
String[] emails = {"ulrickpspgo#gmail.com"};
String message = cabecera + filas;
Intent emailIntent = new Intent (android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emails);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
emailIntent.setType("plain/text");
startActivity(emailIntent);
}
}
What I get as the message of my email is "null".
I think you problem is the following: you never initialize String[] filas;. This means that it remains null all the time. Afterwards you go to your code:
try {
l = (long) i;
hon.open();
returnedQuantity = hon.getQuantity(l);
returnedProduct = hon.getProduct(l);
returnedPrice = hon.getPrice(l);
hon.close();
c=(int)(l-b);
// The next line throws null pointer exception
filas[c]="" + returnedQuantity+" "+ returnedProduct+" "+ returnedPrice + "\n";
} catch (Exception e) { // here you catch the null pointer exception
i = 16;
l = (long) i;
Intent abrePedidos = new Intent(Visual.this, Pedidos.class);
abrePedidos.putExtra("pedidoCompleto", filas); //filas is still null
startActivity(abrePedidos);
}
I have added comments for some of your lines. Why do you call the next activity only in the catch clause? Having so much code in the catch clause is very bad practise it is called expection handling. don't do it. Otherwise if you initialize your array (which I am not sure you have not already done, but this is my guess what the exception you hide is) you should be good to go. Do not forget to place the code outside the catch block, though, because I do not expect any exceptions after the modification.
EDIT I do not like the way you iterate over the elements in the database. I am not familiar with the SQLManager class you use. However the standard Android way is very similar to the JDBC model. You do a query and it returns a cursor over the results. See example of using cursors and SQLitehleprs over here: http://www.higherpass.com/Android/Tutorials/Accessing-Data-With-Android-Cursors/2/
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.