使用adb 发送广播 动态改变app内的值

前言

在开发过程中有时候我们需要做一些调试工作。可以通过adb发送广播实现。

广播注册

注意最后一个参数,Context.RECEIVER_EXPORTED 这是Android 34以后强制要求的,方便外部发送这个广播。否则会报错

kotlin 复制代码
		 val filter = IntentFilter()
        filter.addAction("com.aaa.bbb.ccc.running.test")
        context?.let {
            mLogger.d("registerReceiver is success")
            it.applicationContext.registerReceiver(testReceiver, filter, Context.RECEIVER_EXPORTED)
        }

广播监听器

kotlin 复制代码
    private var testReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            var appState = intent?.getStringExtra("appState");
            mLogger.w("接收到状态 appState=" + appState)
            if ("error".equals(appState)) {
                recordServiceStared = false;
            }
        }
    }

adb 发射命令

其中 -a 后面是上面的Action。

-es 后面跟的是参数

cmd 复制代码
adb shell am broadcast -a com.aaa.bbb.ccc.running.test --es appState "error"
参数 类型 含义 示例
--es String 添加一个字符串(String)类型的 Extra --es key "value"
--ez Boolean 添加一个布尔值(true/false) --ez key true
--ei Integer 添加一个整数(int) --ei key 123
--el Long 添加一个长整型(long) --el key 1234567890
--ef Float 添加一个浮点数(float) --ef key 3.14
--eu URI 添加一个 URI 类型 --eu key content://media/external/audio/media/1
--ecn ComponentName 添加一个组件名(用于指定接收器) --ecn key com.example.app/.MyReceiver
--eia int\[\] Array 添加整型数组 --eia key 1 2 3
--ela long\[\] Array 添加长整型数组 --ela key 1000 2000 3000
--efa float\[\] Array 添加浮点数组 --efa key 1.1 2.2 3.3
--esa String\[\] Array 添加字符串数组 --esa key "a" "b" "c"
--esn null 添加一个 null 值 --esn key

补充

有时候应用没有退出,这个时候监听器没有生效。需要杀了app,重试

cmd 复制代码
adb shell am force-stop <包名>
相关推荐
Arvin.Angela13 分钟前
MySQL安装及运行环境配置
数据库·mysql·adb
她叫我大水龙16 小时前
ADB 入门指南:安装与常用命令速查手册
adb
wb043072011 天前
仓库搬家不停业——从阿明的“在线换仓库“,看数据库迁移与 Schema 演进的实战方法论
数据库·adb·架构
Mr -老鬼1 天前
EasyClick 入门指南:Shell 命令与 ADB 完全指南
android·adb·自动化·shell·easyclick·易点云测
feifeigo1231 天前
C# ADB 安卓设备数据传输工具
android·adb·c#
2301_773643621 天前
mysql5.7稳定版使用
adb
ULIi096kr2 天前
MySQL解决Too many connections报错:连接数爆满排查、优化与永久解决方案
数据库·mysql·adb
ha_lydms2 天前
AnalyticDB基本概念
mysql·adb·analyticdb
会Tk矩阵群控的小木2 天前
小红书矩阵软件:基于Python+ADB的多设备批量管理自动化脚本实战
运维·python·adb·矩阵·自动化·新媒体运营·个人开发
IT界的老黄牛2 天前
手机 Chrome 远程调试实战:adb + DevTools,localhost 就是你的测试服
chrome·测试工具·adb