现在的应用在注册登录或者修改密码中都用到了短信验证码,那在android中是如何实现获取短信验证码并自动填写的呢?
首先,需要要在manifest中注册接收和读取短信的权限:
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"/>
实现一个广播SMSBroadcastReceiver来监听短信:
package com.example.receive;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
/**
* 短信监听
* @author
*
*/
public class SMSBroadcastReceiver extends BroadcastReceiver {
private static MessageListener mMessageListener;
public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
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();
long date = smsMessage.getTimestampMillis();
Date tiemDate = new Date(date);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = simpleDateFormat.format(tiemDate);
//过滤不需要读取的短信的发送号码
if ("+8613450214963".equals(sender)) {
mMessageListener.onReceived(content);
abortBroadcast();
}
}
}
}
//回调接口
public interface MessageListener {
public void onReceived(String message);
}
public void setOnReceivedMessageListener(MessageListener messageListener) {
this.mMessageListener = messageListener;
}
}
在需要填写验证码的Activity中,生产SMSBroadcastReceiver的实例,实现onReceived的回调接口。为了节约系统资源,我们使用动态注册注销广播的方法。
package com.example.smstest;
import com.example.receive.SMSBroadcastReceiver;
import android.os.Bundle;
import android.app.Activity;
import android.content.IntentFilter;
import android.view.Menu;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText edtPassword;
private SMSBroadcastReceiver mSMSBroadcastReceiver;
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtPassword = (EditText) findViewById(R.id.password);
}
@Override
protected void onStart() {
super.onStart();
//生成广播处理
mSMSBroadcastReceiver = new SMSBroadcastReceiver();
//实例化过滤器并设置要过滤的广播
IntentFilter intentFilter = new IntentFilter(ACTION);
intentFilter.setPriority(Integer.MAX_VALUE);
//注册广播
this.registerReceiver(mSMSBroadcastReceiver, intentFilter);
mSMSBroadcastReceiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.MessageListener() {
@Override
public void onReceived(String message) {
edtPassword.setText(message);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
//注销短信监听广播
this.unregisterReceiver(mSMSBroadcastReceiver);
}
}
第二种方法是通过监听短信库的变化,使用 短信观察者
- ContentObserver c=new ContentObserver(han) {
- @Override
- public void onChange(boolean selfChange) {
- // TODO Auto-generated method stub
- super.onChange(selfChange);
- han.sendEmptyMessage(0);
- }
- };
- getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, c);
- Handler han = new Handler() {
- @SuppressWarnings("deprecation")
- public void handleMessage(android.os.Message msg) {
- String codestr = null;
- try {
- codestr = Cus_UnitTools.getsmsyzm(Reg_ForgetPassword.this);
- code.setText(codestr);
- requestcode();
- } catch (Exception e) {
- Log.e("yung", "验证码提取失败:" + codestr);
- }
- };
- };
- public static String getsmsyzm(Activity c) {
- Uri uri = Uri.parse("content://sms/inbox");
- String[] projection = new String[] { "address", "person", "body" };
- String selection = " address='" + JTPHONE + "' ";
- String[] selectionArgs = new String[] {};
- String sortOrder = "date desc";
- @SuppressWarnings("deprecation")
- Cursor cur = c.managedQuery(uri, projection, selection, selectionArgs,
- sortOrder);
- if(cur!=null&&cur.getCount()>0){
- cur.moveToFirst();
- String body = cur.getString(cur.getColumnIndex("body")).replaceAll(
- "\n", " ");
- cur.close();
- return getyzm(body, YZMLENGTH);
- }
- cur.close();
- return null;
- }
- /**
- * 从短信字符窜提取验证码
- * @param body 短信内容
- * @param YZMLENGTH 验证码的长度 一般6位或者4位
- * @return 接取出来的验证码
- */
- public static String getyzm(String body, int YZMLENGTH) {
- // 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的六位数字字母组合
- // (?<![a-zA-Z0-9])负向断言([0-9]{YZMLENGTH})前面不能有数字
- // (?![a-zA-Z0-9])断言([0-9]{YZMLENGTH})后面不能有数字出现
- Pattern p = Pattern
- .compile("(?<![a-zA-Z0-9])([a-zA-Z0-9]{" + YZMLENGTH + "})(?![a-zA-Z0-9])");
- Matcher m = p.matcher(body);
- if (m.find()) {
- System.out.println(m.group());
- return m.group(0);
- }
- return null;
- }
请参考 http://blog.csdn.net/yung7086/article/details/26094987