【问题标题】:Couldn't get notification using PHP as Backend无法使用 PHP 作为后端收到通知
【发布时间】:2017-07-27 12:43:53
【问题描述】:

我是 Android 的新手,我创建了一个程序,该程序将使用 firebase 发送通知,而不使用 firebase 控制台。我使用 php 作为后端,我只有在通过 firebase 控制台发送时才会收到通知,但是当我通过 wamp 服务器发送它我不能。虽然我得到了成功:1.在这里我也分享我的代码和输出。

Index.php

    error_reporting(-1);
    ini_set('display_errors', 'On');

    require_once __DIR__ . '/firebase.php';
    require_once __DIR__ . '/push.php';

    $firebase = new Firebase();
    $push = new Push();

    // optional payload
    $payload = array();
    $payload['title'] = 'Notification!';
    $payload['message'] = 'New PickupListed';

    // notification title
    $title = isset($_GET['title']) ? $_GET['title'] : '';

    // notification message
    $message = isset($_GET['message']) ? $_GET['message'] : '';

    // push type - single user / topic
    $push_type = isset($_GET['push_type']) ? $_GET['push_type'] : '';

    // whether to include to image or not
    $include_image = isset($_GET['include_image']) ? TRUE : FALSE;


    $push->setTitle($title);
    $push->setMessage($message);

   if ($include_image) {
        $push->setImage('http://api.androidhive.info/images/minion.jpg');
    } else {
        $push->setImage('');
    }  

  $push->setIsBackground(FALSE);
   $push->setPayload($payload);

    $json = '';
    $response = '';

    if ($push_type == 'topic') {
        $json = $push->getPush();
        $response = $firebase->sendToTopic('global', $json);
    } else if ($push_type == 'individual') {
        $json = $push->getPush();
        $regId = isset($_GET['regId']) ? $_GET['regId'] : '';
        $response = $firebase->send($regId, $json);
    }

MessagingService.java

private NotificationUtils notificationUtils;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.e(TAG, "===========================messaging 1=======" );

    Log.e(TAG, "From: " + remoteMessage.getFrom());

   if (remoteMessage == null)
        return;

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.e(TAG, "===========================messaging 2=======" );
        Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
        handleNotification(remoteMessage.getNotification().getBody());
    }

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "===========================messaging 3=======" );
        Log.e(TAG, "Data Payload: " + remoteMessage.getData());

        try {
            JSONObject json = new JSONObject(remoteMessage.getData());
            handleDataMessage(json);
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
}

private void handleNotification(String message) {
    Log.e(TAG, "===========================messaging 4=======" );

    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {

        Intent intent= new Intent(this,MainActivity.class);
        intent.putExtra("message",message);
        intent.putExtra("imageUrl",imageUrl);
        intent.putExtra("time_stamp",timeStamp);

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

        final PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, intent, PendingIntent.FLAG_ONE_SHOT);


        Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("NOTIFICATION !!")
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(notificationSound)
                .setContentIntent(pendingIntent) ;

        NotificationManager notificationManager=
                ( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0,notifiBuilder.build());


        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);




    }
}

private void handleDataMessage(JSONObject json) {
    Log.e(TAG, "===========================messaging 4=======" );
    Log.e(TAG, "push json: " + json.toString());


    try {
        JSONObject data = json.getJSONObject("data");

        String title = data.getString("title");
        String message = data.getString("message");
       boolean isBackground = data.getBoolean("is_background");
        String imageUrl = data.getString("image");
       String timestamp = data.getString("timestamp");
    JSONObject payload = data.getJSONObject("payload");

        Log.e(TAG, "title: " + title);
        Log.e(TAG, "message: " + message);
       Log.e(TAG, "isBackground: " + isBackground);
       Log.e(TAG, "payload: " + payload.toString());
        Log.e(TAG, "imageUrl: " + imageUrl);
        Log.e(TAG, "timestamp: " + timestamp);


        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message

            Intent intent= new Intent(this,MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            final PendingIntent pendingIntent = PendingIntent.getActivity(
                    this, 0, intent, PendingIntent.FLAG_ONE_SHOT);



            Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("NOTIFICATION data message!!")
                    .setContentText(message)
                    .addAction(R.mipmap.ic_accept,"ACCEPT",pendingIntent)
                    .addAction(R.mipmap.ic_decline,"DECLINE",pendingIntent)
                    .setAutoCancel(true)
                    .setSound(notificationSound)
                    .setContentIntent(pendingIntent) ;

            NotificationManager notificationManager=
                    ( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0,notifiBuilder.build());


            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
           NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        } else {

            Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
            resultIntent.putExtra("message", message);

            // check for image attachment
            if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, resultIntent);
            } else {

                showNotificationMessageWithBigImage(getApplicationContext(), title, message, resultIntent, imageUrl);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}



private void showNotificationMessage(Context context, String title, String message, Intent intent) {
    Log.e(TAG, "===========================messaging 5=======" );
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, intent);
}

Ravi tamada tutorial

但我得到的是输出:仍然没有收到通知

Request:
{"data":{"title":"hey all","is_background":false,"message":"demo","image":"","timestamp":"2017-07-27 12:22:41"}}


Response:
"{\"multicast_id\":8934845196536440484,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1501158164597153%293f606ef9fd7ecd\"}]}"

【问题讨论】:

  • 我在您的示例负载中看不到目标。您是将其发送到单个设备还是主题?如果订阅某个主题,您确定设备订阅了该主题吗?
  • @AL。发送到单个设备并且无法创建它应该是目标的位置

标签: php android firebase push-notification firebase-cloud-messaging


【解决方案1】:

1) 尝试为优先级设置一个参数。

// optional payload
$payload = array();
$payload['title'] = 'Notification!';
$payload['message'] = 'New PickupListed';
$payload['priority'] = 'High';

请不要随意使用它,以防万一。您还可以创建一个函数,在脚本中为需要立即传递的消息(高)定义优先级,而不是“当应用程序进入前台时它可以等待处理数据”(正常)。

2) 您正在构建数据消息。 Android 上后台进程的处理方式发生了变化。您需要在收到消息后 10 秒内完成处理数据,否则可能无法执行。

请参阅official sample 了解更多信息。 现在在您的 handleDataMessage 中,它可能不是长时间运行的过程,但仍可能需要超过 10 秒的时间来处理。最好的办法是进行分析,看看您是否需要安排一些事情或以更优化的方式处理数据。

最佳实践:
- 数据消息只能用于将一些数据传递给客户端,这些数据对于更新应用程序数据、重置警报/计时器等至关重要。
- 如果您的音量/频率较高,则不应为每个请求使用高优先级,因为高优先级会唤醒睡眠设备以传递可能导致大量电池消耗的消息。您的用户可能会觉得该应用程序消耗了太多资源,并且可能会卸载或禁用通知。

PS:这篇文章并不是一个明确的答案,而只是建议,他们也有可能无法解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    相关资源
    最近更新 更多