小结Android和iOS中LocalNotification

用Unity开发游戏,总难免要用到Native
Development,比如Notification功能。

本文只对LocalNotification进行小结,iOS上RemoteNotification在此未讨论。(后面发现Unity已经把iOS部分给封装好了)

Notification大致提供了两个功能:Register和Cancel,没找到Update的API,后来自己想了个Update的方法,就是先Cancel再Register.

iOS:

 1 //由于c#用long类型传递秒数,而long类型在C#中是64位,在OC中是32位,这样会导致后面参数读取出现问题,所以这边senconds用int64_t代替(也可用long long)
2 + (void) registerLocalNotification:(int64_t)seconds withMessage:(NSString *)msg notificationId:(NSString*) notificationId
3 {
4 UILocalNotification *notification = [[UILocalNotification alloc] init];
5 NSDate *now = [NSDate date];
6 //通知触发的时间
7 notification.fireDate = [now dateByAddingTimeInterval:(NSTimeInterval)seconds];
8 //显示在通知中的信息
9 notification.alertBody = msg;
10 //通知显示时的提示音
11 notification.soundName = UILocalNotificationDefaultSoundName;
12 //桌面应用程序图标右上角显示的消息个数,这里每个消息都标记为1
13 notification.applicationIconBadgeNumber++;
14
15 //设置通知标识符,以便后面取消该通知使用,如果不做取消,可不设置
16 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:notificationId, NOTIFICATION_ID, nil];
17 notification.userInfo = dict;
18
19 //注册通知
20 [[UIApplication sharedApplication] scheduleLocalNotification:notification];
21 }
22
23 //API没Update操作,故用先Cancel再Register来解决
24 + (void) updateLocalNotification:(int64_t)seconds withMessage:(NSString *)msg notificationId:(NSString *)notificationId
25 {
26 [Notifier cancelLocalNotification:notificationId];
27 [Notifier registerLocalNotification:seconds withMessage:msg notificationId:notificationId];
28 }
29
30 + (void) cancelLocalNotification:(NSString *)notificationId
31 {
32 //获取当前应用程序已注册的所有本地通知
33 NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
34 for (UILocalNotification *notification in notifications)
35 {
36 //通过匹配原先注册时标记的Id号来查找
37 if ([[notification.userInfo objectForKey:NOTIFICATION_ID] isEqualToString:notificationId])
38 {
39 [[UIApplication sharedApplication] cancelLocalNotification:notification];
40 break;
41 }
42 }
43 }

Android:


 1 public class Notifier {
2
3 /*
4 * 由于Notification.when不起作用,故需要延时操作时采用postAtTime(Runnable r, Object token, long uptimeMillis)
5 * 其中token用来标记该runnable,以便后面取消用
6 * 注意:如果到了触发通知时,应用程序不在后台运行,则不会弹出通知,即app必须处于运行状态才有效
7 */
8 private static boolean initialized = false;
9 private static Handler mHandler;
10 private static Handler getHandler() {
11 if (!initialized) {
12 initialized = true;
13 HandlerThread thread = new HandlerThread("Notifier");
14 thread.start();
15 mHandler = new Handler(thread.getLooper());
16 }
17 return mHandler;
18 }
19
20 @SuppressWarnings("deprecation")
21 public static void registerLocalNotification(final Context context, final long seconds , final String message, final int notificationId) {
22
23 final Notification notification = new Notification();
24 Resources res = context.getResources();
25 int app_icon = res.getIdentifier("app_icon", "drawable", context.getPackageName());
26 int app_name = res.getIdentifier("app_name", "string", context.getPackageName());
27 String title = context.getString(app_name);
28 notification.icon = app_icon; //图标一定要设置正确,不正确会导致通知栏无法显示
29 long[] vibrate = {0, 100, 200, 300}; // 0ms后 震动100ms,200ms后震动300ms,用振动时,需在AndroidManifest声明android.permission.VIBRATE权限
30 notification.vibrate = vibrate;
31 notification.defaults |= Notification.DEFAULT_SOUND;
32 notification.flags |= Notification.FLAG_AUTO_CANCEL;
33 notification.when = System.currentTimeMillis() + seconds * 1000;
34 notification.tickerText = message;
35
36 Intent intent = new Intent(context, context.getClass());
37 PendingIntent contentIntent = PendingIntent.getActivity(context, app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
38 notification.setLatestEventInfo(context, title, message, contentIntent);
39
40 getHandler().postAtTime(new Runnable() {
41 @Override
42 public void run() {
43 if (Utils.isAppOnBackground(context)) {
44 getNotificationManager(context).notify(notificationId, notification);
45 }
46 }
47 }, Integer.toString(notificationId), SystemClock.uptimeMillis() + seconds * 1000);
48 }
49
50 private static NotificationManager getNotificationManager(Context context) {
51 return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
52 }
53
54 public static void updateLocalNotification(Context context, long seconds, String message, int notificationId) {
55 getHandler().removeCallbacksAndMessages(Integer.toString(notificationId));
56 registerLocalNotification(context, seconds, message, notificationId);
57 }
58
59 public static void cancelLocalNotification(int notificationId) {
60 getHandler().removeCallbacksAndMessages(Integer.toString(notificationId));
61 }
62 }

Android版本由于在应用程序处于前台时也会显示通知,所以我在触发通知的地方做了应用程序是否处于后台的判断


 1     public static boolean isAppOnBackground(Context context) {
2 ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
3 List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
4 for (RunningAppProcessInfo appProcess : appProcesses) {
5 if (appProcess.processName.equals(context.getPackageName())) {
6 if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
7 return true;
8 } else {
9 return false;
10 }
11 }
12 }
13 return false;
14 }

