Codename One前台LocalNotification:振动与悬浮通知问题及解决
解决Codename One LocalNotification的前台振动与悬浮显示问题
问题说明
应用在前台显示LocalNotification时遇到两个问题:
- 接收通知时无法触发振动(已自行解决)
- 通知仅在状态栏显示图标,需下拉状态栏才能查看内容,无法显示悬浮通知
现有通知实现代码如下:
LocalNotification ln = new LocalNotification(); ln.setId("LnMessage"); ln.setAlertTitle("Welcome"); ln.setAlertBody("Hello world!"); Display.getInstance().scheduleLocalNotification(ln, System.currentTimeMillis() + 10, LocalNotification.REPEAT_NONE);
振动问题已解决方案
- 右键项目,依次进入
codename one>CodenameOne settings>advanced settings>Build hints - 添加构建提示:
- Key:
android.permission.VIBRATE - Value:
true
- Key:
- 完成配置后调用
Display.getInstance().vibrate(1000);即可正常触发振动
悬浮通知解决方案
要实现Android平台的悬浮通知(Heads-up Notification),需针对LocalNotification做以下配置:
1. 适配Android 8.0+的通知通道
Android Oreo及以上版本要求通知必须归属到指定通道,高优先级通道才能触发悬浮通知:
if (Display.getInstance().getPlatformName().equals("Android")) { Display.getInstance().callSerially(() -> { try { // 反射创建高优先级通知通道 String channelId = "high_priority_channel"; Class<?> notificationManagerCls = Class.forName("android.app.NotificationManager"); Object notificationManager = Display.getInstance().getContext().getSystemService("notification"); Class<?> channelCls = Class.forName("android.app.NotificationChannel"); Object channel = channelCls.getConstructor(String.class, CharSequence.class, int.class) .newInstance(channelId, "高优先级通知", 4); // 4对应IMPORTANCE_HIGH notificationManagerCls.getMethod("createNotificationChannel", channelCls) .invoke(notificationManager, channel); // 为LocalNotification绑定通道ID ln.setAndroidChannelId(channelId); } catch (Exception e) { e.printStackTrace(); } }); }
2. 设置通知优先级(适配Android 7.1及以下)
对于旧版本Android,直接设置通知优先级为高:
ln.setAndroidPriority(2); // 2对应PRIORITY_HIGH
3. 配置系统权限
部分Android设备需要手动开启应用的「显示悬浮窗」权限,可引导用户前往设置开启,或通过代码跳转设置页面:
if (Display.getInstance().getPlatformName().equals("Android")) { Display.getInstance().callSerially(() -> { try { Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION, android.net.Uri.parse("package:" + Display.getInstance().getContext().getPackageName())); ((android.app.Activity)Display.getInstance().getContext()).startActivityForResult(intent, 1001); } catch (Exception e) { e.printStackTrace(); } }); }
注意:悬浮通知的显示还受系统全局设置影响,部分定制ROM可能限制第三方应用的悬浮权限,需确保系统设置中允许该应用显示悬浮通知。
内容的提问来源于stack exchange,提问作者Alejandro Fernandez
相关产品推荐
相关产品推荐

