我正在实现一个监听的脚本,以下是我的源码:
auto.waitFor();
console.show();
events.observeNotification();
events.onNotification(function (notification) {
console.log(notification.getText());
});
setInterval(function () {}, 1000);
运行脚本是报错:
Wrapped android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? (6888413349fcc6ce5492002d.js#8)
Wrapped android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
at 6888413349fcc6ce5492002d.js:8:0
回答
文档地址 https://docs.hamibot.com/
这个错误是由于通知权限未正确开启导致的。当调用 events.observeNotification()
时,如果系统需要跳转到通知权限设置界面,会因为上下文环境不符合要求(需要 FLAG_ACTIVITY_NEW_TASK 标志)而崩溃。
解决方案:
-
手动开启通知权限
打开系统设置 → 应用管理 → Hamibot → 通知权限 → 启用通知监听。 -
修改代码规避异常
使用try-catch
捕获异常并提示用户手动操作:auto.waitFor(); console.show(); try { events.observeNotification(); events.onNotification(function (notification) { console.log(notification.getText()); }); } catch (e) { toast("请手动开启通知权限:设置→应用管理→Hamibot→通知权限"); } setInterval(function () {}, 1000);
-
避免自动跳转逻辑
删除或注释掉会触发系统设置跳转的代码逻辑,直接通过提示引导用户操作。
关键点说明:
events.observeNotification()
依赖通知服务,未开启时会尝试跳转设置界面,但受限于系统限制(非 Activity 上下文),导致异常。- 通过
try-catch
可以捕获异常并避免崩溃,同时提供明确的权限开启指引。