使用场景
- 监听系统广播
- 广播通信
效果展示
autojs版本号
你将学到以下知识
- 注册广播监听
- 发送广播
- 提取广播发送的值
- 取消广播监听
代码讲解
- 重写
BroadcastReceiver
的onReceive
方法
let receiver = new JavaAdapter(android.content.BroadcastReceiver, { onReceive: function (context, intent) { log(intent); switch (intent.action) { case Intent.ACTION_BATTERY_CHANGED: log("ACTION_BATTERY_CHANGED"); let level = intent.getIntExtra("level", 0); toastLog("当前电量:" + level + "%"); break; case "android.intent.action.yashu": toastLog("牙叔自定义广播"); let value = intent.getStringExtra("author"); log("接收到数据 author: " + value); break; } }, });
- 注册广播
importClass(android.content.IntentFilter); let filter = new IntentFilter(); filter.addAction(Intent.ACTION_BATTERY_CHANGED); filter.addAction("android.intent.action.yashu"); filter.addAction("android.intent.action.激活路飞"); context.registerReceiver(receiver, filter);
- 发送广播
app.sendBroadcast({ action: action, extras: { author: "yashu", }, });
- 取消广播监听
function unregisterReceiver() { if (flag) { receiver && context.unregisterReceiver(receiver); flag = false; toastLog("关闭广播"); } }