主要是在程序中生成验证码,然后将验证码保存到本地,发送验证码和手机号给接口,在通过短信接口发给手机验证码。
public class MainActivity extends Activity {
private Button sc,yanzhen;
private EditText phone,shuru;
public static final String DATABASE = "Database";
private RequestQueue mQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQueue = Volley.newRequestQueue(this);
mQueue.start();
sc=(Button)findViewById(R.id.sc);
yanzhen=(Button)findViewById(R.id.yanzhen);
phone=(EditText)findViewById(R.id.phone);
shuru=(EditText)findViewById(R.id.shuru);
sc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String phone1 = phone.getText().toString();
String code = createRandom(true,4);
SharedPreferences sp = getSharedPreferences(DATABASE, Activity.MODE_PRIVATE);
// 获取Editor对象
SharedPreferences.Editor editor =sp.edit();
editor.putString("code",code);
editor.commit();
// Toast.makeText(getApplicationContext(),""+code,Toast.LENGTH_SHORT).show();
if (!TextUtils.isEmpty(phone1)){
HashMap map = new HashMap<String, String>();
map.put("TelNum",phone1);
map.put("Code",code);
Toast.makeText(getApplicationContext(),""+map,Toast.LENGTH_SHORT).show();
loginRequest(Request.Method.POST, APP_URL, map);
}else {
Toast.makeText(getApplicationContext(),"手机不能为空",Toast.LENGTH_SHORT).show();
}
}
});
yanzhen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String shuru1 = shuru.getText().toString();
SharedPreferences sp = getSharedPreferences(DATABASE, Activity.MODE_PRIVATE);
String cd =sp.getString("code","");
if (!TextUtils.isEmpty(shuru1)){
if (shuru1.equals(cd)){
Toast.makeText(getApplicationContext(),"正确",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"错误",Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(getApplicationContext(),"不能为空",Toast.LENGTH_SHORT).show();
}
}
});
}
//(网上代码)
public static String createRandom(boolean numberFlag, int length){
String retStr = "";
String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
int len = strTable.length();
boolean bDone = true;
do {
retStr = "";
int count = 0;
for (int i = 0; i < length; i++) {
double dblR = Math.random() * len;
int intR = (int) Math.floor(dblR);
char c = strTable.charAt(intR);
if (('0' <= c) && (c <= '9')) {
count++;
}
retStr += strTable.charAt(intR);
}
if (count >= 2) {
bDone = false;
}
} while (bDone);
return retStr;
}
private void loginRequest(int get, final String appUrl, final HashMap map) {
StringRequest stringRequest = new StringRequest(
get,
appUrl,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("LoginActivity", "volleyError:" + volleyError);
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return map;
}
};
mQueue.add(stringRequest);
}
}
完。