1、极光推送流程图。

极光推送简单流程图

2、首先查看极光推送的文档,集成极光推送配置和库。

极光推送文档

极光推送安卓集成指南

3、 参考极光Demo创建自己的监听器并处理消息。

MyReceiver.java 具体过程是将极光推送接收到的自定义消息发送到Activity。

package com.peergine.demo.ext.renmulti;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

import static android.content.Context.ACTIVITY_SERVICE;
import static com.peergine.demo.ext.renmulti.MainActivity.isEmpty;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver,则:
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
	private static final String TAG = "JIGUANG-Example";
	private WindowManager wm = null;
	private View view = null;

	@Override
	public void onReceive(Context context, Intent intent) {
		try {
			Bundle bundle = intent.getExtras();
			Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

			if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
				String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
				Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
				//send the Registration Id to your server...

			} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
				Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
				processCustomMessage(context, bundle);

			} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
				Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
				int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
				Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);

			} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
				Log.d(TAG, "[MyReceiver] 用户点击打开了通知");

//				//打开自定义的Activity
//				Intent i = new Intent(context, TestActivity.class);
//				i.putExtras(bundle);
//				//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
//				context.startActivity(i);

			} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
				Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
				//在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等..

			} else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
				boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
				Log.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
			} else {
				Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
			}
		} catch (Exception e){

		}

	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			}else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
				if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
					Log.i(TAG, "This message has no Extra data");
					continue;
				}

				try {
					JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
					Iterator<String> it =  json.keys();

					while (it.hasNext()) {
						String myKey = it.next();
						sb.append("\nkey:" + key + ", value: [" +
								myKey + " - " +json.optString(myKey) + "]");
					}
				} catch (JSONException e) {
					Log.e(TAG, "Get message extra JSON error!");
				}

			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.get(key));
			}
		}
		return sb.toString();
	}
	
	//send msg to MainActivity
	private void processCustomMessage(Context context, Bundle bundle) {

        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String sAction = "";
        String DesID = "";
        String SrcID = "";
        String sParam = "";

        try {
            JSONObject msgJson = new JSONObject(message);
            sAction = msgJson.getString("Action");
            DesID = msgJson.getString("DesID");
            SrcID = msgJson.getString("SrcID");
            sParam = msgJson.getString("Param");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        MainActivity.sendMessageTo(context,sAction,DesID,SrcID,sParam);



	}

}

在Activity中添加下列代码接收并处理自定义消息。

 //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.peergine.demo.ext.renmulti.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String sAction = intent.getStringExtra("Action" );
                    String DesID = intent.getStringExtra("DesID" );
                    String SrcID = intent.getStringExtra("SrcID");
                    String sParam = intent.getStringExtra("Param");

                    if(MyJGPush.isSelection(sAction)){
                        StringBuilder showMsg = new StringBuilder();
                        showMsg.append(SrcID + " Selection");
                        popCostom(sAction,DesID,SrcID,sParam);
                    }

                }
            } catch (Exception e){
                Log.d("MessageReceiver","ex = " + e.toString());
            }
        }
    }

    private void popCostom(final String sAction, final String DesID, final String SrcID, final String sParam){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("show");
        builder.setMessage("sAction is " + sAction  + " sParam = " + sParam);

        builder.setPositiveButton("YES",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (findFragment(FragmentMain.class) == null) {
                    DatabaseHelper database = new DatabaseHelper(getApplicationContext());//这段代码放到Activity类中才用this

                    SQLiteDatabase db = database.getWritableDatabase();

                    String addr = "";
                    String id = "";
                    try {
                        Cursor c = db.query("config", null, null, null, null, null, null);//查询并获得游标
                        if (c.moveToFirst()) {//判断游标是否为空

                            c.move(c.getCount() - 1);//移动到指定记录
                            addr = c.getString(c.getColumnIndex("addr"));
                            id = c.getString(c.getColumnIndex("id"));
                            c.close();
                        }
                    }catch (Exception e){

                    }

                    if(MainActivity.isEmpty(addr)){
                        addr = "connect.peergine.com:7781";
                    }
                    if(!DesID.equals(id)){
                        return;
                    }
                    if(isEmpty(SrcID)){
                        return;
                    }

                    int iInit = getRender().isInit()?0:1;

                    loadRootFragment(R.id.fl_container, FragmentMain.newInstance(iInit,addr ,DesID , SrcID, "", 0, 1));
                }
            }
        } );
        builder.setNegativeButton("NO", null);
        builder.show();
    }

    public static int sendMessageTo(Context context,String sAction,String DesID, String SrcID, String sParam ){
        String sActivity = GetTopActivity(ExampleApplication.getInstance());


        if (sActivity.contains(MainActivity.class.getSimpleName())) {
            Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
            msgIntent.putExtra("Action", sAction);
            msgIntent.putExtra("DesID", DesID);
            msgIntent.putExtra("SrcID", SrcID);
            msgIntent.putExtra("Param", sParam);

            LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
        } else {
            Intent intent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            intent.setClass(context, MainActivity.class);
            intent.putExtra("Action", sAction);
            intent.putExtra("DesID", DesID);
            intent.putExtra("SrcID", SrcID);
            intent.putExtra("Param", sParam);
            ExampleApplication.getInstance().startActivity(intent);

        }
        return 0;
    }

