Android 获取短信验证
输入发短信的手机号,点击获取验证码,等接收到验证码后就会自动获取
SmsReceiver.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
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
<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
<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>