短信验证码实例 android实验
时间: 2023-08-10 08:38:23 浏览: 143
好的,以下是一个简单的 Android 短信验证码实例:
1. 在 AndroidManifest.xml 文件中添加短信权限:
```xml
<uses-permission android:name="android.permission.RECEIVE_SMS" />
```
2. 创建一个广播接收器 SmsReceiver.java:
```java
public class SmsReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
if (SMS_RECEIVED_ACTION.equals(intent.getAction())) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null && pdus.length > 0) {
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
String messageBody = messages[0].getMessageBody();
// 在这里处理收到的短信验证码
}
}
}
}
}
```
3. 在你的 Activity 中注册 SmsReceiver:
```java
public class MainActivity extends AppCompatActivity {
private static final int SMS_REQUEST_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 请求短信权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, SMS_REQUEST_CODE);
}
// 注册 SmsReceiver
IntentFilter filter = new IntentFilter(SmsReceiver.SMS_RECEIVED_ACTION);
filter.setPriority(1000);
registerReceiver(new SmsReceiver(), filter);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == SMS_REQUEST_CODE && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 短信权限已经授权
}
}
}
```
4. 在你的服务器端发送短信验证码并等待用户输入,然后在收到短信验证码后,将验证码发送给你的应用程序。当应用程序接收到短信验证码时,可以在 SmsReceiver 中处理该验证码。
以上是一个简单的 Android 短信验证码实例,希望对你有帮助。
阅读全文