回答
在 Hamibot 中显示通知,需要调用 Android 原生的 NotificationManager。如果你指的是在状态栏显示一条普通通知,可以直接使用以下代码。如果你指的是绑定前台服务(Foreground Service)的常驻通知,需要额外配置 startForeground() 和 FOREGROUND_SERVICE 权限,一般脚本自动化场景使用普通通知即可满足需求。
以下是完整且兼容 Hamibot(Rhino 1.7.15)的通知显示代码:
// 文档地址 https://docs.hamibot.com/
importClass(android.app.Notification);
importClass(android.app.NotificationManager);
importClass(android.app.NotificationChannel);
importClass(android.content.Context);
importClass(android.graphics.Color);
function showNotification(title, content) {
var channelId = 'hamibot_script_channel';
var channelName = 'Hamibot 脚本通知';
var notificationId = 1001;
var manager = context.getSystemService(Context.NOTIFICATION_SERVICE);
// Android 8.0 及以上必须创建通知渠道
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
var channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.setLightColor(Color.BLUE);
channel.enableVibration(true);
manager.createNotificationChannel(channel);
}
var builder;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
builder = new Notification.Builder(context, channelId);
} else {
builder = new Notification.Builder(context);
}
builder.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(title)
.setContentText(content)
.setAutoCancel(true)
.setWhen(new Date().getTime());
manager.notify(notificationId, builder.build());
log('通知已发送: ' + title);
}
showNotification('任务完成', 'Hamibot 脚本已执行完毕,请查看结果。');
关键说明
- Android 8.0+ 渠道机制:高版本 Android 强制要求使用
NotificationChannel,代码已内置兼容逻辑,无需手动修改。 - 图标配置:
setSmallIcon()必须设置,否则通知不会显示。示例使用了系统内置图标android.R.drawable.ic_dialog_info,你也可以替换为自定义资源 ID。 - 点击行为:当前通知点击后会自动消失(
setAutoCancel(true))。如需点击跳转指定页面或触发脚本逻辑,需配合PendingIntent使用。 - 运行环境:
context是 Hamibot 全局提供的 Android Context 对象,可直接调用系统服务。
注意事项
- 通知显示不需要额外申请权限,但部分定制 ROM(如 MIUI、ColorOS)可能默认关闭了应用的通知权限。如果代码执行后未显示,请手动在系统设置中为 Hamibot 开启通知权限。
- 代码已严格遵循 Rhino 引擎规范,未使用箭头函数、默认参数等不兼容语法,可直接复制到 Hamibot 脚本中运行。
如果你有点击通知触发特定脚本逻辑、或需要常驻前台服务通知的需求,可以告诉我具体场景,我会提供对应的实现方案。
ℹ️ 内容由 AI 生成,可能不准确,请注意核实