public class SmsRecevier extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "有短消息来了", Toast.LENGTH_LONG).show();
Bundle b = intent.getExtras();
Object[] pdus = (Object[]) b.get("pdus");
SmsMessage[] smsMsgs = new SmsMessage[pdus.length];
for (int i = 0; i < smsMsgs.length; i++) {
smsMsgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
String phoneNumber = null;
String data = null;
StringBuilder builder = new StringBuilder();
for (SmsMessage sms : smsMsgs) {
phoneNumber = sms.getDisplayOriginatingAddress();
data = sms.getDisplayMessageBody();
builder.append(data);
}
Log.i("SmsRecevier ", "短信号码:" + phoneNumber);
Log.i("SmsRecevier ", "短信内容:" + builder.toString());
abortBroadcast();
NotificationCompat.Builder nb = new NotificationCompat.Builder(context);
nb.setContentTitle(phoneNumber);
nb.setContentText(builder.toString());
nb.setSmallIcon(R.drawable.ic_launcher);
NotificationManager nm = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE);
nm.notify(2, nb.build());
}
}
<receiver android:name="com.qianfeng.day23_broadcastsystem.SmsRecevier">
<intent-filter android:priority="3000">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>