Ok i Have this broadcast reciver for Listening incoming SMS
public class SmsReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
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]);
str += msgs[i].getMessageBody().toString();
}
}
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File dir = new File (root.getAbsolutePath() + "/Bonbon info");
dir.mkdirs();
File f = new File(dir, "test.txt");
FileWriter fw = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fw);
out.write(str);
out.close();
}
} catch (IOException e) {
}
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
}
}
Now, i need to listen only specific SMS messages, that have word "Nemas" or "Potrosio" for the first word in the SMS.Can you help me with this ????
EDIT: I made a mistake, and i didn't ask a right question. I want to recive ALL messages, but only SMS with specific text I need to save into text file ?
NOTE: I believe this works on all phones, but not tested.
Uri allMessage = Uri.parse("content://sms/inbox");
ContentResolver cr = getContentResolver();
Cursor c = cr.query(allMessage, new String[]{"body"}, null, null, null);
while (c.moveToNext()) {
if(c.getColumnName(0).equals("body")){
String result = c.getString(0);
}
}
This gets the body from every SMS message stored on the phone. If you only want to see texts from the last hour:
String selection = "date>=" + (System.currentTimeMillis()-60*60*1000);
Uri allMessage = Uri.parse("content://sms/inbox");
ContentResolver cr = getContentResolver();
Cursor c = cr.query(allMessage, new String[]{"body"}, null, null, null);
while (c.moveToNext()) {
if(c.getColumnName(0).equals("body")){
String result = c.getString(0);
}
}
from there you should be able to search thru the bodies of the SMSs for what you need or write a query (just like the date example) to search them.
来源:https://stackoverflow.com/questions/7387305/listening-and-reciveing-specific-sms-message