在使用SmsManager发送短信时,需要添加发送短信权限,并使用兼容Android 12的方式发送短信。具体实现示例:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { // Android 12及以上版本 PendingIntent intent = PendingIntent.getBroadcast(context, /* 请求码 */1, new Intent(), 0); SmsManager.getSmsManagerForSubscriptionId(subscriptionId) .sendTextMessage(destinationAddress, serviceCenterAddress, text, intent, null); } else { // Android 12以下版本 SmsManager.getDefault().sendTextMessage(destinationAddress, serviceCenterAddress, text, null, null); }
其中,subscriptionId是SIM卡使用的订阅ID,destinationAddress是目标号码,serviceCenterAddress是服务中心号码,text是要发送的短信内容。在Android 12及以上版本中,使用getSmsManagerForSubscriptionId方法获得SmsManager对象,并将 PendingIntent 作为参数传递给 sendTextMessage 方法,来实现发送短信。