好了,关于LocalNotification的小结就到这了。如果读者有什么疑惑,可以回复下,大家一起探讨,互相学习。

小结Android和iOS中LocalNotification

时间: 2024-08-24 13:13:07

小结Android和iOS中LocalNotification的相关文章

Unity在Android和iOS中如何调用Native API

本文主要是对unity中如何在Android和iOS中调用Native API进行介绍. 首先unity支持在C#中调用C++ dll,这样可以在Android和iOS中提供C++接口在unity中调用.利用这一特性,可以扩展unity的功能.例如集成和调用第三方库.同时为了满足对unity接口的一致性,可以考虑在android和iOS上提供相同的接口供C#调用. 这里列举以下两个例子. 1. 1. 以弹出一个覆盖部分屏幕的webview为例来说明如何从C#调用Native接口. 2. 2. 简

Android和iOS中Cocos2dx的横屏竖屏设置

一.横屏.竖屏设置 1.android AndroidManifest.xml文件中, screenOrientation="landscape" 为横屏, screenOrientation="portrait"为竖屏 2.iOS - (NSUInteger) supportedInterfaceOrientations{ #ifdef __IPHONE_6_0 // 横屏显示 // return UIInterfaceOrientationMaskLandsca

张高兴的 Xamarin.Forms 开发笔记:为 Android 与 iOS 引入 UWP 风格的汉堡菜单 ( MasterDetailPage )

所谓 UWP 样式的汉堡菜单,我曾在"张高兴的 UWP 开发笔记:汉堡菜单进阶"里说过,也就是使用 Segoe MDL2 Assets 字体作为左侧 Icon,并且左侧使用填充颜色的矩形用来表示 ListView 的选中.如下图 但怎样通过 Xamarin.Forms ,将这一样式的汉堡菜单带入到 Android 与 iOS 中呢? 一.大纲-细节模式简介 讲代码前首先来说说这种导航模式,官方称"大纲-细节模式"(MasterDetail).左侧的汉堡菜单称为&qu

Android和iOS的委托实现

前段时间写了一部分iOS的程序,其中的委托(delegate)/代理非常强大.今天也就写个简单的委托程序对Android和iOS中委托的原理给大家分享下: 1.项目截图 1.1 第一步:新建接口IProxy(iOS中建的是协议(protocol)含义一样但是还是有区别在这也就不多说了) 1 package com.xx; 2 3 public interface IProxy { 4 String SayHello(String name); 5 } 第二步:新建A委托(代理类) 1 packa

iOS中xib与storyboard原理,与Android界面布局的异同

用文本标记语言来进行布局,用的最多的应该是HTML语言.HTML可以理解为有一组特殊标记的XML语言. 一.iOS中xib与storyboard显示原理 在iOS中主要的布置界面的方式有3种:代码,xib,storyboard. 1. 代码 代码布置界面是万能的,但通常很复杂.布置一个简单的界面可能需要很多行代码,因此十分繁琐. 下面为创建一个按钮的代码,最少也要3行: UIButton *btn = [UIButton buttonWithType:UIButtonTypeContactAdd

结合活体检测,人脸识别在Android、IOS、服务器中的应用

随着深度学习方法的应用,人工智能的发展,人脸识别技术的识别率已经得到质的提升,通过反复开发试验,目前我司的人脸识别技术率已经达到99%.人脸识别技术与其他生物特征识别技术相吃比,在实际应用中具有天然独到的优势:通过摄像头直接获取,在非接触的方式完成识别过程.通过人脸识别与证件识别的比对,目前我司的人脸识别技术已应用在金融.教育.景区.旅运.社保等领域. 人脸识别技术简介 人脸识别技术主要分为两部分: 第一部为前端人脸活体检测技术,主要支持android.ios平台,在前端通过眨眼.张嘴.摇头.点

Base64编解码Android和ios的例子,补充JNI中的例子

1.在Android中java层提供了工具类:android.util.Base64; 里面都是静态方法,方便直接使用: 使用方法如下: Java代码   // Base64 编码: byte [] encode = Base64.encode("Hello, World".getBytes(), Base64.DEFAULT); String enc = new String(encode); Log.d("","base 64 encode = &qu

移动应用开发(IOS/android等)中一个通用的图片缓存方案讲解(附流程图)

在移动应用开发中,我们经常会遇到从网络请求图片到设备上展示的场景. 如果每次都重复发起请求,浪费流量.浪费电量,用户体验也不佳: 将图片持久化到磁盘也不失为一种策略:但每次从文件读取图片也存在一定的io开销,就算采用此策略,我们也需要控制磁盘缓存的容量,以免占用过多系统资源. 其实没有一个方案可以说是完美的方案,只有最适合自己业务需求的方案,才可以说是一个好方案. 我们下面所讲解的方案具备很强的通用性,设计思路简单而清晰: 1.假设每个网络图片的url具有唯一性,如果网络上的图片变化了,会引起输

iOS中的NSTimer 和 Android 中的Timer

首先看iOS的, Scheduling Timers in Run Loops A timer object can be registered in only one run loop at a time, although it can be added to multiple run loop modes within that run loop. There are three ways to create a timer: Use the scheduledTimerWithTimeI