4、利用服务器端发送极光推送。

推送分成两步:

一) 绑定ID等关键信息。

极光推送是安装到设备后会自动生成 RegistrationID,通过函数JPushInterface.getRegistrationID 获取。P2P有自己的ID,APP可能也有自己账号或者ID。为了能使极光推送可以准确的推送自定义消息到特定的设备。就需要将这样的关键信息和ID关联到一起。保存到数据库。

二)通过P2PID推送自定义消息到P2P设备。

客户端示例代码:

/**
 * 封装的极光推送+直播模块集成类
 */
public class MyJGPush {

    private pgLibLiveMultiCapture mCapLive = null;
    private pgLibLiveMultiRender mRndLive = null;
    private pgLibJNINode mNode = null;

    /**
     * 绑定采集端实例
     * @param mLive 采集端
     */
    public void AttachCapture(pgLibLiveMultiCapture mLive){
        mNode = mLive.GetNode();
        mCapLive = mLive;
        mRndLive = null;
    }

    /**
     * 绑定播放端实例
     * @param mLive 播放端
     */
    public void AttachRender(pgLibLiveMultiRender mLive){
        mNode = mLive.GetNode();
        mCapLive = null;
        mRndLive = mLive;
    }

    /**
     * P2P 本端ID 绑定极光推送设备ID
     * @param regID 极光推送设备注册ID
     * @return P2P错误码
     */
    public int JGPushAttach(String regID){
        if(isEmpty(regID)){
            System.out.println("regID empty");
            return 2;
        }
        String sData = "JGPushAttach?" + regID;
        int iErr = 0;
        if(mCapLive!=null){
            iErr = mCapLive.SvrRequest(sData, "JGPushAttach");
        }else if(mRndLive!=null){
            iErr = mRndLive.SvrRequest(sData, "JGPushAttach");
        }else{
            System.out.println("not Attach P2P Live");
            iErr = 2;
        }
        return iErr;
    }

    /**
     * 推送 Selection 信号到 DesID
     * @param DesID 推送目标ID
     * @param SrcID 推送源ID
     * @param sParam 自定义信息
     * @return P2P错误码
     */
    public int JGPushSelection(String DesID, String SrcID, String sParam){
        return JGPush("Selection",DesID,SrcID,sParam);
    }

