1. Monitor the broadcast
Disadvantages, it may not be received due to priorities.
Code:
public static final String TAG = "ImiChatSMSReceiver"; public static final String SMS_RECEIVED_ACTION = ".SMS_RECEIVED"; public void onReceive(Context context, Intent intent) { if (().equals(SMS_RECEIVED_ACTION)) { SmsMessage[] messages = getMessagesFromIntent(intent); for (SmsMessage message : messages) { String text = () + " : " + () + " : " + () + " : " + (); String num = (); (TAG, "-------------" + text); (context, text, Toast.LENGTH_LONG).show(); sendMessage(num, "From" + num + "The text message has been received", context); ().registerContentObserver(("content://sms/"), true, new SmsObserver(new Handler(), context)); } } } public void sendMessage(String num, String text, Context context) { SmsManager smsManager = (); PendingIntent sentIntent = (context, 0, new Intent(), 0); String strContent = text; (num, null, strContent, sentIntent, null); TelephonyManager tl = (TelephonyManager) (Context.TELEPHONY_SERVICE); int itype = (); (TAG, "-------------" + "The current card type is:" + itype); if (itype == TelephonyManager.PHONE_TYPE_GSM) { (context, "Current card type is: GSM", Toast.LENGTH_LONG).show(); } else if (itype == TelephonyManager.PHONE_TYPE_CDMA) { (context, "Current card type is: CDMA", Toast.LENGTH_LONG).show(); } else if (itype == TelephonyManager.PHONE_TYPE_NONE) { (context, "Current card type is: NONE", Toast.LENGTH_LONG).show(); } } public final SmsMessage[] getMessagesFromIntent(Intent intent) { Object[] messages = (Object[]) ("pdus"); byte[][] pduObjs = new byte[][]; for (int i = 0; i < ; i++) { pduObjs[i] = (byte[]) messages[i]; } byte[][] pdus = new byte[][]; int pduCount = ; SmsMessage[] msgs = new SmsMessage[pduCount]; for (int i = 0; i < pduCount; i++) { pdus[i] = pduObjs[i]; msgs[i] = (pdus[i]); } return msgs; }
2. Use observation method to monitor the SMS database
public class SmsObserver extends ContentObserver { private Context mContext; public SmsObserver(Handler handler , Context context) { super(handler); mContext = context; } public void onChange(boolean selfChange) { (selfChange); Cursor cursor =null; try { //Read SMS in Inbox cursor = ().query(("content://sms/inbox"), null, null, null, "date desc"); String body; boolean hasDone =false; if (cursor !=null) { while (()) { body = (("body")); if(body !=null)//&& ("【startMyActivity】" { hasDone =true; break; } if (hasDone) { break; } } } } catch(Exception e) { (); } finally { if(cursor!=null) (); } } }
Permissions used:
<uses-permission android:name=".SEND_SMS" /> <uses-permission android:name=".RECEIVE_SMS" /> <uses-permission android:name=".READ_SMS" />