你好,我有一个android应用程序,我使用了Firebase通知,它的工作正常,现在我需要接收无提示的无声推送,或者,当应用程序在运行时,我尝试了一些想法,并且它在后台运行,或者在后台运行时终止了工作!如果有人有想法解决这个问题,请告诉我:)这是我的代码

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    Boolean isSilent;
    String Silent = "";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        try {
            Bundle bundle = new Bundle();
            for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) {
                bundle.putString(entry.getKey(), entry.getValue());
                Log.d(entry.getKey(), entry.getValue());
            }
//            remoteMessage.getData().get("screen_id")
            if (remoteMessage.getData().size() > 0) {
                sendNotificationData(bundle.getString("data_title"), bundle.getString("data_body"), bundle.getString("screen_id"));

            } else if (remoteMessage.getNotification() != null) {
                sendNotification(remoteMessage.getNotification(), bundle.getString("screen_id"));
            }


        } catch (Exception ex) {
            ex.printStackTrace();

        }
    }

    private void sendNotification(RemoteMessage.Notification notificationR, String screenId) {
        NotificationManager nManager = (NotificationManager) this.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intentNotification = new Intent(this, MainActivity.class);
        intentNotification.putExtra("screen_id", screenId);
        Log.v("sendNotification ", " >>>>>####>>>>>>>>  " + screenId);
        // finish previous activity
        if (!Silent.equals("yes")) {
            intentNotification.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intentNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 50, intentNotification, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this.getApplicationContext())
                    .setContentTitle(notificationR.getTitle())
                    .setContentText(notificationR.getBody())
                    .setSmallIcon(getNotificationIcon())
                    .setLargeIcon(icon(getApplicationContext()))
                    .setLights(Color.LTGRAY, 1000, 1000)
                    .setAutoCancel(true)
                    .setTicker(notificationR.getTitle())
                    .setContentIntent(pendingIntent)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));


            Notification notification = notificationBuilder.build();
            //  '|' Binary OR Operator copies a bit if it exists in either operand. to ensure no conflict on the flags
            notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;

            nManager.notify((int) SystemClock.currentThreadTimeMillis(), notification);

        }
    }


    private void sendNotificationData(String dataTitle, String dataBody, String screenId) {
        NotificationManager nManager = (NotificationManager) this.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intentNotification = new Intent(this, MainActivity.class);
        intentNotification.putExtra("screen_id", screenId);


        if (!Silent.equals("yes")) {
            intentNotification.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intentNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 50, intentNotification, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this.getApplicationContext())
                    .setContentTitle(dataTitle)
                    .setContentText(dataBody)
                    .setSmallIcon(getNotificationIcon())
                    .setLargeIcon(icon(getApplicationContext()))
                    .setLights(Color.LTGRAY, 1000, 1000)
                    .setAutoCancel(true)
                    .setTicker(dataTitle)
                    .setContentIntent(pendingIntent)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

            Notification notification = notificationBuilder.build();
            //  '|' Binary OR Operator copies a bit if it exists in either operand. to ensure no conflict on the flags
            notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;

            nManager.notify((int) SystemClock.currentThreadTimeMillis(), notification);
        }
       @Override
        public boolean zzE(Intent intent) {
            isSilent = intent.hasExtra("silent");
            if (isSilent) {
                Silent = "yes";
            }
            return super.zzE(intent);
        }


当应用程序正在运行时,此代码正在运行,但在后台或终止时无法运行!

最佳答案

当您的应用程序处于后台时,在“系统任务栏”上收到firbase通知消息,这就是为什么不调用FirebaseMessagingService.onMessageReceived的原因。


  当您的应用程序在后台运行时,Android会将通知消息定向到系统任务栏。默认情况下,用户点击通知会打开应用启动器。


尝试发送将调用onMessageReceived的数据有效负载。然后您的代码将
 工作
对于数据消息...。
从FirebaseInstanceIdService获取firebase令牌,并将其发送到应用服务器。
Google有很好的文档发送给它Here

您也可以使用php发送。

然后在onMessageReceived

if (remoteMessage.getData().size() > 0) {
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");
        String screen = remoteMessage.getData().get("screen");

        sendNotification(title, body, screen );}


对于服务器端php实现

    <?php
$path_to_fcm = "https://fcm.googleapis.com/fcm/send";
$headers = array(
    'Authorization:key='YOUR_SERVER_KEY,
    'Content-Type:application/json'
);

$reg_id_array = array
(
    'token1',
    'token2'
)

$mesg = array
(
    'title'=>$_POST['title'],
    'body'=> $_POST['message'],
    'url'=>$_POST['Screen'],

);

$fields = array("registration_ids"=>$reg_id_array, 'data'=>$mesg);


$payload = json_encode($fields);
$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);

$Qresult = curl_exec($curl_session);
$httpcode = curl_getinfo($curl_session , CURLINFO_HTTP_CODE);
curl_close($curl_session);
if ($httpcode==200) {
    echo "Success";
}
?>


对不起英语不好

07-24 09:36
查看更多