要在Android的状态栏中显示短信,你需要创建一个BroadcastReceiver来接收短信,并在接收到短信时将其显示在状态栏上。
下面是一个简单的示例代码:
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "SmsReceiver";
private static final int NOTIFICATION_ID = 1;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null && pdus.length > 0) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdus[0]);
String sender = sms.getDisplayOriginatingAddress();
String message = sms.getDisplayMessageBody();
showNotification(context, sender, message);
}
}
}
}
private void showNotification(Context context, String sender, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "channel_id")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(sender)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application>
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
请注意,代码中使用了NotificationCompat.Builder和NotificationManagerCompat来构建和显示通知。还需要在AndroidManifest.xml文件中声明相关的通知渠道(channel)。
这样,当你的应用接收到新的短信时,它会显示在状态栏上作为通知。