操作 GCM 下游消息

Posted

技术标签:

【中文标题】操作 GCM 下游消息【英文标题】:Manipulating a GCM downstream message 【发布时间】:2016-03-14 06:13:30 【问题描述】:

我正在创建一个使用 GCM 的 android 应用程序。我已经为双向功能实现了 XMPP CCS 应用服务器。到目前为止,上游消息传递工作完美 - 设备注册自己,获取令牌 ID,并将相关数据发送到应用程序服务器。 App server 还可以解析传入的上游消息并将其保存在数据库中。我还为一组令牌创建了 notification_key,即使这样也可以正常工作。

下游消息传递也运行良好。我收到来自 GCM 的消息。但是,在打开通知时,我想打开一个 Activity,它根据服务器的输出计算某些位置,并在谷歌地图上显示输出位置。我怎么做?我试图在onMessageReceived 函数中创建一个 IntentService,但它不起作用。

MyGcmListenerService

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.gcm.GcmListenerService;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.StringTokenizer;



public class MyGcmListenerService extends GcmListenerService 


    public LatLng midpoint;
    public double lat;
    public double lng;
    public String location;
    public PlacePicker placePicker;
    public final int PLACE_PICKER_REQUEST = 1;
    public GoogleMap map;
    public final String SERVER_KEY = "MY_GCM_SERVER_KEY";
    public double curr_lat;
    public double curr_long;




    @Override
    public void onMessageReceived(String from, Bundle data) 

        String type = data.getString("type");

        //If broadcast,
        if("meetup.be2015.gcm_meetup.BROADCAST".equals(type))
            //Issue request to the Google Directions and places API

            //extract latitude & longitude
            String latitude_str = data.getString("latitude");
            String longitude_str = data.getString("longitude");

             this.lat = Double.parseDouble(latitude_str);
             this.lng = Double.parseDouble(longitude_str);

            String dest_msg = "Destination:: "+lat+", "+lng;

            sendNotification(dest_msg, "BROADCAST");

            //Launch an intenservice to handle the JSON data

            Intent DirectionIntent = new Intent(getApplicationContext(), Directions.class);
            DirectionIntent.putExtra("current_lat",curr_lat);
            DirectionIntent.putExtra("current_long",curr_long);
            DirectionIntent.putExtra("target_lat",lat);
            DirectionIntent.putExtra("target_long", lng);
            startService(DirectionIntent); // <- HOW DO I GET THIS TO WORK?

        

        else if("meetup.be2015.gcm_meetup.UNICAST".equals(type)) 

            /*
            *   Message format of packet sent from Server:
            *
            *   payload.put("Message", midString);
                payload.put("type", "meetup.be2015.gcm_meetup.UNICAST");
                payload.put("notification_key", not_key);
                payload.put("Embedded_MsgID", msgID);
            *
            * */

            Log.d("RECV_MSG","Received message from "+from+". MsgId:"+data.getString("Embedded_MsgID"));

            //Create Double array
            ArrayList<String> temp = new ArrayList<>();

            String pos = data.getString("Message");

            //Format to be the LatLng:
            //"latitude: XYZ :: longitude: ABC"

            String notification_key = data.getString("notification_key");

            //Passing through StringTokenizer
            StringTokenizer tokenizer = new StringTokenizer(pos);
            while (tokenizer.hasMoreTokens()) 
                temp.add(tokenizer.nextToken());
            

            //Create the LatLng point
            midpoint = new LatLng(Double.parseDouble(temp.get(1)), Double.parseDouble(temp.get(4)));

            //Set initial radius (m)
            double radius = 500;

            //Use a function to map SE and NW bounds of circle
            //LatLngBounds bounds = convertCenterAndRadiusToBounds(midpoint, radius);

            //pack everything in an intent and send to Places.java
            Intent placeIntent = new Intent(getApplicationContext(), Places.class);
            placeIntent.putExtra("midpoint", midpoint);
            placeIntent.putExtra("radius", radius);
            placeIntent.putExtra("notification_key", notification_key);
            startService(placeIntent); // <- THIS AS WELL

            sendNotification(pos, "MIDPOINT");
        
    

    //THIS FUNCTION WORKS PROPERLY. SENDS ME THE NOTIFICATION
    public void sendNotification(String message, String type) 
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("GCM MESSAGE: " + type)
                .setContentText(message)
                .setSmallIcon(R.drawable.ic_mail_black_24dp)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

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

【问题讨论】:

【参考方案1】:

在发送通知时,像这样在意图中添加一些数据

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("midpoint", midpoint);
intent.putExtra("radius", radius);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_ONE_SHOT);

然后在你的 mainActivity 类中实现下面的方法

@Override
protected void onNewIntent(Intent intent) 
    super.onNewIntent(intent);
    if (intent.hasExtra("radius")) 

        midpoint = intent.getStringExtra("midpoint");
        radius = intent.getStringExtra("radius");
        // do what ever you want with this data.
    

如果上述方法不起作用,也尝试像这样检查 onCreate 中的意图数据。

if (intent.hasExtra("radius")) 

   midpoint = intent.getStringExtra("midpoint");
   radius = intent.getStringExtra("radius");
   // do what ever you want with this data.

希望对你有帮助。

【讨论】:

以上是关于操作 GCM 下游消息的主要内容,如果未能解决你的问题,请参考以下文章

识别上游 GCM 消息的发送者

适用于 iOS 的 GCM 下游消息传递 JSON 格式

使用 XMPP 关闭 GCM 连接服务器的套接字

带有PHP的Android中的高优先级GCM消息?

GCM 如何使用 BroadCastReceiver 处理应用程序

GCM / FCM / Mozilla (Web Push Service) 使用统计