您好,登錄后才能下訂單哦!
如何在Android開發中利用Mob實現一個短信驗證碼?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
前期準備
(1)Mob網站上下載SMS對應的SDK,解壓出來為圖1,打開圖1,將其中的文件拷貝到as項目中的libs文件夾下,另外在add as library。
圖1
圖2
(2)在as項目中的AndroidManifest.xml文件中添加圖3所需權限,由于SMS權限為危險權限,所以還要動態申請,這在下面代碼中會有體現。注意權限是寫在application外面,不是里面。
圖3
(3)如果圖4中的targetSdkVersion大于22,那么在代碼中必須動態申請權限。
圖4
(4)在as項目中的圖7中的build.gradle文件中添加圖5和圖6紅色框中內容。
圖5
圖6
圖7
(5)在Mob網站上申請App Key和App Secret。
圖8
(6)Toast
3、代碼(沒整理,將就看)
package com.gxu.lepao.activity; import android.Manifest; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.Message; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.gxu.lepao.R; import com.gxu.lepao.model.UserInfo; import org.litepal.crud.DataSupport;//LitePal開源數據庫框架 import java.util.List; import cn.smssdk.EventHandler;//Mob短信驗證碼 import cn.smssdk.SMSSDK;//Mob短信驗證碼 /** * Created by ljy on 2017-05-21. * 獲取和驗證短信驗證碼界面 */ public class RegisterActivity extends BaseActivity { private EditText phoneEdit; private EditText smsEdit; private Button getSms; private Button submitSms; private TextView login; private TextView reset; private CountDownTimer countDownTimer; //倒計時 private int TIME = 60; //這是中國區號,如果需要其他國家列表,可以使用getSupportedCountries();獲得國家區號 public String country = "86"; //APPKEY private static String appKey = "1e0d15118480d"; // 填寫從短信SDK應用后臺注冊得到的APPSECRET private static String appSecret = "daa97d794e2436abcae624ac3785d2ef"; //表示是否使用了registerEventHandler private boolean ready; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("RegisterActivity","Task; id is " + getTaskId()); setContentView(R.layout.activity_register); // 初始化界面 initView(); //初始化SMSSDK initSDK(); getSms.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { boolean isLogin = false; //判斷手機號碼是否已注冊過 isLogin = isRegister(); if(!TextUtils.isEmpty(phoneEdit.getText().toString())){ if(!isLogin){ //發送短信權限 if(ContextCompat.checkSelfPermission(RegisterActivity.this ,Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED){ //顯示申請權限彈窗 showRequestPermission(); }else{ //彈窗確認 alterWarning(); } }else{ Toast.makeText(RegisterActivity.this,"此手機號碼已經注冊過",Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(RegisterActivity.this,"請輸入手機號碼",Toast.LENGTH_SHORT).show(); } } }); submitSms.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { String sms = smsEdit.getText().toString(); String phone = phoneEdit.getText().toString(); if(!TextUtils.isEmpty(sms)){ SMSSDK.submitVerificationCode( country, phone, sms); }else{ Toast.makeText(RegisterActivity.this,"請輸入驗證碼",Toast.LENGTH_SHORT).show(); } } }); login.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Intent intent = new Intent(RegisterActivity.this,LoginActivity.class); startActivity(intent); } }); reset.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Intent intent = new Intent(RegisterActivity.this,ResetPwdActivity.class); startActivity(intent); } }); } //申請權限彈窗 private void showRequestPermission(){ //先new出一個監聽器,設置好監聽 DialogInterface.OnClickListener dialogOnclicListener=new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { switch(which){ case Dialog.BUTTON_POSITIVE: //接收短信權限 ActivityCompat.requestPermissions(RegisterActivity.this,new String[]{Manifest.permission.RECEIVE_SMS},1); //發送短信權限 ActivityCompat.requestPermissions(RegisterActivity.this,new String[]{Manifest.permission.SEND_SMS},2); //彈窗確認 alterWarning(); break; case Dialog.BUTTON_NEGATIVE: Toast.makeText(RegisterActivity.this, "拒絕" + which, Toast.LENGTH_SHORT).show(); break; } } }; //dialog參數設置 AlertDialog.Builder builder=new AlertDialog.Builder(RegisterActivity.this); //先得到構造器 builder.setTitle("申請權限"); //設置標題 builder.setMessage("要允許lepao接收驗證碼短信嗎?"); //設置內容 builder.setIcon(R.mipmap.ic_launcher);//設置圖標,圖片id即可 builder.setPositiveButton("允許",dialogOnclicListener); builder.setNegativeButton("拒絕", dialogOnclicListener); builder.create().show(); } //申請權限 public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode){ case 1: if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ //initSDK(); Toast.makeText(this,"你授權。。。接收短信權限",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this,"你拒絕。。。接收短信權限",Toast.LENGTH_SHORT).show(); } break; case 2: if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ Toast.makeText(this,"你授權。。。發送短信權限",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this,"你拒絕。。。發送短信權限",Toast.LENGTH_SHORT).show(); } break; default: } } // 初始化短信SDK private void initSDK() { SMSSDK.initSDK(this, appKey, appSecret, true); //final Handler handler = new Handler(); EventHandler eventHandler = new EventHandler() { public void afterEvent(int event, int result, Object data) { //回調完成 if (result == SMSSDK.RESULT_COMPLETE) { //驗證碼驗證成功 if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) { toast("驗證成功"); Intent intent = new Intent(RegisterActivity.this,SetPwdActivity.class); intent.putExtra("phone",phoneEdit.getText().toString()); startActivity(intent); finish(); } //已發送驗證碼 else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) { toast("驗證碼已經發送"); } else { ((Throwable) data).printStackTrace(); String str = data.toString(); toast(str); } } if(result==SMSSDK.RESULT_ERROR) { toast("驗證碼錯誤"); } } }; // 注冊回調監聽接口 SMSSDK.registerEventHandler(eventHandler); ready = true; } //吐司的一個小方法 private void toast(final String str) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(RegisterActivity.this, str, Toast.LENGTH_SHORT).show(); } }); } //銷毀短信注冊 @Override protected void onDestroy() { // 注銷回調接口registerEventHandler必須和unregisterEventHandler配套使用,否則可能造成內存泄漏。 if(ready){ SMSSDK.unregisterAllEventHandler(); } super.onDestroy(); } //初始化界面 private void initView(){ phoneEdit = (EditText) findViewById(R.id.phone); smsEdit = (EditText) findViewById(R.id.sms); getSms = (Button) findViewById(R.id.getSms); submitSms = (Button) findViewById(R.id.submitSms); login = (TextView) findViewById(R.id.login); reset = (TextView) findViewById(R.id.reset); } //彈窗確認 private void alterWarning(){ //先new出一個監聽器,設置好監聽 DialogInterface.OnClickListener dialogOnclicListener=new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { switch(which){ case Dialog.BUTTON_POSITIVE: dialog.dismiss(); //通過sdk發送短信驗證(請求獲取短信驗證碼,在監聽(eventHandle)中返回) SMSSDK.getVerificationCode(country, phoneEdit.getText().toString()); //設置獲取驗證碼按鈕不能點擊 getSms.setClickable(false); //倒計時,執行次數為(TIME+1)*1000/1000,countDownTimer每次執行間隔:1000(單位為毫秒) countDownTimer = new CountDownTimer((TIME+1)*1000, 1000) { @Override public void onTick(long millisUntilFinished) { getSms.setText(TIME-- + "秒后再次獲取驗證碼"); } @Override public void onFinish() { //設置獲取驗證碼按鈕可以點擊 getSms.setClickable(true); getSms.setText("點擊獲取短信驗證碼"); } }; countDownTimer.start(); break; case Dialog.BUTTON_NEGATIVE: dialog.dismiss(); Toast.makeText(RegisterActivity.this, "已取消", Toast.LENGTH_SHORT).show(); break; } } }; //dialog參數設置 AlertDialog.Builder builder=new AlertDialog.Builder(this); //先得到構造器 builder.setTitle("發送短信"); //設置標題 builder.setMessage("我們將把驗證碼發送到以下號碼:\n"+country+"-"+phoneEdit.getText().toString()); //設置內容 builder.setIcon(R.drawable.icon);//設置圖標,圖片id即可 builder.setPositiveButton("確認",dialogOnclicListener); builder.setNegativeButton("取消", dialogOnclicListener); builder.create().show(); } //判斷手機號碼是否已注冊過 public boolean isRegister(){ boolean isLogin = false; 。。。。。299 return isLogin; } }
看完上述內容,你們掌握如何在Android開發中利用Mob實現一個短信驗證碼的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。