cocos2dx 消息推送

前端之家收集整理的这篇文章主要介绍了cocos2dx 消息推送前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

用coocs2dx引擎开发游戏,消息推送通知是很有必要的。android端实现

首先是一个消息管理者:
CCNotificationManager.h

#ifndef __CCNOTIFICATION_MANAGER_H__
#define __CCNOTIFICATION_MANAGER_H__
#define NM CCNotificationManager::getNotificationManager()
#include "GlobalHead.h"
class CCNotificationManager
{
public:
    static CCNotificationManager* getNotificationManager();
    void notification(const char * message,long delay,int repeats,const char * key);
private:
    CCNotificationManager();
private:
    staticCCNotificationManager* m_pNotifiMgr;
};

CCNotificationManager.cpp

#include "CCNotificationManager.h"
#include "CCTimeHelper.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "CCNotificationHelper.h"
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "CCNotificationAndroid.h"
#endif
CCNotificationManager* CCNotificationManager::m_pNotifiMgr = NULL;

CCNotificationManager::CCNotificationManager()
{

}

CCNotificationManager* CCNotificationManager::getNotificationManager()
{
    if (NULL == m_pNotifiMgr)
    {
        m_pNotifiMgr = newCCNotificationManager();
        returnm_pNotifiMgr;
    }
    returnm_pNotifiMgr;
}

void CCNotificationManager::notification(const char * message,const char * key)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
// CNH->pushMessage(message,delay,repeats,key );
    CNH->pushMessage(message,0,key );
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    java_push(message,delay + GTH->getCurrentTime(),repeats);
#endif
}
#endif 

**

android下的实现

**
CCNotificationAndroid.h

#ifndef __CCNOTIFICATION_ANDROID_H__
#define __CCNOTIFICATION_ANDROID_H__
#include "GlobalHead.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include 
extern"C"
{
    extern void java_push(string message,long mark,int repeats);
    extern void java_removePush();
}
#endif
#endif

调用android端

#include "CCNotificationAndroid.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "jni/JniHelper.h"
#include 
#include 
extern"C"
{
    void java_push(string message,long mark,int repeats)
    {
        JniMethodInfo t;
        //LI
        if (JniHelper::getStaticMethodInfo(t,"com/ea/product/DAoTest/DAoTest","pushMessage","(Ljava/lang/String;JI)V"))
        {
            jstring messageStr = t.env->NewStringUTF(message.c_str());
            t.env->CallStaticVoidMethod(t.classID,t.methodID,messageStr,mark,repeats);
            t.env->DeleteLocalRef(messageStr);
        }
    }

    void java_removePush()
    {
        JniMethodInfo minfo;
        bool isHave = JniHelper::getStaticMethodInfo(minfo,"removeNotification","()V");
        if (!isHave)
        {
            CCLOG("jni:此函数不存在");
        }
        else
        {
            minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
        }
    }
}
#endif

然后切换到pro.android

public class DAoTest extends Cocos2dxActivity {
public  finalstaticint  convert = 1000;
public  finalstatic String SER_KEY = "com.ea.product.DAoTest.message";
publicstatic DAoTest mDAoTestObj;

protected void onCreate(Bundle savedInstanceState) {
Log.e("com.ea.product.DAoTest","onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mDAoTestObj = this;
} 

public Cocos2dxGLSurfaceView onCreateView() {
    Log.e("com.ea.product.DAoTest","onCreateView");
    Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
    // DAoTest should create stencil buffer

    glSurfaceView.setEGLConfigChooser(5,6,5,16,8);
    return glSurfaceView;
}

@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data) {

    super.onActivityResult(requestCode,resultCode,data);
}

//Serializeable传递对象的方法 

public void SerializeMethod(NotificationMessage message) {
    Intent intent = new Intent();
    intent.setClass(DAoTest.this,CCNotifitionService.class);
    Bundle mBundle = new Bundle();
    mBundle.putSerializable(SER_KEY,message);
    intent.putExtras(mBundle);
    DAoTest.this.startService(intent);
    System.out.println("Push notify message.");
}

public static void pushMessage(String message,int repeats) {
    System.out.println("DAoTest.passFromJni()"+mark);
    NotificationMessage nmObj = new NotificationMessage();
    nmObj.setMessage(message);
    nmObj.setMark(mark * convert);
    nmObj.setId(repeats);
    mDAoTestObj.SerializeMethod(nmObj);
}

public void onStop() {
    super.onStop();
}

public void onDestroy() {
    super.onDestroy();
}

public DAoTest() {

}

static {
    System.loadLibrary("DAoTest");
}
}

