Unity之android推送

来源:互联网 发布:现代诗歌 知乎 编辑:程序博客网 时间:2024/06/05 07:05

0x00 引子
最近在整理android相关的一些工作,想起很久前做的android推送功能,记得当时网上资料不多,新手做起来有些困难,因此决定写一篇详细的博客,供大家参考一下,

0x01 交互
要想实现推送机制,那么第一步便是需要完成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#,因为推送暂时用不到,就不说了,也很简单,需要的可以自己去查下。

0x02 android推送
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);    }

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

0x03 小结

其实android推送说起来很简单,就是启动一个定时器,定时器会通过广播的方式,按时回调onRecevie方法。代码也都贴出来了,如果还有哪里不明白,欢迎大家留言探讨。

0 0
原创粉丝点击