通过定义一个继承BroadcastReceiver类来实现,继承该类后覆盖其onReceiver方法,并在该方法中响应事件。
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// get data from SMS intent
Bundle bundle = intent.getExtras();
if (bundle != null){
// get message by "pdus"
Object[] objArray = (Object[]) bundle.get("pdus");
// rebuild SMS
SmsMessage[] messages = new SmsMessage[objArray.length];
for (int i=0; i < objArray.length; i++){
messages[i] = SmsMessage.createFromPdu((byte[])objArray[i]);
StringBuilder str = new StringBuilder("from: ");
str.append(messages[i].getDisplayOriginatingAddress());
str.append("\nmessage:\n");
str.append(messages[i].getDisplayMessageBody());