在Android平台上实现收发短信监听可以通过注册BroadcastReceiver来实现。以下是一个简单的示例代码:
- 在AndroidManifest.xml文件中添加权限声明:
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
- 创建一个BroadcastReceiver类来监听收到的短信:
public class SmsBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
String messageBody = smsMessage.getMessageBody();
String sender = smsMessage.getOriginatingAddress();
// 处理收到的短信
// 可以进行一些逻辑处理,比如发送短信到指定号码
}
}
}
}
}
- 在Activity或Service中注册BroadcastReceiver:
public class MainActivity extends AppCompatActivity {
private SmsBroadcastReceiver smsBroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smsBroadcastReceiver = new SmsBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsBroadcastReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsBroadcastReceiver);
}
}
通过以上步骤,你就可以在Android应用中实现收发短信监听的功能了。需要注意的是,Android 6.0及以上版本需要动态申请权限才能正常接收短信。
在Android平台上,要实现短信的收发监听,可以通过注册BroadcastReceiver来接收系统发出的短信相关广播。以下是一个简单的示例代码:
- 在AndroidManifest.xml中添加权限和注册BroadcastReceiver:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application
...
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
...
</application>
- 创建BroadcastReceiver类SmsReceiver.java并实现短信的收发监听逻辑:
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
String sender = message.getDisplayOriginatingAddress();
String messageBody = message.getMessageBody();
// 处理收到的短信
Log.d("SmsReceiver", "Received message from: " + sender + ", content: " + messageBody);
}
}
}
}
}
}
以上代码通过注册SmsReceiver广播接收器来监听系统发出的短信广播,并在onReceive方法中读取短信发送者和内容。注意要在AndroidManifest.xml中声明相应的权限并注册BroadcastReceiver,以确保应用可以正常接收短信。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/156521.html