wjc
20 小时以前 2f5411b86c59706d31f6ec7de629d8f860725e46
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
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));
        Log.d(TAG, "来自: " + remoteMessage.getFrom());
 
 
//        // 数据消息:任何状态都会执行
//        if (!remoteMessage.getData().isEmpty()) {
//            handleDataMessage(remoteMessage.getData()); // 总是执行
//        }
//
//        // 通知消息:只有前台时才会执行
//        if (remoteMessage.getNotification() != null) {
//            handleNotification(remoteMessage.getNotification()); // 只有前台执行
//        }
 
        if (isAppInForeground(this)) {
            // 检查消息是否包含数据负载
            if (!remoteMessage.getData().isEmpty()) {
                PushMessageInfoBean pushMessageInfoBean = HdlPushLogic.getInstance().pushDataProcessing("", "", JSON.toJSONString(remoteMessage.getData()));
                HdlPushLogic.getInstance().PushPushCommonData(this, pushMessageInfoBean, false);
//            Log.d(TAG, "消息数据: " + remoteMessage.getData());
//            handleDataMessage(remoteMessage.getData());
            }
        } else {
            // 检查消息是否包含通知负载
            if (!remoteMessage.getData().isEmpty()) {
                PushMessageInfoBean pushMessageInfoBean = HdlPushLogic.getInstance().pushDataProcessing("", "", 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.desktop_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);
 
        // 显示通知
        notificationManager.notify((int) System.currentTimeMillis(), builder.build());
    }
 
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel(NotificationManager notificationManager) {
        NotificationChannel channel = new NotificationChannel(
                "fcm_channel",
                "FCM 消息",
                NotificationManager.IMPORTANCE_HIGH
        );
        channel.setDescription("Firebase Cloud Messaging 通知");
        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;
        }
        UserConfigManage.getInstance().setPushToken(token);
        UserConfigManage.getInstance().Save();
        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<ActivityManager.RunningAppProcessInfo> 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;
        }
    }
}