无法使用PHP作为Backend获取通知

时间:2017-07-27 12:43:54

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

我是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\"}]}"

1 个答案:

答案 0 :(得分:0)

1)尝试输入优先级参数。



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




如果有效,请不要松散地使用它。您还可以创建一个函数来定义脚本中的优先级,以确定需要立即传递(高)的消息,而不是#34;当应用程序到达前台时,它可以等待处理数据。 (正常)。

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

有关详情,请参阅official sample。 现在在handleDataMessage中,它可能不是很长的运行过程,但处理可能仍需要10秒以上。最好的方法是进行性能分析,看看是否需要以更优化的方式安排某些事情或处理数据。

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

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

相关问题