在Unity3D中实现安卓平台的本地通知推送_unity 定时推送-程序员宅基地

技术标签: unity  android  本地推送  eclipse  

这是我在网上看到的一个大神写的android本地推送的文章很好,很详细,特转载了过来,如果原作者看到,不让转载的话,我会立刻删除该博客,大神原链接:https://www.cnblogs.com/GuyaWeiren/p/4830854.html

 

【前言】

  对于手游来说,什么时候需要推送呢?玩过一些带体力限制的游戏就会发现,我的体力在恢复满后,手机会收到一个通知告诉我体力已完全恢复了。这类通知通常是由本地的客户端发起的,没有经过服务端。

  在安卓应用中,本地通知推送是通过调用系统级服务NotificationManager实现的。虽然U3D本身也有NotificationServices类可以进行通知推送,但仅限于iOS平台(这篇博文讲了怎么使用它在iOS平台发起本机推送)。

  而现在我们的游戏是使用U3D开发的,并不能像安卓开发一样直接在代码中调用服务。为了实现本地定时推送效果,需要自己写一个插件来实现了。

  由于推送通常发生在客户端关闭的状态,这个推送应该被放在一个延时服务中,否则玩游戏玩得好好的突然跳出来一条自己的推送,太诡异了。

  于是我们需要完成一个提供三个功能的模块:1、设定X秒后显示一条推送通知;2、设定X秒后显示一条通知,之后每天再显示一次;3、清除本应用的所有推送。

 


【解决思路】

  因为U3D引擎提供了调用jar包的方法,所以我们可以在jar包中调用安卓的类库,实现消息推送,然后在jar包中留出接口供U3D使用即可,没有必要走JNI层。

 


【所需工具】

  ● eclipse

  ● 安卓SDK(我使用的4.4)

  ● Unity编辑器(我使用的5.1.3) 

 


【开工】

  1、  创建jar包工程

    创建的时候要引入两个第三方jar包。

    一个是Unity的包,地址: Unity安装目录\Editor\Data\PlaybackEngines\androidplayer\release\bin\classes.jar(貌似4.x的目录和5.x不太一样,但总之就是找到androidplayer里面的classes.jar)

    还有一个是安卓SDK的包,地址: 安卓SDK安装目录\platforms\安卓版本\android.jar

     

 

  2、  编码

    思路就是使用AlarmManager服务,在一定时间后发起广播,然后通过接收器接受展示。如果你做过安卓开发,对这段代码肯定不会陌生。如果没做过也没关系,当成一个黑盒,在需要的时候调接口就行。

    首先添加一个Java类,注意父类要设为BroadcastReceiver。

    

    

    添加完成后,就可以开始写了:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

package com.guyastudio.unityplugins;

 

import java.util.Calendar;

 

import android.app.Activity;

import android.app.AlarmManager;

import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.pm.ApplicationInfo;

import android.content.pm.PackageManager;

import android.os.Bundle;

 

import com.unity3d.player.UnityPlayer;

 

 

/**

 * 用于生成 / 清除本地通知推送的插件

 * 仅在安卓平台有效

 *

 * @author Weiren

 *

 */

public class AndroidNotificator extends BroadcastReceiver {

 

    private static int m_nLastID = 0;

         

     

    /**

     * 显示数秒后的通知

     *

     * @param pAppName 应用名

     * @param pTitle 通知标题

     * @param pContent 通知内容

     * @param pDelaySecond 延迟时间

     * @param pIsDailyLoop 是否每日自动推送

     * @throws IllegalArgumentException

     */

