Android广播拦截短信并回调处理

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);
        }
    });


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值