    /**
     * 推送 Selection 信号到 DesID
     * @param DesID 推送目标ID
     * @param SrcID 推送源ID
     * @param sParam 自定义信息
     * @return P2P错误码
     */
    public int JGPushSelectionCancel(String DesID, String SrcID, String sParam){
        return JGPush("SelectionCancel",DesID,SrcID,sParam);
    }
    /**
     * 推送 Selection 信号到 DesID
     * @param sAction 信号名称
     * @param DesID 推送目标ID
     * @param SrcID 推送源ID
     * @param sParam 自定义信息
     * @return P2P错误码
     */
    public int JGPush( String sAction , String DesID, String SrcID, String sParam){
        JSONObject msgJson = new JSONObject();
        try {

            msgJson.put("Action",sAction);
            msgJson.put("SrcID",SrcID);
            msgJson.put("DesID",DesID);
            msgJson.put("Param",sParam);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        String sData = "JGPush?(User){" + mNode.omlEncode(DesID) + "}(Msg){" + mNode.omlEncode(msgJson.toString()) + "}";
        int iErr = 0;
        if(mCapLive!=null){
            iErr = mCapLive.SvrRequest(sData, sParam);
        }else if(mRndLive!=null){
            iErr = mRndLive.SvrRequest(sData, sParam);
        }else{
            iErr = 2;
        }

        return iErr;
    }
}

P2P服务器插件示例代码:

   ......
	public int PeerExtend(String sPeer, String sData, int iHandle) {

		// The sample code.
		int iInd = sData.indexOf('?');
		if (iInd <= 0) {
			return pgErrCode.PG_ERR_Normal;
		}

		// Check 'Forward' method.
		String sMeth = sData.substring(0, iInd);
		String sParam = sData.substring(iInd+1);

		//m_Proc.PeerNotify(sPeer, "UserExtend", ("Push: " + sData));
		//m_Proc.SetReplyData("Reply: " + sData);
		OutString("PeerExtend sMeth = " + sMeth);

		if ("Forward".equals(sMeth)) {
			return MethodForward(sPeer, sData, iHandle);
		}
		else if ("JGPush".equals(sMeth)){
			return JGPush(sPeer, sParam, iHandle);
		}
		else if ("JGPushAttach".equals(sMeth)){
			return JGPushAttach(sPeer, sParam, iHandle);
		}
		else{
			return pgErrCode.PG_ERR_Normal;
		}
	}
  ......

自定义推送示例代码:

......
private static PushPayload buildPushObject_android_cid(String registrationId, String sMsgConten,String cid) {
        if(isEmpty(registrationId)||isEmpty(sMsgConten)){
            return null;
        }
        Collection<String> list =new LinkedList<String>();
        list.add(registrationId);
        PushPayload.Builder builder = PushPayload.newBuilder();
        builder.setPlatform(Platform.android());
        builder.setAudience(Audience.registrationId(registrationId));
        builder.setMessage(Message.newBuilder()
                        .setMsgContent(sMsgConten)
                        //.addExtra("from", "JPush")
                        .build());
        if(!isEmpty(cid)){
            builder.setCid(cid);
        }
        return builder.build();
    }

    private static void SendPushWithCid(int APP, String registrationId, String sMsgConten,String cid) {
        //OutString("SendPushWithCid APP = " + APP + " registrationId = " + registrationId + " sMsgConten = "+ sMsgConten);
        JPushClient jPushClient = new JPushClient(MASTER_SECRET[APP], APP_KEY[APP]);
        //OutString("SendPushWithCid  MASTER_SECRET[APP]="+ MASTER_SECRET[APP] + " APP_KEY[APP] = " + APP_KEY[APP] );
        PushPayload pushPayload = buildPushObject_android_cid(registrationId, sMsgConten,cid);
        if(pushPayload == null){
            OutString("pushPayload = null");
            return;
        }
        try {

            PushResult result = jPushClient.sendPush(pushPayload);
            OutString("Got result - " + result);
        } catch (APIConnectionException e) {
            OutString("Connection error. Should retry later. "+ e.toString());
        } catch (APIRequestException e) {
            OutString("Error response from JPush server. Should review and fix it. " + e .toString());
            OutString("HTTP Status: " + e.getStatus());
            OutString("Error Code: " + e.getErrorCode());
            OutString("Error Message: " + e.getErrorMessage());
        }
    }
.......

 

 

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

16 − 10 =