cocos2dx 本地推送

http://blog.sina.com.cn/s/blog_62f189570101bw5x.html 的基础上进行修改完善的。

由于项目的需求,需要将推送做到客户端。用的引擎是cocos2dx的。但是我看了下,大概思路还是安卓普遍都可以使用的。
大致思路就是建立一个service,然后在service中不断的去判断当前时间是否达到了指定时间,打到了指定时间就用安卓的notification进行推送。
首先在c++中定义一个Notification的管理类:
   
   
#ifndef __CCnotificationmanager_H__#define NM CCnotificationmanager::getnotificationmanager()#include "GlobalHead.h"class CCnotificationmanager{public: static* getnotificationmanager();void notification(constchar message, int delay repeats key);private(); m_pNotifiMgr;};#endif
void notification(const char * message,int delay,int repeats,const char * key); 的作用就是将需要的类容,时间等 发送到java那边进行存储。
key 这个字段可以不管,这是ios需要使用的,现在暂时不需要管。(我是在上面那个地址的内容上进行修改的,也可以单独区分ios 和 安卓的)
"CCnotificationmanager.h"#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)"CCNotificationHelper.h"#elif(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)"CCNotificationAndroid.h"#endifCCnotificationmanagerm_pNotifiMgr = NULL;"..\Player\FmLocalPlayer.h"CCnotificationmanager::CCnotificationmanager(){}CCnotificationmanager{ifNULL ) m_pNotifiMgr newreturn;}}notification){#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) // CNH->pushMessage(message,delay,repeats,key ); CNH->pushMessagemessage 0);long time GetLocalPlayer()->getCurrentTime java_push#endif}
iso的展示不需要去看。
间的获取是这样的:
Playerstruct tm time_t timep#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) time(&timep);#else cc_timeval Now CCTimegettimeofdayCocos2dNow timep Now.tv_sec#endif localtime timeSecond tmtm_sec +tm_min 60tm_hour 3600 timeSecond}
然后看java_push
__CCNOTIFICATION_ANDROID_H__"SDK/GlobalHead.h"#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)<jni.h>extern"C"externsrcint rep java_removePush();}#endif#endif
    
    
"Common.h""jni/JniHelper.h"<android/log.h><jni.h> delaytime JniMethodInfo t//LIbool ishave false JniHelpergetStaticmethodInfot"org/cocos2dx/bighero/BigHero""pushMessage""(Ljava/lang/String;II)V"ishave jstring messageStr env->NewStringUTF->CallStaticVoidMethodclassIDmethodID messageStrdelaytimerep->DeleteLocalRefmessageStr() minfo isHave minfo"removeNotification""()V"(!isHave cclOG("jni:此函数不存在"else}#endif
这里,本来是想着用直接把long类型的时间用jni传递到java里面直接使用,但是这样的话,前面的获取间的方法需要修改下。我这里的方法是直接传入delay的时间。(原谅我对Jni 和java 不熟悉)
然后是java 部分:
在主activity中实现:
public pushMessage(Stringint// System.out.println("alpaca.passFromJni()"+mark); NotificationMessage nmObj NotificationMessage String[] ss split"#" nmObjsetMessagess[]);setTitle1 curtime SystemcurrentTimeMillissetMarkcurtime convertsetIdrepeats BigHero.SerializeMethodnmObj}
我这里的message 传入的是安卓Notification 需要用到的title 和 info,我用title#info 传入。

  
  
SerializeMethod(NotificationMessage Intent intent Intent intentsetClassbighero NotifitionService.class Bundle mBundle Bundle mBundleputSerializableSER_KEYputExtrasmBundle// addFlags(IntentFLAG_ACTIVITY_NEW_TASK bigherostartServiceintent}
这里就是开启我们的推送服务
存储数据的类:
implements Serializableprivatefinal serialVersionUID -7060210544600464481L mark id title getMessage getTitle setTitle){thistitle setMessagemessage getMark setMarkmark getId setIdid super}
然后看推送的service
NotifitionServiceextends Service List<NotificationMessage> mMessageList ArrayList>(); mMessage "" mTitle @Override IBinder onBind(Intent// Todo Auto-generated method stubnull onStartCommand flags startIdonStartCommand onCreateonCreate Timer timer Timertrue timerschedule javautil.TimerTask(){ runcheckPauseState())ifisAppOnForeground showNotification},11000 onStartonStartintent != notimessage (NotificationMessagegetSerializableExtra(BigHero notimessagegetMark mMessageListaddnotimessageboolean checkPauseStateoutprintln"NotifitionService=========="curtimemMessageListsize listsize for i < listsize i++)geti).*1000&&-getMessagegetTitleremove Notification notification Notificationicon Rdrawableic_launchertickerText mMessagewhen defaults DEFAULT_SOUNDflags |=FLAG_AUTO_CANCELACTION_MAINsetClassName"org.cocos2dx.bighero.BigHero"addCategoryCATEGORY_LAUNCHERsetFlagsFLAG_ACTIVITY_NEW_TASK |FLAG_ACTIVITY_RESET_TASK_IF_NEEDED PendingIntent pintent PendingIntentgetActivity(NotifitionServicesetLatestEventInfomTitlemMessagepintent service ContextNOTIFICATION_SERVICE notificationmanager mnotificationmanager =(notificationmanagergetSystemServiceservice mnotificationmanagernotifyRstringapp_name PushThread Runnable"CCNotifitionService.PushThread.run()"());whiletry Threadsleep(catch(InterruptedException e// Todo: handle exceptionprintstacktrace/** * 程序是否在前台运行 * * @return */ isAppOnForeground// Returns a list of application processes that are running on the // device ActivityManager activityManager (ActivityManager getApplicationContext().(ContextACTIVITY_SERVICE packageName getPackageName<RunningAppProcessInfo appProcesses activityManager getRunningAppProcessesappProcesses (RunningAppProcessInfo appProcess appProcesses// The name of the process that this object is associated with. appProcessprocessNameequalspackageName appProcessimportance RunningAppProcessInfoIMPORTANCE_FOREGROUND}
更多的可以去看看Notification的实现
最后是AndroidManifest 中添加服务
<service android:name="NotifitionService"
android:process=":system" >
</service>
请注意,这里的提升进程的级别是:system 而不是system ,网上一堆的system 把我害惨了。。。。。

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...