package com.hdl.photovoltaic.push.fcm; import android.app.ActivityManager; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.text.TextUtils; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import com.hdl.photovoltaic.R; import com.hdl.photovoltaic.config.ConstantManage; import com.hdl.photovoltaic.config.UserConfigManage; import com.hdl.photovoltaic.enums.MessageStateType; import com.hdl.photovoltaic.other.HdlPushLogic; import com.hdl.photovoltaic.push.PushMessageInfoBean; import com.hdl.photovoltaic.ui.BPowerStationActivity; import com.hdl.photovoltaic.ui.StartActivity; import com.hdl.sdk.link.core.bean.eventbus.BaseEventBus; import org.greenrobot.eventbus.EventBus; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import cn.jpush.android.api.NotificationMessage; public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "FCMService"; /** * 当收到新的 FCM Token 时调用 */ @Override public void onNewToken(@NonNull String token) { Log.d(TAG, "刷新 FCM Token: " + token); // 将 token 发送到您的服务器 sendRegistrationToServer(token); } /** * 当收到消息时调用 */ @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.d(TAG, "在前台还是在后" + isAppInForeground(this)); Log.d(TAG, "来自RemoteMessage: " + JSON.toJSONString(remoteMessage)); // // 数据消息:任何状态都会执行 // if (!remoteMessage.getData().isEmpty()) { // handleDataMessage(remoteMessage.getData()); // 总是执行 // } // // // 通知消息:只有前台时才会执行 // if (remoteMessage.getNotification() != null) { // handleNotification(remoteMessage.getNotification()); // 只有前台执行 // } String title = "";//推送标题 String content = "";//推送内容 if (remoteMessage.getNotification() != null) { title = remoteMessage.getNotification().getTitle(); content = remoteMessage.getNotification().getBody(); } if (isAppInForeground(this)) { // 检查消息是否包含数据负载 if (!remoteMessage.getData().isEmpty()) { PushMessageInfoBean pushMessageInfoBean = HdlPushLogic.getInstance().pushDataProcessing(title, content, JSON.toJSONString(remoteMessage.getData())); HdlPushLogic.getInstance().PushPushCommonData(this, pushMessageInfoBean, false); // handleDataMessage(remoteMessage.getData()); } } else { // 检查消息是否包含通知负载 if (!remoteMessage.getData().isEmpty()) { PushMessageInfoBean pushMessageInfoBean = HdlPushLogic.getInstance().pushDataProcessing(title, content, JSON.toJSONString(remoteMessage.getData())); this.showCustomNotification(pushMessageInfoBean); } } } /** * 处理通知消息(应用在后台时,系统会自动显示通知) * * @param pushMessageInfoBean */ private void showCustomNotification(PushMessageInfoBean pushMessageInfoBean) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // 创建通知渠道(Android 8.0+) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createNotificationChannel(notificationManager); } // 构建通知内容 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "fcm_channel") .setSmallIcon(R.drawable.notification_logo) .setContentTitle(pushMessageInfoBean.getTitle()) .setContentText(pushMessageInfoBean.getContent()) .setAutoCancel(true) .setWhen(System.currentTimeMillis()); // 设置点击意图,为通知添加点击后的跳转意图 Intent intent = createNotificationIntent(pushMessageInfoBean.getExpandData()); PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); builder.setContentIntent(pendingIntent); // 发送通知,通知栏显示通知 int notificationId = (int) System.currentTimeMillis(); // 每个通知的唯一ID notificationManager.notify(notificationId, builder.build()); } @RequiresApi(api = Build.VERSION_CODES.O) private void createNotificationChannel(NotificationManager notificationManager) { NotificationChannel channel = new NotificationChannel( "fcm_channel", "FCM Message", NotificationManager.IMPORTANCE_HIGH ); channel.setDescription("Firebase Cloud Messaging Notification"); notificationManager.createNotificationChannel(channel); } private Intent createNotificationIntent(String data) { Intent intent = new Intent(this, StartActivity.class); intent.putExtra("from_fcm", true); intent.putExtra("pushData", data); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } private void sendRegistrationToServer(String token) { // 将 FCM Token 发送到您的服务器 // 可以使用 Retrofit、Volley 等网络库 Log.d(TAG, "发送 Token 到服务器: " + token); if (TextUtils.isEmpty(token)) { return; } BaseEventBus bus = new BaseEventBus(); bus.setTopic(ConstantManage.refresh_push_token); bus.setType(token); EventBus.getDefault().post(bus); // // 示例:使用 SharedPreferences 存储 token // SharedPreferences prefs = getSharedPreferences("fcm_prefs", MODE_PRIVATE); // prefs.edit().putString("fcm_token", token).apply(); } /** * 应用是否在前台 * * @param context 上下 * @return true表示在前台,false在后台 */ private static boolean isAppInForeground(Context context) { try { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List appProcesses = activityManager.getRunningAppProcesses(); if (appProcesses == null) { return false; } final String packageName = context.getPackageName(); for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) { return true; } } return false; } catch (Exception e) { return false; } } }