您的当前位置:首页Android实现获取短信验证码的功能以及自定义GUI短信验证

Android实现获取短信验证码的功能以及自定义GUI短信验证

2024-12-13 来源:哗拓教育

1、 获取SDK


app是这个Project的一个module。如要在这个module里面使用带界面的SMSSDK。就将MobCommons.jar,MobTools.jar,SMSSDK-2.0.2.aar,SMSSDKGUI-2.0.2.aar放到了app的libs目录下。然后在app目录下的build.gradle,加上红圈中的这几句就行了。注意版本号要一致。我这里用的是
repositories{  
    flatDir{  
        dirs 'libs' //就是你放aar的目录地址  
    }  
}  
dependencies {  
    compile fileTree(include: ['*.jar'], dir: 'libs')  
    testCompile 'junit:junit:4.12'  
    compile 'com.android.support:appcompat-v7:21.0.3'  
    compile name:'SMSSDK-2.0.2',ext:'aar'  
    compile name:'SMSSDKGUI-2.0.2',ext:'aar'  
}  
Paste_Image.png

2、配置AndroidManifest.xml

打开您项目的AndroidManifest.xml,在其中添加如下的权限:

<uses-permission android:name="android.permission.READ_CONTACTS" />  
<uses-permission android:name="android.permission.READ_PHONE_STATE" />  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
<uses-permission android:name="android.permission.INTERNET" />  
<uses-permission android:name="android.permission.RECEIVE_SMS" />  
<uses-permission android:name="android.permission.GET_TASKS" />  
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

如果使用自带的GUI,需要再“application”下添加如下activity:

<activity  
android:name="com.mob.tools.MobUIShell"  
android:theme="@android:style/Theme.Translucent.NoTitleBar"  
android:configChanges="keyboardHidden|orientation|screenSize"  
android:windowSoftInputMode="stateHidden|adjustResize"/>  

3、添加代码

启动SDK

在您的项目启动时,调用下面的代码:
SMSSDK.initSDK(this, "您的appkey", "您的appsecret");
发送短信验证码
短信SDK内置了开源的GUI功能,您可以通过调用下面的代码打开短信验证页面:

//打开注册页面  
RegisterPage registerPage = new RegisterPage();  
registerPage.setRegisterCallback(new EventHandler() {  
public void afterEvent(int event, int result, Object data) {  
// 解析注册结果  
if (result == SMSSDK.RESULT_COMPLETE) {  
@SuppressWarnings("unchecked")  
HashMap<String,Object> phoneMap = (HashMap<String, Object>) data;  
String country = (String) phoneMap.get("country");  
String phone = (String) phoneMap.get("phone");   
  
// 提交用户信息  
registerUser(country, phone);  
}  
}  
});  
registerPage.show(context);  
// 提交用户信息  
    private void registerUser(String country, String phone) {  
        Random rnd = new Random();  
        int id = Math.abs(rnd.nextInt());  
        String uid = String.valueOf(id);  
        String nickName = "SmsSDK_User_" + uid;  
        String avatar = AVATARS[id % 12];  
        SMSSDK.submitUserInfo(uid, nickName, avatar, country, phone);  
    }  

其中的AVATARS就是一个字符串数组,里面是头像的网络链接而已,这些在下载的SDKDEMO中可查看。

4、下面看看如何自定义GUI短信验证而不是调用系统的设计我们的布局文件:

<RelativeLayout   
      
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MainActivity" >  
   
    <TextView  
        android:id="@+id/textView2"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="20dp"  
        android:text="短信验证"  
        android:textColor="#00ffaa"  
        android:textSize="20dp" />  
   
    <TextView  
        android:id="@+id/textView1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_below="@+id/textView2"  
        android:layout_marginLeft="20dp"  
        android:layout_marginTop="20dp"  
        android:text="手机号:" />  
   
    <EditText  
        android:id="@+id/phone"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignBaseline="@+id/textView1"  
        android:layout_alignBottom="@+id/textView1"  
        android:layout_toRightOf="@+id/textView1"  
        android:maxLength="11"  
        android:ems="11"  
        android:inputType="phone" >  
        <requestFocus />  
        </EditText>  
   
    <TextView  
        android:id="@+id/textView3"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignLeft="@+id/textView1"  
        android:layout_marginTop="40dp"  
        android:layout_below="@+id/phone"  
        android:text="验证码:"/>  
   
    <EditText  
        android:id="@+id/cord"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_marginTop="20dp"  
        android:layout_alignBaseline="@+id/textView3"  
        android:layout_alignBottom="@+id/textView3"  
        android:layout_alignLeft="@+id/phone"  
        android:ems="4"  
        android:maxLength="4"  
        android:inputType="phone" />  
   
    <Button  
        android:id="@+id/getcord"  
        style="?android:attr/buttonStyleSmall"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignTop="@+id/cord"  
        android:layout_marginLeft="20dp"  
        android:layout_marginTop="10dp"  
        android:layout_toRightOf="@+id/cord"  
        android:visibility="visible"  
        android:text="获取验证码" />  
   
    <Button  
        android:id="@+id/savecord"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:layout_below="@+id/cord"  
        android:layout_margin="20dp"  
        android:text="验证" />  
   
    <TextView  
        android:id="@+id/now"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:layout_above="@+id/savecord"  
        android:layout_toRightOf="@+id/cord"  
        android:gravity="center_horizontal"  
        android:visibility="gone"  
        android:text="提示信息"  
        android:textColor="#aaaaaa" />  
       
</RelativeLayout>  

一个主Activity代码如下:

