安卓intent接收短信
时间: 2024-10-24 12:02:24 浏览: 8
Android使用Intent发送短信的实现方法
在Android应用开发中,Intent是用于启动活动、传递数据以及请求系统功能的核心组件。如果想让应用程序接收短信,你可以通过注册BroadcastReceiver来监听`ACTION_NEW_SMS`这个系统广播。以下是步骤:
1. **在AndroidManifest.xml中声明权限和BroadcastReceiver**:
```xml
<uses-permission android:name="android.permission.READ_SMS" />
<receiver android:name=".SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
```
2. **创建BroadcastReceiver类**:
```java
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
Bundle bundle = intent.getExtras();
SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
// 处理接收到的短信数据
for (SmsMessage message : messages) {
String smsBody = message.getMessageBody();
handleSMS(smsBody);
}
}
}
private void handleSMS(String smsBody) {
// 这里编写处理接收到的短信的具体业务逻辑
}
}
```
3. **在需要的地方注册BroadcastReceiver**:
```java
registerReceiver(new SMSReceiver(), new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION));
```
4. **记得在不需要接收短信时解绑BroadcastReceiver**:
```java
unregisterReceiver(SMSReceiver);
```
阅读全文