最近做一个用户注册短信验证的功能,为了方便用户我就增加一个自动识别验证短信的功能。下面直接上代码:
2、使用代码实现短信验证,这里使用的是Mob短信验证平台,详细内容参考:http://blog.csdn.net/crazy1235/article/details/41912003。
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class RegisteredActivity extends Activity implements OnClickListener{
private EditText etPhone;
private EditText etCode;
private Button btnValidation;
private int i = 30;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.registered);
initView();
initData();
setListener();
}
private void initView() {
// TODO Auto-generated method stub
etPhone = (EditText) findViewById(R.id.et_phone);
etCode = (EditText) findViewById(R.id.et_code);
btnValidation = (Button) findViewById(R.id.btn_validation);
}
private void initData() {
// TODO Auto-generated method stub
// 启动短信验证sdk
SMSSDK.initSDK(this, "61cbcec26abd", "1b4f765b20660bf975f942c1d71cc64e");
EventHandler eventHandler = new EventHandler(){
@Override
public void afterEvent(int event, int result, Object data) {
Message msg = new Message();
msg.what = 1;
msg.arg1 = event;
msg.arg2 = result;
msg.obj = data;
handler.sendMessage(msg);
}
};
//注册回调监听接口
SMSSDK.registerEventHandler(eventHandler);
}
private void setListener() {
// TODO Auto-generated method stub
btnValidation.setOnClickListener(this);
}
private void smsMonitor(){
//注册广播
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.gesoft.qingchunhao.activity.registered");
registerReceiver(broadcastReceiver, intentFilter);
//启动短信监听Service
intent = new Intent(RegisteredActivity.this, SmsStatusService.class);
startService(intent);
}
private void stopSmsMonitor(){
//注销广播,停止Service
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
etCode.setText(intent.getStringExtra("code"));
}
};
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String phoneNums = etPhone.getText().toString();
switch (v.getId()) {
case R.id.btn_validation:
// 1. 通过规则判断手机号
if (!judgePhoneNums(phoneNums)) {
return;
}
smsMonitor();
// 2. 通过sdk发送短信验证
SMSSDK.getVerificationCode("86", phoneNums);
// 3. 把按钮变成不可点击,并且显示倒计时(正在获取)
i = 30;
btnValidation.setClickable(false);
btnValidation.setText("(" + i + ")");
new Thread(new Runnable() {
@Override
public void run() {
for (; i > 0; i--) {
handler.sendEmptyMessage(2);
if (i <= 0) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
handler.sendEmptyMessage(3);
}
}).start();
break;
}
}
/**
* 判断手机号码是否合理
* @param phoneNums
*/
private boolean judgePhoneNums(String phoneNums) {
if (isMatchLength(phoneNums, 11)
&& isMobileNO(phoneNums)) {
return true;
}
Toast.makeText(this, "手机号码输入有误!",Toast.LENGTH_SHORT).show();
return false;
}
/**
* 判断一个字符串的位数
* @param str
* @param length
* @return
*/
public static boolean isMatchLength(String str, int length) {
if (str.isEmpty()) {
return false;
} else {
return str.length() == length ? true : false;
}
}
/**
* 验证手机格式
*/
public static boolean isMobileNO(String mobileNums) {
/*
* 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
* 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通)
* 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9
*/
String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
if (TextUtils.isEmpty(mobileNums))
return false;
else
return mobileNums.matches(telRegex);
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
String sign = (String)msg.obj;
SimpleHUD.dismiss();
if(!TextUtils.isEmpty(sign) && sign.equals("注册成功!")){
SimpleHUD.showSuccessMessage(RegisteredActivity.this, sign);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
finish();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}else{
SimpleHUD.showErrorMessage(RegisteredActivity.this, sign);
}
break;
case 1:
SimpleHUD.dismiss();
int event = msg.arg1;
int result = msg.arg2;
Object data = msg.obj;
if (result == SMSSDK.RESULT_COMPLETE) {
// 短信注册成功后,返回MainActivity,然后提示
if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
Toast.makeText(getApplicationContext(), "验证成功",Toast.LENGTH_SHORT).show();
} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
Toast.makeText(getApplicationContext(), "验证码已经发送",Toast.LENGTH_SHORT).show();
} else {
((Throwable) data).printStackTrace();
}
}else{
SimpleHUD.showErrorMessage(RegisteredActivity.this, "验证码错误!");
}
break;
case 2:
btnValidation.setText("(" + i + ")");
break;
case 3:
btnValidation.setText("获取");
btnValidation.setClickable(true);
break;
}
}
};
@Override
protected void onDestroy() {
SMSSDK.unregisterAllEventHandler();
stopSmsMonitor();
super.onDestroy();
}
}
上面还缺少一个验证按钮,进行验证。增加一个按钮,点击事件中加入下面的方法进行验证。
SMSSDK.submitVerificationCode("86", phoneNums, etCode.getText().toString());
3、下面实现短信内容识别Service
package com.gesoft.qingchunhao.activity.registered;
import android.app.Service;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class SmsStatusService extends Service{
@Override
public void onCreate() {
//为content://sms的数据改变注册监听器
getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, new SmsObserver(new Handler()));
super.onCreate();
}
// ContentObserver监听器类
private final class SmsObserver extends ContentObserver{
public SmsObserver(Handler handler){
super(handler);
}
public void onChange(boolean selfChange){
sendMsg();
}
private void sendMsg(){
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/"), null, null, null, null);
if (cursor.moveToFirst()){
String strMsm = cursor.getString(cursor.getColumnIndex("body"));
if(strMsm.indexOf("短信中的关键字") != -1){
Intent intent = new Intent();
//截取验证码,一般为后四位
intent.putExtra("code", strMsm.substring(strMsm.length()-4));
//为了过滤广播设置Action,唯一的
intent.setAction("com.gesoft.qingchunhao.activity.registered");
sendBroadcast(intent);
}
}
if(cursor!=null){
cursor.close();
cursor=null;
}
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
4、短信监听需要的权限
还有Service不要忘了声明,因为项目中的部分代码,所以现在还没有源码,以后有时间会整理出来。