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>
相关推荐
枯骨成佛35 分钟前
Android中Crash Debug技巧
android
kim56596 小时前
android studio 更改gradle版本方法(备忘)
android·ide·gradle·android studio
咸芝麻鱼6 小时前
Android Studio | 最新版本配置要求高,JDK运行环境不适配,导致无法启动App
android·ide·android studio
无所谓จุ๊บ6 小时前
Android Studio使用c++编写
android·c++
csucoderlee6 小时前
Android Studio的新界面New UI,怎么切换回老界面
android·ui·android studio
kim56597 小时前
各版本android studio下载地址
android·ide·android studio
饮啦冰美式7 小时前
Android Studio 将项目打包成apk文件
android·ide·android studio
夜色。7 小时前
Unity6 + Android Studio 开发环境搭建【备忘】
android·unity·android studio
ROCKY_8178 小时前
AndroidStudio-滚动视图ScrollView
android
趴菜小玩家9 小时前
使用 Gradle 插件优化 Flutter Android 插件开发中的 Flutter 依赖缺失问题
android·flutter·gradle