要在Android的狀態(tài)欄中顯示短信,你需要?jiǎng)?chuàng)建一個(gè)BroadcastReceiver來接收短信,并在接收到短信時(shí)將其顯示在狀態(tài)欄上。
下面是一個(gè)簡單的示例代碼:
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>
請(qǐng)注意,代碼中使用了NotificationCompat.Builder和NotificationManagerCompat來構(gòu)建和顯示通知。還需要在AndroidManifest.xml文件中聲明相關(guān)的通知渠道(channel)。
這樣,當(dāng)你的應(yīng)用接收到新的短信時(shí),它會(huì)顯示在狀態(tài)欄上作為通知。