Unity 应用的消息推送《一》本地推送

欢迎加入Unity业内qq交流群:956187480

qq扫描二维码加群


 

  参考博客地址:https://blog.csdn.net/qq_37310110/article/details/80423463

 自打接了这个项目到现在天天活在煎熬之中,这不新需求来了。需要推送消息,然后在后端大哥的帮助下梳理了一下推送的大致流程。之后我就在网上参考广大开发者的方案。

       依据我当前的项目我的理解,消息推送分本地客户端推送(不需要第三方sdk,不需要后端)和服务器推送(接第三方sdk或者不接),首先大致讲解一下本地客户端推送,这个推送是用不到服务器的,整个流程都是在客户端完成。

以下资料来源网络,如有侵权请告知

IOS本地推送Unity内部封装了在iOS下的本地推送功能,可以很方便的实现在iOS设备上的简单本地推送。

命名空间为:UnityEngine.iOS 在Unity中的代码和直接用swift的代码基本类似。具体代码实现:

static void NotificationMessage(string message, System.DateTime newDate, bool isRepeatDay)
{        //推送时间需要大于当前时间
    if (newDate > System.DateTime.Now)
    {
        UnityEngine.iOS.LocalNotificationlocalNotification = new UnityEngine.iO      S.LocalNotification();
        localNotification.fireDate = newDate;
        localNotification.alertBody = message;
        localNotification.applicationIconBadgeNumber = 1;
        localNotification.hasAction = true;
        if (isRepeatDay)
        {                //是否每天定期循环
            localNotification.repeatCalendar = UnityEngine.iOS.CalendarIdentifier.C  hineseCalendar;//中国日历
            localNotification.repeatInterval = UnityEngine.iOS.CalendarUnit.Day;//每日推送
        }
        localNotification.soundName = UnityEngine.iOS.LocalNotification.defaultSound Name;
        UnityEngine.iOS.NotificationServices.RegisterForNotifications(UnityEngine.iOS.NotificationType.Alert | UnityEngine.iOS.NotificationType.Badge | UnityEngine.iOS.NotificationType.Sound);
        //以特定的类型推送
        UnityEngine.iOS.NotificationServices.ScheduleLocalNotification(localNotification);
    }
}    //游戏退出时调用
void OnApplicationQuit()
{        //每天中午12点推送
    NotificationMessage("每天中午12点推送", 12, true);
}    //游戏进入后台时或者从后台进入前台时调用
void OnApplicationPause(bool paused)
{        //程序进入后台时
    if (paused)
    {            //每天中午12点推送
        NotificationMessage("每天12点推送", 12, true);
    }
    else
    {            //程序从后台进入前台时
        CleanNotification();
    }
}    //清除推送消息,在Awake中调用
void CleanNotification()
{
    UnityEngine.iOS.LocalNotification ln = new UnityEngine.iOS.LocalNotification();
    ln.applicationIconBadgeNumber = -1;
    UnityEngine.iOS.NotificationServices.PresentLocalNotificationNow(ln);
    UnityEngine.iOS.NotificationServices.CancelAllLocalNotifications();
    UnityEngine.iOS.NotificationServices.ClearLocalNotifications();
}

Android本地推送:

要想实现推送机制,那么第一步便是需要完成unity与android之间的交互,也就是c#与java之间的互相调用。

首先来看C# to java,通过查询unity官方api,发现unity提供了调用java代码的接口,下面贴出我封装好的一个类 
public class AndroidNative 

public static void ScheduleLocalNotification(string message, int seconds, int id) 

CallActivityFunction(“ScheduleLocalNotification”,message, seconds, id); 

}

public static void callLoginMethod(string methodName)
{
    CallActivityFunction(methodName);
}
private static void CallActivityFunction(string methodName, params object[] args) 
{
    #if UNITY_ANDROID
    if(Application.platform != RuntimePlatform.Android) 
    {
        return;
    }
    try 
    {
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); 
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"); 
        jo.Call(methodName, args);
    }
    catch(System.Exception ex)
    {
        Debug.LogWarning(ex.Message);
    }
    #endif
}

可以看到jo.Call(methodName, args);这句代码就是实现c#调用java的关键了,而调用的方法名字既是java端的ScheduleLocalNotification方法。 

 

至于java调用c#,因为推送暂时用不到,就不说了,也很简单,需要的可以自己去查下

 

 

android推送不比ios,ios总得来说是对开发者友好的,只需要启动一个推送,然后设置更新时间,就可以隔一段时间自动推送了,然而android不能,写一个推送,只能在你指定的时间推送一次,因此,要实现定时推送,就必须配合计时器使用了。

首先说下android定时器

需要在AndroidManifest.xml里面注册一个receiver: 
这里写图片描述 
还需要实现一个receiver类,”com.XXX.XXX.MyReceiver”,该类继承自BroadcastReceiver。

接着我们启动一个定时器 
 

 public void ScheduleLocalNotification (String message,int seconds, int notificationId ) 
{     JSONObject json = new JSONObject(); 
        try {
            json.put("message", message);
            json.put("seconds",seconds);
            json.put("notificationId",notificationId);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Intent intent = new Intent(this,MyReceiver.class);

        intent.putExtra("json",json.toString());
          // get the AlarmManager instance   
        AlarmManager am= (AlarmManager) getSystemService(ALARM_SERVICE);  
        // create a PendingIntent that will perform a broadcast  
        PendingIntent pi= PendingIntent.getBroadcast(UnityPlayerNativeActivity.this, 0, intent, 0);  
        // just use current time + 10s as the Alarm time.   
        Calendar c=Calendar.getInstance();

        c.setTimeInMillis(System.currentTimeMillis());
        c.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        //可以根据项目要求修改,秒、分钟、提前、延后
        c.add(Calendar.SECOND, seconds);
        // schedule an alarm  
        am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),86400000, pi);
    }

定时器就是通过广播的形式,建立一个长连接,然后在receiver类里面实现public void onReceive(Context context, Intent intent) { }方法,这样到了定时器设定的时间,就会走onRecevie方法,在该方法里面,即可实现推送逻辑,json也会通过透传的方式传递过来,String jasonStr = intent.getStringExtra(“json”);即可得到json字符串,然后起一个推送即可。

再来看推送实现,推送就很简单了,下面直接贴出代码, 

 public static void registerLocalNotification(final Context context, final int seconds , final String message, final int notificationId) {        Builder notification = new Notification.Builder(context);   
        Resources res = context.getResources();
        int app_icon = res.getIdentifier("app_icon", "drawable", context.getPackageName());
        int app_name = res.getIdentifier("app_name", "string", context.getPackageName());
        String title = context.getString(app_name);
        Intent intent = new Intent(context, UnityPlayerNativeActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setAutoCancel(true);

        notification.setContentTitle(title);
        notification.setContentIntent(contentIntent);
        notification.setContentText(message);
        notification.setSmallIcon(app_icon);
        notification.setWhen(System.currentTimeMillis());
        final Notification notify = notification.build();

        getNotificationManager(context).notify(notificationId,notify);
   }

    private static NotificationManager getNotificationManager(Context context) {
        return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }

按照要求设置好信息以后,就可以正常推送了,注意图标一定要设置正确,否则推送无法正常显示。

参考链接    点击打开链接

这次只记录本地推送,下一篇记录第三方插件的运用


欢迎加入Unity业内qq交流群:956187480

qq扫描二维码加群

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

幻世界

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值