要在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)。
這樣,當你的應用接收到新的短信時,它會顯示在狀態欄上作為通知。