现在的游戏里一般都会有本地消息,比如每天定时12点或者下午6点告诉玩家进入游戏领取体力。这种东西没必要服务器去推送,客户端就可以完成。Unity里面提供了本地任务的功能但是只有IOS上才支持,开始我有点不解为什么Android上不支持,当我把Android的本地通知做完后,我才明白。IOS源生的API中就支持固定时间循环推送,而Android上需要自己开启一个Services,启动一个AlarmManager的定时器任务,还好我之前开发过Android, 言归正传今天我们先说IOS上的本地通知。
代码其实很简单,我先说下原理后面给出实现步骤。
1.当游戏进入后台的时候注册本地通知
2.当游戏进入前台的时候关闭本地通知
下面上代码。
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
|
using
UnityEngine
;
using
System
.
Collections
;
public
class
NewBehaviourScript
:
MonoBehaviour
{
//本地推送
public
static
void
NotificationMessage
(
string
message
,
int
hour
,
bool
isRepeatDay
)
{
int
year
=
System
.
DateTime
.
Now
.
Year
;
int
month
=
System
.
DateTime
.
Now
.
Month
;
int
day
=
System
.
DateTime
.
Now
.
Day
;
System
.
DateTime
newDate
=
new
System
.
DateTime
(
year
,
month
,
day
,
hour
,
0
,
0
)
;
NotificationMessage
(
message
,
newDate
,
isRepeatDay
)
;
}
//本地推送 你可以传入一个固定的推送时间
public
static
void
NotificationMessage
(
string
message
,
System
.
DateTime
newDate
,
bool
isRepeatDay
)
{
//推送时间需要大于当前时间
if
(
newDate
>
System
.
DateTime
.
Now
)
{
LocalNotification
localNotification
=
new
LocalNotification
(
)
;
localNotification
.
fireDate
=
newDate
;
localNotification
.
alertBody
=
message
;
localNotification
.
applicationIconBadgeNumber
=
1
;
localNotification
.
hasAction
=
true
;
if
(
isRepeatDay
)
{
//是否每天定期循环
localNotification
.
repeatCalendar
=
CalendarIdentifier
.
ChineseCalendar
;
localNotification
.
repeatInterval
=
CalendarUnit
.
Day
;
}
localNotification
.
soundName
=
LocalNotification
.
defaultSoundName
;
NotificationServices
.
ScheduleLocalNotification
(
localNotification
)
;
}
}
void
Awake
(
)
{
//第一次进入游戏的时候清空,有可能用户自己把游戏冲后台杀死,这里强制清空
CleanNotification
(
)
;
}
void
OnApplicationPause
(
bool
paused
)
{
//程序进入后台时
if
(
paused
)
{
//10秒后发送
NotificationMessage
(
"雨松MOMO : 10秒后发送"
,
System
.
DateTime
.
Now
.
AddSeconds
(
10
)
,
false
)
;
//每天中午12点推送
NotificationMessage
(
"雨松MOMO : 每天中午12点推送"
,
12
,
true
)
;
}
else
{
//程序从后台进入前台时
CleanNotification
(
)
;
}
}
//清空所有本地消息
void
CleanNotification
(
)
{
LocalNotification
l
=
new
LocalNotification
(
)
;
l
.
applicationIconBadgeNumber
=
-
1
;
NotificationServices
.
PresentLocalNotificationNow
(
l
)
;
NotificationServices
.
CancelAllLocalNotifications
(
)
;
NotificationServices
.
ClearLocalNotifications
(
)
;
}
}
|
弹出的消息通知。