实例

package com.ea.product.DAoTest;
import java.io.Serializable;
public class NotificationMessage implements Serializable{
    private static final long serialVersionUID = -7060210544600464481L;   

private String message;

privatelong   mark;

privateint    id;

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

public long getMark() {

return mark;

}

public void setMark(long mark) {

this.mark = mark;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public NotificationMessage(String message,int id) {

super();

this.message = message;

this.mark = mark;

this.id = id;

}



public NotificationMessage() {
}
}

**

最后在service中做逻辑处理(启动一个定时器到时间就推送)

**

package com.ea.product.DAoTest;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

import com.ea.product.DAoTest.DAoTest;
import android.app.NotificationManager;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;


public class CCNotifitionService extends Service {

static List mMessageList = new ArrayList(); 

String mmessage = "" ;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

public CCNotifitionService(){
System.out.println("CCNotifitionService.CCNotifitionService()");
}

@Override
public void onCreate()
{
System.out.println("onCreate()"+mMessageList.size());
super.onCreate();

Timer timer = new Timer(true);
timer.schedule(
new java.util.TimerTask() 
{ 
public void run() {

if(checkPushStatue())
{
showNotification();
}
} 
},1*1000); 
}

@Override
public void onStart(Intent intent,int startId)
{
if((intent!=null) )
{
NotificationMessage message = (NotificationMessage)intent.getSerializableExtra(DAoTest.SER_KEY); 
mMessageList.add(message);
}
}

@Override
public void onDestroy() {

super.onDestroy();
}

public CCNotifitionService(Context context){

}

public boolean checkPushStatue(){

long currentTime = System.currentTimeMillis();

if(mMessageList.size()>0)
{
int listSize = mMessageList.size();

for(int i = 0 ;i

if(mMessageList.get(i).getMark() < currentTime)
{
mmessage = mMessageList.get(i).getMessage();
mMessageList.remove(i);
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
return false;
}

public void showNotification()
{

Notification notification = new Notification(R.drawable.icon,mmessage,System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_SOUND;

Intent it = new Intent(Intent.ACTION_MAIN);
it.setClassName(this,"com.ea.product.DAoTest.DAoTest");
it.addCategory(Intent.CATEGORY_LAUNCHER);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

PendingIntent pintent = PendingIntent.getActivity(CCNotifitionService.this,it,0);
notification.setLatestEventInfo(CCNotifitionService.this,"",pintent);

String service = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager =(NotificationManager)getSystemService(service);
mNotificationManager.notify(R.string.app_name,notification);
}

public class PushThread implements Runnable {
public void run() {
System.out.println("CCNotifitionService.PushThread.run()"+mMessageList.size());

while(true)
{
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

if(checkPushStatue())
{
showNotification();
}
}
}
}

}

最后千万不能忘了在配置文件中加入这个service的属性

独立进程
无论程序是否正在运行,我们都要能通知到客户,我们需要一个独立进程的后台服务。 我们需要一个独立进程的后台服务。
在androidmanifest.xml中注册service时,有一个android:process属性,如果这个属性以”.”开头,则为此服务开启一个
全局的独立进程,如果以”:”开头则为此服务开启一个为此应用私有的独立进程。 这样就可以在用户退出后,开启一个新的进程来处理逻辑(判断满足条件推送)

 <serviceandroid:enabled="true"android:name=".CCNotifitionService" android:process=":message" />
原文链接:https://www.f2er.com/cocos2dx/340601.html

猜你在找的Cocos2d-x相关文章