接收短信

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"/>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值