后台推送

来源:互联网 发布:tv远程控制软件 编辑:程序博客网 时间:2024/06/04 19:41

void PushNotificationIOS::addNoticfy(std::string title,std::string content,unsignedint delalt,std::string key,unsignedint repeatTime)

{

    

    // 创建一个本地推送//

    UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];

    //设置delalt秒之后//

    NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:delalt];

    if (notification != nil)

    {

        // 设置推送时间//

        notification.fireDate = pushDate;

        // 设置时区//

        notification.timeZone = [NSTimeZone defaultTimeZone];

        // 设置重复间隔//

        if (repeatTime!=0)

        {

            notification.repeatInterval = kCFCalendarUnitDay;

        }

        else

        {

            notification.repeatInterval = 0;

        }

        // 推送声音//

        notification.soundName = UILocalNotificationDefaultSoundName;

        // 推送内容//

        notification.alertBody = [NSString stringWithUTF8String: content.c_str()];

        //显示在icon上的红色圈中的数子//

        notification.applicationIconBadgeNumber = 1;

        //设置userinfo 方便在之后需要撤销的时候使用//

        NSDictionary *info = [NSDictionary dictionaryWithObject:[NSString stringWithUTF8String: key.c_str()] forKey:@"DDNoticfykey"];

        notification.userInfo = info;

        //添加推送到UIApplication//

        UIApplication *app = [UIApplication sharedApplication];

        [app scheduleLocalNotification:notification];

        

    }


}


删除一条推送


void PushNotificationIOS::removeNoticfy(std::string key)

{

    // 获得 UIApplication

    UIApplication *app = [UIApplication sharedApplication];

    app.applicationIconBadgeNumber = 0;

    //获取本地推送数组

    NSArray *localArray = [app scheduledLocalNotifications];

    //声明本地通知对象

    UILocalNotification *localNotification = nil;


    if (localArray)

    {

        for (UILocalNotification *notiin localArray)

        {

            NSDictionary *dict = noti.userInfo;

            if (dict) {

                NSString* keys = [[[NSString alloc] initWithUTF8String: key.c_str()] autorelease];

                NSString* inKey = [dict objectForKey:@"DDNoticfykey"];

                

                if ([inKey isEqualToString:keys])

                {

                    NSLog(@"remove1 %@,%@",keys,inKey);

                    [app cancelLocalNotification: noti];

                    if (localNotification){

                        [localNotification release];

                        localNotification = nil;

                    }

                    localNotification = [noti retain];

                    break;

                }

                

            }

        }

        

        //判断是否找到已经存在的相同key的推送

        if (!localNotification) {

            //不存在初始化

            localNotification = [[UILocalNotification alloc] init];

        }

        

        if (localNotification) {

            //不推送 取消推送

            [app cancelLocalNotification:localNotification];

            [localNotification release];

            return;

        }

    }

}


android下没有系统直接延时本地推送的功能,我们使用AlarmManager闹钟服务,和BroadcastReceiver广播来做一个本地推送

首先建一个Cocos2dxAlarmManager类


package org.cocos2dx.lib;


import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;


import android.app.AlarmManager;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.util.Log;


public class Cocos2dxAlarmManager {

    publicstatic void alarmNotify(Context Context, String jsonString)

