Android广播拦截短信并回调处理
今天用android做一个接受短信验证码后直接把验证码赋值在输入框上的功能,主要操作有编写广播并设置回调,在配置清单中配置广播,在界面代码中触发调用。
1.编写自定义广播继承BroadcastReceiver并设置回调
**
* 短信监听
* @author
*
*/
public class SMSBroadcastReceiver extends BroadcastReceiver {
private static MessageListener mMessageListener;
public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
public static final String TAG = "SMSBroadcastReceiver";
public SMSBroadcastReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
Object[] pdus = (Object[]) intent.getExtras().get("pdus");
for(Object pdu:pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte [])pdu);
String sender = smsMessage.getDisplayOriginatingAddress();
//短信内容
String content = smsMessage.getDisplayMessageBody();
// String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(smsMessage.getTimestampMillis()));
//您的验证码为2354
//过滤不需要读取的短信的发送号码
if (sender.equals(sender)) {
mMessageListener.onReceived(content.substring(6,10));
//中断广播的传递
abortBroadcast();
Log.e(TAG, "onReceive: "+content.substring(6,10));
}
}
}
}
//回调接口
public interface MessageListener {
public void onReceived(String message);
}
public void setOnReceivedMessageListener(MessageListener messageListener) {
mMessageListener = messageListener;
}
}
2.在配置清单中配置广播
<receiver android:name=".util.SMSBroadcastReceiver" />
3.在界面代码中触发调用
private SMSBroadcastReceiver mSMSBroadcastReceiver;
//生成广播处理
mSMSBroadcastReceiver = new SMSBroadcastReceiver();
//实例化过滤器并设置要过滤的广播
IntentFilter intentFilter = new IntentFilter(ACTION);
intentFilter.setPriority(Integer.MAX_VALUE);
//注册广播
registerReceiver(mSMSBroadcastReceiver, intentFilter);
mSMSBroadcastReceiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.MessageListener() {
@Override
public void onReceived(String message) {
//给输入框赋值
et_messageNumber.setText(message);
}
});