    public static void ShowNotification(String pAppName, String pTitle, String pContent, int pDelaySecond, boolean pIsDailyLoop) throws IllegalArgumentException { 

         

        if(pDelaySecond < 0)

        {

            throw new IllegalArgumentException("The param: pDelaySecond < 0");

        }

         

        Activity curActivity = UnityPlayer.currentActivity;

         

        Intent intent = new Intent("UNITY_NOTIFICATOR");

        intent.putExtra("appname", pAppName);

        intent.putExtra("title", pTitle);

        intent.putExtra("content", pContent);

        PendingIntent pi =  PendingIntent.getBroadcast(curActivity, 0, intent, 0);

         

        AlarmManager am = (AlarmManager)curActivity.getSystemService(Context.ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance(); 

        calendar.add(Calendar.SECOND, pDelaySecond);

        long alarmTime = calendar.getTimeInMillis(); 

         

        if (pIsDailyLoop){

            am.setRepeating(

                    AlarmManager.RTC_WAKEUP,

                    alarmTime,

                    86400// 24 hours

                    pi);

        else {

            am.set(

                    AlarmManager.RTC_WAKEUP,

                    alarmTime,

                    pi);  

        }

    }  

     

     

    /**

     * 清除所有通知,包括日常通知

     */

    public static void ClearNotification() {

         

        Activity act = UnityPlayer.currentActivity;

        NotificationManager nManager = (NotificationManager)act.getSystemService(Context.NOTIFICATION_SERVICE);

         

        for(int i = m_nLastID; i >= 0; i--) {

            nManager.cancel(i);

        }

         

        m_nLastID = 0;

    }

     

     

    @SuppressWarnings("deprecation")

    public void onReceive(Context pContext, Intent pIntent) {

         

        Class<?> unityActivity = null;

        try {

            unityActivity = pContext.getClassLoader().loadClass("com.unity3d.player.UnityPlayerProxyActivity");

        catch (Exception ex) {   

            ex.printStackTrace(); 

            return;     

        }     

         

        ApplicationInfo applicationInfo = null;

        PackageManager pm = pContext.getPackageManager(); 

         

        try {             

            applicationInfo = pm.getApplicationInfo(pContext.getPackageName(), PackageManager.GET_META_DATA); 

        catch (Exception ex) {

            ex.printStackTrace();

            return;    

        }    

         

        Bundle bundle = pIntent.getExtras();

         

        Notification notification = new Notification(

                applicationInfo.icon,

                (String)bundle.get("appname"),

                System.currentTimeMillis());    

         

        PendingIntent contentIntent = PendingIntent.getActivity(

                pContext,

                m_nLastID,

                new Intent(pContext, unityActivity),

                0);  

        notification.setLatestEventInfo(

                pContext,

                (String)bundle.get("title"),

                (String)bundle.get("content"),

                contentIntent);

         

        NotificationManager nm = (NotificationManager)pContext.getSystemService(Context.NOTIFICATION_SERVICE); 

        nm.notify(m_nLastID, notification); 

         

        m_nLastID++;

    }

}

   

  3、  导出jar包

    在项目上右键——Export,导出为jar格式。

    

 

  4、添加AndroidManifest.xml

    安卓应用中如果要让应用收到广播,还需要在AndroidManifest.xml中加入receiver标签。我们创建的项目是一个Java项目,不会自动生成AndroidManifest,所以需要手动写一个:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="preferExternal" android:theme="@android:style/Theme.NoTitleBar" android:versionName="1.0" android:versionCode="10">

  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />

  <application android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="false"> 

    <receiver android:process=":remote" android:name="com.macaronics.notification.AlarmReceiver"></receiver>

    <activity android:name="com.unity3d.player.UnityPlayerProxyActivity" android:label="@string/app_name" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" >

      <intent-filter>

        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />

      </intent-filter>

    </activity>

    <activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="@string/app_name" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" >

    </activity>

    <receiver android:name="com.guyastudio.unityplugins.AndroidNotificator" >

      <intent-filter>

        <action android:name="UNITY_NOTIFICATOR" />

      </intent-filter>

    </receiver>

  </application>

  <uses-feature android:glEsVersion="0x00020000" />

  

  <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />

  

</manifest>

  ● 注意“<action android:name="UNITY_NOTIFICATOR" />”这里名字要和前面Java代码中的一致。

 

  4、  在U3D项目中调用

    创建一个新的U3D项目,在界面上放一个Text和两个Button(为节约时间我用的源生UI):

    

    

    然后将导出的jar文件和AndroidManifest.xml文件移动到 U3D项目目录\Assets\Plugins\Android下:

    

 

    在几个UI的父节点上加一个脚本,内容如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

using UnityEngine;

using UnityEngine.UI;

 

 

public class JARTest : MonoBehaviour {

 

    public Text Text_Message;

 

 

#if UNITY_ANDROID

    private AndroidJavaObject m_ANObj = null;

#endif

 

 

    // Use this for initialization

    void Start () { }

     

    // Update is called once per frame

    void Update () { }

 

 

    public void Button_1_Clicked()

    {

#if UNITY_ANDROID

        if(InitNotificator())

        {

            m_ANObj.CallStatic(

                "ShowNotification",

                Application.productName,

                "温馨提示",

                "你该食屎了",

                10,

                false);

            this.Text_Message.text = "Notification will show in 10 sec.";

        }

#endif

    }

 

 

    public void Button_2_Clicked()

    {

#if UNITY_ANDROID

        if(InitNotificator())

        {

            m_ANObj.CallStatic("ClearNotification");

            this.Text_Message.text = "Notification has been cleaned";

        }

#endif

    }

 

 

#if UNITY_ANDROID

    private bool InitNotificator()

    {

        if (m_ANObj == null)

        {

            try

            {

                m_ANObj = new AndroidJavaObject("com.guyastudio.unityplugins.AndroidNotificator");

            }

            catch

            {

                this.Text_Message.text = "Init AndroidNotificator Fail";

                return false;

            }

        }

 

        if (m_ANObj == null)

        {

            this.Text_Message.text = "AndroidNotificator Not Found.";

            return false;

        }

 

        return true;

    }

#endif

}

    ● 注意实例化AndroidJavaObject的参数名字要和Java工程的包名类名一致。

 

     然后绑定控件和事件方法。绑定好后先编译一下,如果通过了,就可以导出一个apk包了。将这个包安装到安卓设备上。我手头没有安卓设备,就用模拟器来测试:

    

    

    点击“Show”按钮,10秒后会收到通知(点击后可将应用至后台,或杀掉):

    

    

    而点击“Clean”按钮,通知都会被清除。

 

    至此,这个通知插件就完成了。

 

经过本人测试,没有弹出推送信息,查了一下里面的一些方法过时了,这里再给出一个链接:https://blog.csdn.net/azhou_hui/article/details/50790870

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/CrazyApp/article/details/88106438

智能推荐

稀疏编码的数学基础与理论分析-程序员宅基地

文章浏览阅读290次,点赞8次,收藏10次。1.背景介绍稀疏编码是一种用于处理稀疏数据的编码技术,其主要应用于信息传输、存储和处理等领域。稀疏数据是指数据中大部分元素为零或近似于零的数据,例如文本、图像、音频、视频等。稀疏编码的核心思想是将稀疏数据表示为非零元素和它们对应的位置信息,从而减少存储空间和计算复杂度。稀疏编码的研究起源于1990年代,随着大数据时代的到来,稀疏编码技术的应用范围和影响力不断扩大。目前,稀疏编码已经成为计算...

EasyGBS国标流媒体服务器GB28181国标方案安装使用文档-程序员宅基地

文章浏览阅读217次。EasyGBS - GB28181 国标方案安装使用文档下载安装包下载,正式使用需商业授权, 功能一致在线演示在线API架构图EasySIPCMSSIP 中心信令服务, 单节点, 自带一个 Redis Server, 随 EasySIPCMS 自启动, 不需要手动运行EasySIPSMSSIP 流媒体服务, 根..._easygbs-windows-2.6.0-23042316使用文档

【Web】记录巅峰极客2023 BabyURL题目复现——Jackson原生链_原生jackson 反序列化链子-程序员宅基地

文章浏览阅读1.2k次,点赞27次,收藏7次。2023巅峰极客 BabyURL之前AliyunCTF Bypassit I这题考查了这样一条链子:其实就是Jackson的原生反序列化利用今天复现的这题也是大同小异,一起来整一下。_原生jackson 反序列化链子

一文搞懂SpringCloud,详解干货,做好笔记_spring cloud-程序员宅基地

文章浏览阅读734次,点赞9次,收藏7次。微服务架构简单的说就是将单体应用进一步拆分,拆分成更小的服务,每个服务都是一个可以独立运行的项目。这么多小服务,如何管理他们?(服务治理 注册中心[服务注册 发现 剔除])这么多小服务,他们之间如何通讯?这么多小服务,客户端怎么访问他们?(网关)这么多小服务,一旦出现问题了,应该如何自处理?(容错)这么多小服务,一旦出现问题了,应该如何排错?(链路追踪)对于上面的问题,是任何一个微服务设计者都不能绕过去的,因此大部分的微服务产品都针对每一个问题提供了相应的组件来解决它们。_spring cloud

Js实现图片点击切换与轮播-程序员宅基地

文章浏览阅读5.9k次,点赞6次,收藏20次。Js实现图片点击切换与轮播图片点击切换<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <script type="text/ja..._点击图片进行轮播图切换

tensorflow-gpu版本安装教程(过程详细)_tensorflow gpu版本安装-程序员宅基地

文章浏览阅读10w+次,点赞245次,收藏1.5k次。在开始安装前,如果你的电脑装过tensorflow,请先把他们卸载干净,包括依赖的包(tensorflow-estimator、tensorboard、tensorflow、keras-applications、keras-preprocessing),不然后续安装了tensorflow-gpu可能会出现找不到cuda的问题。cuda、cudnn。..._tensorflow gpu版本安装

随便推点

物联网时代 权限滥用漏洞的攻击及防御-程序员宅基地

文章浏览阅读243次。0x00 简介权限滥用漏洞一般归类于逻辑问题,是指服务端功能开放过多或权限限制不严格,导致攻击者可以通过直接或间接调用的方式达到攻击效果。随着物联网时代的到来,这种漏洞已经屡见不鲜,各种漏洞组合利用也是千奇百怪、五花八门,这里总结漏洞是为了更好地应对和预防,如有不妥之处还请业内人士多多指教。0x01 背景2014年4月,在比特币飞涨的时代某网站曾经..._使用物联网漏洞的使用者

Visual Odometry and Depth Calculation--Epipolar Geometry--Direct Method--PnP_normalized plane coordinates-程序员宅基地

文章浏览阅读786次。A. Epipolar geometry and triangulationThe epipolar geometry mainly adopts the feature point method, such as SIFT, SURF and ORB, etc. to obtain the feature points corresponding to two frames of images. As shown in Figure 1, let the first image be ​ and th_normalized plane coordinates

开放信息抽取(OIE)系统(三)-- 第二代开放信息抽取系统(人工规则, rule-based, 先抽取关系)_语义角色增强的关系抽取-程序员宅基地

文章浏览阅读708次,点赞2次,收藏3次。开放信息抽取(OIE)系统(三)-- 第二代开放信息抽取系统(人工规则, rule-based, 先关系再实体)一.第二代开放信息抽取系统背景​ 第一代开放信息抽取系统(Open Information Extraction, OIE, learning-based, 自学习, 先抽取实体)通常抽取大量冗余信息,为了消除这些冗余信息,诞生了第二代开放信息抽取系统。二.第二代开放信息抽取系统历史第二代开放信息抽取系统着眼于解决第一代系统的三大问题: 大量非信息性提取(即省略关键信息的提取)、_语义角色增强的关系抽取

10个顶尖响应式HTML5网页_html欢迎页面-程序员宅基地

文章浏览阅读1.1w次,点赞6次,收藏51次。快速完成网页设计,10个顶尖响应式HTML5网页模板助你一臂之力为了寻找一个优质的网页模板,网页设计师和开发者往往可能会花上大半天的时间。不过幸运的是,现在的网页设计师和开发人员已经开始共享HTML5,Bootstrap和CSS3中的免费网页模板资源。鉴于网站模板的灵活性和强大的功能,现在广大设计师和开发者对html5网站的实际需求日益增长。为了造福大众,Mockplus的小伙伴整理了2018年最..._html欢迎页面

计算机二级 考试科目,2018全国计算机等级考试调整,一、二级都增加了考试科目...-程序员宅基地

文章浏览阅读282次。原标题:2018全国计算机等级考试调整,一、二级都增加了考试科目全国计算机等级考试将于9月15-17日举行。在备考的最后冲刺阶段,小编为大家整理了今年新公布的全国计算机等级考试调整方案,希望对备考的小伙伴有所帮助,快随小编往下看吧!从2018年3月开始,全国计算机等级考试实施2018版考试大纲,并按新体系开考各个考试级别。具体调整内容如下:一、考试级别及科目1.一级新增“网络安全素质教育”科目(代..._计算机二级增报科目什么意思

conan简单使用_apt install conan-程序员宅基地

文章浏览阅读240次。conan简单使用。_apt install conan