    {

        AlarmManager localAlarmManager = (AlarmManager)Context.getSystemService(android.content.Context.ALARM_SERVICE);

        

        String countTimeType = "rtc";

        long intervalAtMillis = 86400;

        long triggerAtMillis = System.currentTimeMillis() / 1000L;

        int type = AlarmManager.RTC;

        PendingIntent localPendingIntent;

        try

        {

          JSONObject localJSONObject = new JSONObject(jsonString);

          String packageName = localJSONObject.optString("packageName",Context.getPackageName());

          String ticker = localJSONObject.optString("ticker", "null");

          String title = localJSONObject.optString("title", "null");

          String text = localJSONObject.optString("text", "null");

          String str1 = localJSONObject.optString("tag", "noonce");

          triggerAtMillis = localJSONObject.optLong("triggerAtMillis", System.currentTimeMillis() / 1000L);

          long triggerOffset = localJSONObject.optLong("triggerOffset", 0L);

          intervalAtMillis = localJSONObject.optLong("intervalAtMillis", 0);

          countTimeType = localJSONObject.optString("countTimeType", "rtc");

          triggerAtMillis *= 1000L;

          long triggerOffsetMillis = triggerOffset * 1000L;

          intervalAtMillis *= 1000L;

          int id = localJSONObject.optInt("id", 0);



          if (triggerOffsetMillis > 0L)

              triggerAtMillis += triggerOffsetMillis;

//          if (!countTimeType.equals("rtc"))

//            return;


          Intent localIntent = new Intent("game_receiver");//广播名,时间到了就会发送game_receiver

          Bundle localBundle = new Bundle();

          localBundle.putInt("flag", id);

          localBundle.putString("packageName", packageName);

          localBundle.putString("ticker", ticker);

          localBundle.putString("title", title);

          localBundle.putString("text", text);

          localIntent.putExtras(localBundle);

          localPendingIntent = PendingIntent.getBroadcast(Context, id, localIntent, PendingIntent.FLAG_UPDATE_CURRENT);

          if (!str1.equals("once"))

          {

              localAlarmManager.set(type, triggerAtMillis, localPendingIntent);

          }

          else

          {

              localAlarmManager.setRepeating(type , triggerAtMillis, intervalAtMillis, localPendingIntent); 

          }


//            Intent localIntent1 = new Intent("game_receiver");

//            PendingIntent localPendingIntent1 = PendingIntent.getBroadcast(Context, 0, localIntent, 0);

          long sss = System.currentTimeMillis();

          sss += 10000;   

          Log.v("MyService","Cocos2dxAlarmManager "+(System.currentTimeMillis()-triggerAtMillis));

          

//            localAlarmManager.set(AlarmManager.RTC_WAKEUP , triggerAtMillis, localPendingIntent);

//            localAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP , System.currentTimeMillis(), 5000, localPendingIntent); 

        }

        catch (JSONException localJSONException)

        {

//          localJSONException.printStackTrace();

//

//          if (countTimeType.equals("rtc_wakeup"))

//              type = AlarmManager.RTC_WAKEUP;

//          if (countTimeType.equals("elapsed_wakeup"))

//              type = AlarmManager.ELAPSED_REALTIME_WAKEUP;

//          type = AlarmManager.ELAPSED_REALTIME;

//          

//          localAlarmManager.setRepeating(type, triggerAtMillis, intervalAtMillis, localPendingIntent);

        }

    }

    

    publicstatic void cancelNotify(Context paramContext,int paramInt)

      {

        NotificationManager localNotificationManager = (NotificationManager)paramContext.getSystemService("notification");

        localNotificationManager.cancel(paramInt);

        

        AlarmManager localAlarmManager = (AlarmManager)paramContext.getSystemService(android.content.Context.ALARM_SERVICE);

        PendingIntent localPendingIntent = PendingIntent.getBroadcast(paramContext, paramInt,new Intent("game_receiver"), PendingIntent.FLAG_NO_CREATE);

        if (localPendingIntent ==null)

          return;

        localAlarmManager.cancel(localPendingIntent);

      }


      publicstatic void cancelNotify(Context paramContext, String paramString)

      {

        AlarmManager localAlarmManager = (AlarmManager)paramContext.getSystemService(android.content.Context.ALARM_SERVICE);

        try

        {

          JSONArray localJSONArray = new JSONObject(paramString).optJSONArray("piids");

          int i = 0;

          if (i >= localJSONArray.length())

            return;

          PendingIntent localPendingIntent = PendingIntent.getBroadcast(paramContext, localJSONArray.getInt(i),new Intent("game_receiver"), PendingIntent.FLAG_NO_CREATE);

          if (localPendingIntent !=null)

            localAlarmManager.cancel(localPendingIntent);

          ++i;

        }

        catch (JSONException localJSONException)

        {

          localJSONException.printStackTrace();

        }

      }

}


在Cocos2dxActivity.java中添加一个方法给调用者使用


