短信工具类 SmsUtil

只需要 服务器 获取验证码接口
布局中 设置一个 输入框 一个按钮 就可以 获取验证码后倒计时 并将短信自动填写到输入框

/**
 * 获取验证码工具
 * 功能:获取验证码 按钮倒计时, 自动填写验证码
 * Created by my on 2016/4/21.
 */
public class VcodeUtils {
    /**
     * 获取验证码
     *
     * @param
     */
    private Button mBt_vcode;
    private EditText mEtVcode;
    private Activity acitvity;
    private SMSReceiver mSmsReceiver;


    /**
     * @param mBt_vcode 倒计时的button
     * @param acitvity
     */
    public VcodeUtils(Button mBt_vcode, Activity acitvity,EditText mEtVcode ) {
        this.mBt_vcode = mBt_vcode;
        this.acitvity = acitvity;
        this.mEtVcode=mEtVcode;
        registSmsReciver();
    }
    private CountDownTimer timer = new CountDownTimer(30000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            //  btVcode.setText("重新发送(" + msg.arg1 + ")");
            mBt_vcode.setEnabled(false);
            mBt_vcode.setTextColor(Color.GRAY);
            mBt_vcode.setText((millisUntilFinished / 1000) + "秒后可重发");
        }

        @Override
        public void onFinish() {
            mBt_vcode.setEnabled(true);
            mBt_vcode.setTextColor(Color.parseColor("#ff4e8de3"));
            mBt_vcode.setText("获取验证码");
        }
    };
    public void getVcode(String url) {
        final Dialog progressDialog = CustomProgress.show(acitvity, "加载中", true, null);
        OkHttpUtils.get()
                .url(url)
                .addHeader("DeviceID", MyApplication.DeviceID)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
                Toast.makeText(acitvity, "获取验证码失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response) {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
                String result = StreamUtils.decodeUnicode(response);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String code = jsonObject.getString("code");
                    if (code.equals("200")) {
                        Toast.makeText(acitvity, "获取验证码成功", Toast.LENGTH_SHORT).show();
                        timer.start();
                    } else {
                        Toast.makeText(acitvity, "获取验证码失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }
    public static boolean checkMobile(String mobile) {
        Pattern pattern = Pattern.compile("^1\\d{10}");
        Matcher matcher = pattern.matcher(mobile);
        if (matcher.find()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 注册短信广播接收者
     */
    private  void registSmsReciver() {
        mSmsReceiver = new SMSReceiver();
        mSmsReceiver.setMessageListener(new SMSReceiver.MessageListener() {
            @Override
            public void onReceived(String cont) {
                mEtVcode.setText(cont);
            }
        });
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        intentFilter.setPriority(1000);
        acitvity.registerReceiver(mSmsReceiver,intentFilter);//注册
    }

    /**
     * 必须在合适位置调用此方法  解绑广播接收者
     * 可以再 onDestroy() 中使用该函数
     */
    public   void unregisterReceiver(){
        if(mSmsReceiver!=null){
            acitvity.unregisterReceiver(mSmsReceiver);
            mSmsReceiver=null;
        }
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的Java发送短信工具类: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class SMSUtil { private static final String SMS_URL = "http://sms.com/sendSMS.php"; private static final String SMS_USERNAME = "your_username"; private static final String SMS_PASSWORD = "your_password"; public static void sendSMS(String phoneNumber, String message) throws Exception { // Encode phone number and message String encodedPhoneNumber = URLEncoder.encode(phoneNumber, "UTF-8"); String encodedMessage = URLEncoder.encode(message, "UTF-8"); // Create the SMS URL String smsUrl = SMS_URL + "?username=" + SMS_USERNAME + "&password=" + SMS_PASSWORD + "&phone=" + encodedPhoneNumber + "&message=" + encodedMessage; // Send the SMS URL url = new URL(smsUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // Read the response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String response = reader.readLine(); reader.close(); // Check the response if (!response.startsWith("OK")) { throw new Exception("Failed to send SMS: " + response); } } } ``` 使用方式: ```java try { SMSUtil.sendSMS("1234567890", "Hello, World!"); System.out.println("SMS sent successfully"); } catch (Exception e) { System.err.println("Error sending SMS: " + e.getMessage()); } ``` 注意:这个工具类是一个简单的示例,实际使用时需要替换SMS_URL、SMS_USERNAME和SMS_PASSWORD为你自己的信息。另外,这个工具类只支持GET方式发送短信,实际使用时可能需要根据短信服务商的要求修改为POST方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值