public class MainActivity extends Activity {
private TextView name, Context;
private IntentFilter receiveFilter;
private MessageReceiver messageReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.name);
Context = (TextView) findViewById(R.id.Context);
//动态注册广播
receiveFilter=new IntentFilter();
receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
messageReceiver=new MessageReceiver();
registerReceiver(messageReceiver, receiveFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(messageReceiver);
}
//广播接收器
class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(android.content.Context context, Intent intent) {
//从Intent参数中取出一个Bundle对象
Bundle bundle = intent.getExtras();
//使用pdu密钥来提取一个SMS odus数组,其中每一个pdu都表示一条短信消息。
Object[] pdus = (Object[]) bundle.get("pdus");//获取短信消息
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
String address = messages[0].getOriginatingAddress();//获取发送方号码
String fullMessage = "";
for (SmsMessage message : messages) {
fullMessage += message.getMessageBody();//获取短信内容
}
name.setText(address);
Context.setText(fullMessage);
}
}
}
权限
<uses-permission android:name="android.permission.RECEIVE_SMS"/>