Android中使用命令 adb shell am broadcast 发送广播。
代码:
注册一个广播接收器,用来监听广播,如果收到了自己监听到的广播,则打印一条log:
public class MyBroadcastReceiverextends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("MyBroadcastReceiver","onReceive: start...");
throw new UnsupportedOperationException("Not yet implemented");
}
}
监听的广播内容在AndroidManifest.xml设置:
让广播接收器MyBroadcastReceiver去监听一条com.chen.broadcasttest.MY_BROADCAST的广播
<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.chen.broadcasttest.MY_BROADCAST"/>
</intent-filter>
</receiver>
MainActivity只打印一条log
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("MainActivity", "starts...");
}
}
启动app后,在cmd中输入
adb shell am broadcast -a com.chen.broadcasttest.MY_BROADCAST com.chen.broadcasttest
其中参数 -a表示action;
com.chen.broadcasttest.MY_BROADCAS是广播接收器想要监听的广播名称
com.chen.broadcasttest是app的包名。在我的环境中,不加入包名则无法发送广播,不知道为什么。
执行:
C:\Users\chen>adb shell am broadcast -a com.chen.broadcasttest.MY_BROADCAST com.chen.broadcasttest
Broadcasting: Intent { act=com.chen.broadcasttest.MY_BROADCAST flg=0x400000 pkg=com.chen.broadcasttest }
Broadcast completed: result=0
Android Studio中logcat的结果:
2019-08-09 09:30:11.480 20631-20631/com.chen.broadcasttest D/MyBroadcastReceiver: onReceive: start...
网友评论