Android中实现推送通知需要使用第三方库或者服务,比如Firebase Cloud Messaging(FCM),JPush等。以下是使用FCM实现推送通知的代码示例:
dependencies {
// ...
implementation 'com.google.firebase:firebase-messaging:22.0.0'
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMessagingService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// 获取通知数据
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
Map data = remoteMessage.getData();
// 处理通知
sendNotification(title, body, data);
}
private void sendNotification(String title, String body, Map data) {
// 构建通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default");
builder.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.mipmap.ic_launcher)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(getPendingIntent(data));
// 发送通知
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(0, builder.build());
}
private PendingIntent getPendingIntent(Map data) {
Intent intent = new Intent(this, MainActivity.class);
intent.setAction("OPEN_NOTIFICATION_ACTION");
for (String key : data.keySet()) {
intent.putExtra(key, data.get(key));
}
return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
上述代码中,使用MyFirebaseMessagingService类继