cocos2d-x中本地推送訊息,cocos2d-x推送訊息

來源:互聯網
上載者:User

cocos2d-x中本地推送訊息,cocos2d-x推送訊息

作者:HU

轉載請註明,原文連結:http://www.cnblogs.com/xioapingguo/p/4038277.html 

IOS下很簡單:

添加一條推送

void PushNotificationIOS::addNoticfy(std::string title,std::string content,unsigned int delalt,std::string key,unsigned int 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 *noti in 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 {    public static 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); } } public static 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); } public static 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 static void 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 Cocos2dxBroadcastReceiver extends BroadcastReceiver{    @Override    public void 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 {    public static 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();        }    }}

使用時只要使用Cocos2dxActivity.java中

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

方法就可以和IOS一樣了。


百度貼吧訊息推送

你要再一個大型貼吧裡 層級比較高 發的文章是原創 有新意 很難得。
 
什是推送訊息?

(什麼是推送訊息)?
隨著 iPhone 和安卓手機這類超級手機的興起,現在完全可以繞過電訊廠商,通過標準 TCP/IP 網路直接向這些手機發送訊息。這些訊息就稱為推送 訊息。推送訊息是通過 Apple 和 Google 掌控的互連網伺服器發送的。推送訊息從根本上就是設計用於與應用程式通訊的。它們可以發送文本、多媒體檔案和特定於應用程式的資料,例如警告聲音和顯示在應用程式圖示上的標記等。推播通知非常適合智能手機應用,但與基於電訊廠商的移動訊息傳遞相比,它們的普及性和可靠性都較差。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.