public staticvoid addNoticfy(String title,String content,int delalt,int key,int repeatTime)

    {

        JSONObject j = new JSONObject();

        try {

            j.put("ticker", content);

            j.put("title", title);

            j.put("text", content);

            if(repeatTime<=0)

            {

                j.put("tag", "once");

            }

            else

            {

                j.put("intervalAtMillis", repeatTime);

            }

            j.put("triggerOffset", delalt);

            j.put("id", key);

            j.put("packageName", "com.xxx.cxxxx");//包名注意填

            Cocos2dxAlarmManager.alarmNotify(instance, j.toString());

        } catch (JSONException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }


再添加一个Cocos2dxBroadcastReceiver类用于接收广播


package org.cocos2dx.lib;


import android.app.ActivityManager;

import android.app.ActivityManager.RunningServiceInfo;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.util.Log;


public class Cocos2dxBroadcastReceiverextends BroadcastReceiver

{


    @Override

    publicvoid onReceive(Context context, Intent intent) {

        // TODO Auto-generated method stub


        if(intent.getAction().equals("game_receiver"))

        {

            Log.v("MyService","Cocos2dxPushService onReceive"); 

            Bundle localBundle = intent.getExtras();

            int flag = localBundle.getInt("flag");

            String packageName = localBundle.getString("packageName");

            String ticker = localBundle.getString("ticker");

            String title = localBundle.getString("title");

            String text = localBundle.getString("text");

            int id = localBundle.getInt("id");

            Log.v("MyService","Cocos2dxPushService onReceive2  "+packageName); 

            Cocos2dxNotification.doNotify(context, packageName, ticker, title, text,id);//开始本地推送

        }

    }

}


再添加一个推送消息类


package org.cocos2dx.lib;


import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.Context;

import android.content.Intent;

import android.support.v4.app.NotificationCompat;

import android.util.Log;


public class Cocos2dxNotification {

    publicstatic void doNotify(Context paramContext, String packageName, String ticker, String title, String text,int id)

    {int icon = paramContext.getResources().getIdentifier("notification_icon", "drawable", paramContext.getPackageName()); 

        

        NotificationManager localNotificationManager = (NotificationManager)paramContext.getSystemService("notification");

        NotificationCompat.Builder localBuilder = new NotificationCompat.Builder(paramContext);

        localBuilder.setSmallIcon(icon);

        localBuilder.setTicker(ticker);

        localBuilder.setContentTitle(title);

        localBuilder.setContentText(text);

        localBuilder.setAutoCancel(true);

        try

        {

            Log.v("MyService",packageName);

            Log.v("MyService",Class.forName(packageName).toString());

          Intent localIntent = new Intent(paramContext, Class.forName(packageName));

          localIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

          localIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

          localBuilder.setContentIntent(PendingIntent.getActivity(paramContext, 0, localIntent, PendingIntent.FLAG_ONE_SHOT));

          Notification notfi =localBuilder.build();

          notfi.defaults=Notification.DEFAULT_SOUND;

          notfi.defaults |= Notification.DEFAULT_VIBRATE;

          notfi.defaults|=Notification.DEFAULT_LIGHTS; 

          localNotificationManager.notify(id, notfi);

          return;

        }

        catch (ClassNotFoundException localClassNotFoundException)

        {

          localClassNotFoundException.printStackTrace();

        }

    }

}

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 八个月宝宝只吃母乳不吃奶粉怎么办 八个月母乳不够宝宝不吃奶粉怎么办 八个月宝宝吃母乳不吃奶粉怎么办 八个月宝宝戒奶不吃奶粉怎么办 刚满月的宝宝发烧38度怎么办 未满月的宝宝发烧38度怎么办 半月大的婴儿吃奶就漾奶怎么办 上司交给你不能完成的任务怎么办 电脑光驱里放入光碟放不出来怎么办 黑暗之魂3太难了怎么办 苹果手机下载的游戏闪退怎么办 宝宝两岁了不怎么爱拉大便怎么办? 小狗脖子发硬疼的直叫怎么办 厨房里有很多小虫子围着鸡蛋怎么办 狗生小狗后几天不吃饭怎么办 还没满月的小兔子突然死了怎么办 宝宝小鸡被蚊子咬后肿得很大怎么办 不知道是哪知兔子下的小兔怎么办 兔子生完小兔不吃东西了怎么办 人工喂养七天的小羊拉希怎么办 仔兔出生3天吃过奶就尿怎么办 小兔子买回来两天不拉屎怎么办 大狗生了小狗把小狗咬死了怎么办 狗妈妈一直咬小狗的脐带怎么办 狗狗体内驱虫驱不干净怎么办 打老鼠脚被老鼠咬了怎么办 天正画的cad打开显示空白怎么办 苹果手机信息被拉进群聊怎么办 空调的控制线的报验资料怎么办 窗窗户罩子护栏上的瓦楞板怎么办 酸洗好的带钢容易返锈怎么办 化肥撤到小树苗上现在变黑了怎么办 尿素液烧的太慢了怎么办 天堂鸟肥料施多了黄叶了怎么办 死水塘养的鱼每天在死怎么办 北京的阿姆斯肥把苗都烧死了怎么办 纱窗被老鼠咬了个洞 怎么办 低电量模式下动态墙纸不能用怎么办 吃的包装袋执行标准错了怎么办 退换东西的时候外包装坏了怎么办 闲鱼买家以与描述不符退货怎么办