Android 获取短信验证

Android 获取短信验证

Android 获取短信验证

输入发短信的手机号,点击获取验证码,等接收到验证码后就会自动获取

SmsReceiver.Java

java 复制代码
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver {

    private Handler handler;

    public SmsReceiver(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        // 获取短信类型
        String format = intent.getStringExtra("format");
        Bundle bundle = intent.getExtras();

        // 提前短信消息
        Object[] pdus = (Object[]) bundle.get("pdus");
        SmsMessage[] messages = new SmsMessage[pdus.length];

        if (Build.VERSION.SDK_INT >= 23) {
            for (int i = 0; i < messages.length; i++) {
                // 此方法适用于Android6.0
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
            }
        } else {
            for (int i = 0; i < messages.length; i++) {
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            }
        }

        String number = messages[0].getOriginatingAddress();
        String content = "";
        for (SmsMessage message : messages) {
            // 获取短信内容
            content += message.getMessageBody();
        }

        Message message = handler.obtainMessage();
        message.what = 123;
        Bundle bundle1 = new Bundle();
        bundle.putString("number", number);
        bundle.putString("content", content);
        message.setData(bundle);
        handler.sendMessage(message);
    }


}

ReceiveMessage.Java

java 复制代码
import android.Manifest;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.xxh.test1.R;


public class ReceiveMessage extends AppCompatActivity {

    private EditText smsContent;
    private EditText smsNumber;
    private SmsReceiver smsReceiver;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 123) {
                Bundle bundle = msg.getData();
                smsContent.setText(bundle.getString("content"));
                smsNumber.setText(bundle.getString("number"));
                unregisterReceiver(smsReceiver);
            }
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive);
        initView();
    }

    private void initView() {
        smsContent = (EditText) findViewById(R.id.confirm_text);
        smsNumber = (EditText) findViewById(R.id.confirm_number);
        Button smsButton = (Button) findViewById(R.id.confirm_button);
        smsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPermission();
            }
        });
    }

    public void registerSmsReceiver() {
        IntentFilter receiverFilter = new IntentFilter();
        receiverFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        smsReceiver = new SmsReceiver(handler);
        registerReceiver(smsReceiver, receiverFilter);
    }

    private void getPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCALLPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS);
            // 判断是否具有权限
            if (checkCALLPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, 1);
                return;
            } else {
                registerSmsReceiver();
            }
        } else {
            registerSmsReceiver();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "获取权限成功", Toast.LENGTH_SHORT).show();
                    // 获取权限成功,发送短信
                    registerSmsReceiver();
                } else {
                    Toast.makeText(this, "获取权限失败", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

activity_receive.xml

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".receivemessage.ReceiveMessage">

    <EditText
        android:id="@+id/confirm_number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:hint="请输入电话号码"
        android:textSize="22sp" />

    <EditText
        android:id="@+id/confirm_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:hint="短信内容"
        android:textSize="22sp" />

    <Button
        android:id="@+id/confirm_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="获取短信验证码" />


</LinearLayout>

AndroidManifest.xml

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">


    <uses-feature
        android:name="android.hardware.telephony"
        android:required="true" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name_receive"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Learn">
        <activity
            android:name=".receivemessage.ReceiveMessage"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
相关推荐
叶落无痕5240 分钟前
关于安卓App自动化的一些想法
android·运维·自动化·android studio
miao_zz2 小时前
基于react native的锚点
android·react native·react.js
安卓美女2 小时前
Android自定义View性能优化
android·性能优化
Dingdangr3 小时前
Android中的四大组件
android
mg6685 小时前
安卓玩机工具-----无需root权限 卸载 禁用 删除当前机型app应用 ADB玩机工具
android
安卓机器5 小时前
Android架构组件:MVVM模式的实战应用与数据绑定技巧
android·架构
码龄3年 审核中5 小时前
MySQL record 05 part
android·数据库·mysql
服装学院的IT男5 小时前
【Android 13源码分析】WindowContainer窗口层级-1-初识窗口层级树
android
技术无疆6 小时前
Hutool:Java开发者的瑞士军刀
android·java·开发语言·ide·spring boot·gradle·intellij idea
qluka10 小时前
Android 应用安装-提交阶段
android