安卓接收消息通知并显示消息弹窗怎么写
时间: 2024-02-04 16:04:16 浏览: 24
你可以使用Android的Notification类来实现接收通知显示消息弹窗,具体步骤如下:
1.创建消息通知
```
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Notification Title")
.setContentText("Notification Text")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true);
```
2.发送通知
```
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(notificationId, builder.build());
```
3.在AndroidManifest.xml文件中添加通知渠道
```
<application ...>
...
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id"/>
...
</application>
```
4.在Activity中实现接收通知
```
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check if message contains a notification payload.
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey("google.message_id")) {
String notificationTitle = getIntent().getStringExtra("gcm.notification.title");
String notificationBody = getIntent().getStringExtra("gcm.notification.body");
// Create notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(notificationTitle)
.setContentText(notificationBody)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true);
// Show notification
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());
}
}
}
```
以上就是安卓接收消息通知并显示消息弹窗的基本实现步骤,你可以根据自己的需求进行修改和优化。