public class MainActivity extends Activity implements OnClickListener{  
       
    private EditText phone;  
    private EditText cord;  
    private TextView now;  
    private Button getCord;  
    private Button saveCord;  
       
    private String iPhone;  
    private String iCord;  
    private int time = 60;  
    private boolean flag = true;  
   
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(R.layout.activity_main);  
        init();  
           
     SMSSDK.initSDK(this, "<您的appkey>", "<您的appsecret>");  
        EventHandler eh=new EventHandler(){  
   
            @Override  
            public void afterEvent(int event, int result, Object data) {  
                   
                Message msg = new Message();  
                msg.arg1 = event;  
                msg.arg2 = result;  
                msg.obj = data;  
                handler.sendMessage(msg);  
            }  
               
        };  
        SMSSDK.registerEventHandler(eh);  
           
    }  
   
    private void init() {  
        phone = (EditText) findViewById(R.id.phone);  
        cord = (EditText) findViewById(R.id.cord);  
        now = (TextView) findViewById(R.id.now);  
        getCord = (Button) findViewById(R.id.getcord);  
        saveCord = (Button) findViewById(R.id.savecord);  
        getCord.setOnClickListener(this);  
        saveCord.setOnClickListener(this);  
    }  
   
    @Override  
    public void onClick(View v) {  
        switch (v.getId()) {  
        case R.id.getcord:  
            if(!TextUtils.isEmpty(phone.getText().toString().trim())){  
                if(phone.getText().toString().trim().length()==11){  
                    iPhone = phone.getText().toString().trim();  
                    SMSSDK.getVerificationCode("86",iPhone);  
                    cord.requestFocus();  
                    getCord.setVisibility(View.GONE);  
                }else{  
                    Toast.makeText(MainActivity.this, "请输入完整电话号码", Toast.LENGTH_LONG).show();  
                    phone.requestFocus();  
                }  
            }else{  
                Toast.makeText(MainActivity.this, "请输入您的电话号码", Toast.LENGTH_LONG).show();  
                phone.requestFocus();  
            }  
            break;  
   
        case R.id.savecord:  
            if(!TextUtils.isEmpty(cord.getText().toString().trim())){  
                if(cord.getText().toString().trim().length()==4){  
                    iCord = cord.getText().toString().trim();  
                    SMSSDK.submitVerificationCode("86", iPhone, iCord);  
                    flag = false;  
                }else{  
                    Toast.makeText(MainActivity.this, "请输入完整验证码", Toast.LENGTH_LONG).show();  
                    cord.requestFocus();  
                }  
            }else{  
                Toast.makeText(MainActivity.this, "请输入验证码", Toast.LENGTH_LONG).show();  
                cord.requestFocus();  
            }  
            break;  
               
        default:  
            break;  
        }  
    }  
       
    //验证码送成功后提示文字  
    private void reminderText() {  
        now.setVisibility(View.VISIBLE);  
        handlerText.sendEmptyMessageDelayed(1, 1000);  
    }  
   
    Handler handlerText =new Handler(){  
        public void handleMessage(Message msg) {  
            if(msg.what==1){  
                if(time>0){  
                    now.setText("验证码已发送"+time+"秒");  
                    time--;  
                    handlerText.sendEmptyMessageDelayed(1, 1000);  
                }else{  
                    now.setText("提示信息");  
                    time = 60;  
                    now.setVisibility(View.GONE);  
                    getCord.setVisibility(View.VISIBLE);  
                }  
            }else{  
                cord.setText("");  
                now.setText("提示信息");  
                time = 60;  
                now.setVisibility(View.GONE);  
                getCord.setVisibility(View.VISIBLE);  
            }  
        };  
    };  
       
    Handler handler=new Handler(){  
   
        @Override  
        public void handleMessage(Message msg) {  
            // TODO Auto-generated method stub  
            super.handleMessage(msg);  
            int event = msg.arg1;  
            int result = msg.arg2;  
            Object data = msg.obj;  
            Log.e("event", "event="+event);  
            if (result == SMSSDK.RESULT_COMPLETE) {  
                //短信注册成功后,返回MainActivity,然后提示新好友  
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功,验证通过  
                    Toast.makeText(getApplicationContext(), "验证码校验成功", Toast.LENGTH_SHORT).show();  
                    handlerText.sendEmptyMessage(2);  
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){//服务器验证码发送成功  
                    reminderText();  
                    Toast.makeText(getApplicationContext(), "验证码已经发送", Toast.LENGTH_SHORT).show();  
                }else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){//返回支持发送验证码的国家列表  
                    Toast.makeText(getApplicationContext(), "获取国家列表成功", Toast.LENGTH_SHORT).show();  
                }  
            } else {  
                if(flag){  
                    getCord.setVisibility(View.VISIBLE);  
                    Toast.makeText(MainActivity.this, "验证码获取失败,请重新获取", Toast.LENGTH_SHORT).show();  
                    phone.requestFocus();  
                }else{  
                    ((Throwable) data).printStackTrace();  
                    int resId = getStringRes(MainActivity.this, "smssdk_network_error");  
                    Toast.makeText(MainActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();  
                    cord.selectAll();  
                    if (resId > 0) {  
                        Toast.makeText(MainActivity.this, resId, Toast.LENGTH_SHORT).show();  
                    }  
                }  
                   
            }  
               
        }  
           
    };  
       
    @Override  
    protected void onDestroy() {  
        super.onDestroy();  
        SMSSDK.unregisterAllEventHandler();  
    }  
   
}  

handlerText是自定义设计的Handler对象,用于当服务器发送验证码后,提醒用户注意。

显示全文