我们经常在一个app注册的时候需要使用到短信验证码,输入一个手机号码,点击获取验证码,手机就能收到一条短信,输入短信中的验证码就能验证成功进而进行一些操作。
![](https://img-blog.csdn.net/20161123150333800)
当然现在提供短信服务的也有很多,我们选择一个免费的sdk平台Mob,如果有问题还可以咨询技术支持,服务还挺好的。但是因为是免费的,所以还是有一些限制吧,如果是作为测试的话,一个手机号码最多只能收到不到10次验证码,超过10次就不发送了,这时你就要换一个手机号码去接收验证码。
官网地址: http://www.mob.com/#/ 该平台还提供其他的一些服务,有需要的可以挖掘。
![](https://img-blog.csdn.net/20161123152053141)
当然你还是要注册一个账户,然后申请一个app,获取到app key 和app secret, 这个在你的项目里面需要用到,如图中的SecurityCodeSDK
![](https://img-blog.csdn.net/20161123160818585)
然后下载sdk。下图就是Android sdk下载的页面, 可以看到我们可以根据IDE选择不同的sdk,我下载的就是Android studio的sdk,
![](https://img-blog.csdn.net/20161123152535768)
下载完成之后解压出来,可以获取到如下的四个jar包, 还有一个txt文件, txt文件是添加sdk到工程的方法。
![](https://img-blog.csdn.net/20161123153730072)
先把这四个jar包拷贝到项目的libs文件夹下,然后在gradle文件中添加如下红色部分
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
minSdkVersion 23
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir{
dirs 'libs'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.0'
compile name:'SMSSDK-2.1.2',ext:'aar'
compile name:'SMSSDKGUI-2.1.2',ext:'aar'
testCompile 'junit:junit:4.12'
}
然后还要在AndroidManifest.xml文件中添加如下的activity:
- <activity
- android:name="com.mob.tools.MobUIShell"
- android:configChanges="keyboardHidden|orientation|screenSize"
- android:theme="@android:style/Theme.Translucent.NoTitleBar"
- android:windowSoftInputMode="stateHidden|adjustResize"/>
布局文件很简单,就两个textiew和两个button,下面贴上主代码:
- public class MainActivity extends AppCompatActivity implements View.OnClickListener {
-
- private static final String TAG = "SmsYanzheng";
- EditText mEditTextPhoneNumber;
- EditText mEditTextCode;
- Button mButtonGetCode;
- Button mButtonLogin;
-
- EventHandler eventHandler;
- String strPhoneNumber;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- mEditTextPhoneNumber = (EditText) findViewById(R.id.phone_number);
- mEditTextCode = (EditText) findViewById(R.id.verification_code);
- mButtonGetCode = (Button) findViewById(R.id.button_send_verification_code);
- mButtonLogin = (Button) findViewById(R.id.button_login);
-
- mButtonGetCode.setOnClickListener(this);
- mButtonLogin.setOnClickListener(this);
-
- SMSSDK.initSDK(this, "app key", "app secret");
-
- eventHandler = new EventHandler() {
-
-
-
-
-
-
-
-
-
- @Override
- public void afterEvent(int event, int result, Object data) {
- Message message = myHandler.obtainMessage(0x00);
- message.arg1 = event;
- message.arg2 = result;
- message.obj = data;
- myHandler.sendMessage(message);
- }
- };
-
- SMSSDK.registerEventHandler(eventHandler);
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- SMSSDK.unregisterEventHandler(eventHandler);
- }
-
- @Override
- public void onClick(View view) {
- if (view.getId() == R.id.button_login) {
- String strCode = mEditTextCode.getText().toString();
- if (null != strCode && strCode.length() == 4) {
- Log.d(TAG, mEditTextCode.getText().toString());
- SMSSDK.submitVerificationCode("86", strPhoneNumber, mEditTextCode.getText().toString());
- } else {
- Toast.makeText(this, "密码长度不正确", Toast.LENGTH_SHORT).show();
- }
- } else if (view.getId() == R.id.button_send_verification_code) {
- strPhoneNumber = mEditTextPhoneNumber.getText().toString();
- if (null == strPhoneNumber || "".equals(strPhoneNumber) || strPhoneNumber.length() != 11) {
- Toast.makeText(this, "电话号码输入有误", Toast.LENGTH_SHORT).show();
- return;
- }
- SMSSDK.getVerificationCode("86", strPhoneNumber);
- mButtonGetCode.setClickable(false);
-
- new Thread() {
- @Override
- public void run() {
- int totalTime = 60;
- for (int i = 0; i < totalTime; i++) {
- Message message = myHandler.obtainMessage(0x01);
- message.arg1 = totalTime - i;
- myHandler.sendMessage(message);
- try {
- sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- myHandler.sendEmptyMessage(0x02);
- }
- }.start();
- }
- }
-
- Handler myHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case 0x00:
- int event = msg.arg1;
- int result = msg.arg2;
- Object data = msg.obj;
- Log.e(TAG, "result : " + result + ", event: " + event + ", data : " + data);
- if (result == SMSSDK.RESULT_COMPLETE) {
- if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
- Toast.makeText(MainActivity.this, "发送验证码成功", Toast.LENGTH_SHORT).show();
- Log.d(TAG, "get verification code successful.");
- } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
- Log.d(TAG, "submit code successful");
- Toast.makeText(MainActivity.this, "提交验证码成功", Toast.LENGTH_SHORT).show();
- Intent intent = new Intent(MainActivity.this, SecondActivity.class);
- startActivity(intent);
- } else {
- Log.d(TAG, data.toString());
- }
- } else {
- try {
- Throwable throwable = (Throwable) data;
- throwable.printStackTrace();
- JSONObject object = new JSONObject(throwable.getMessage());
- String des = object.optString("detail");
- int status = object.optInt("status");
-
- Log.e(TAG, "status: " + status + ", detail: " + des);
- if (status > 0 && !TextUtils.isEmpty(des)) {
- Toast.makeText(MainActivity.this, des, Toast.LENGTH_SHORT).show();
- return;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- break;
- case 0x01:
- mButtonGetCode.setText("重新发送(" + msg.arg1 + ")");
- break;
- case 0x02:
- mButtonGetCode.setText("获取验证码");
- mButtonGetCode.setClickable(true);
- break;
- }
- }
- };
- }
当然还需要在AndroidManifest文件中声明权限:
- <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
- <uses-permission android:name="android.permission.RECEIVE_SMS"/>
- <uses-permission android:name="android.permission.READ_SMS"/>
- <uses-permission android:name="android.permission.READ_CONTACTS"/>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
-
-
- <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.GET_TASKS"/>
现在就可以测试手机能不能获取到验证码了,当然,前提是需要手机能访问网络。
还有详细的方法的用法和指导,可以直接区mob官网自行查询。
代码下载:github