通过adb命令和广播形式传入参数到程序中
目的:程序中要接收通过adb广播传来的包名,包名以字符串形式传入
命令:
adb shell am broadcast -a <action> --es string "字符串"
代码:动态注册监听器,不用再manifest文件中注册
第一步:在onCreat方法中先注册监听器
IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("mobi.acpm.inspeckage.MyReceiver"); //添加事件 MyReceiver myReceiver = new MyReceiver(); getActivity().registerReceiver(myReceiver, intentFilter);
第二步:实现MyReceiver
public class MyReceiver extends BroadcastReceiver { public MyReceiver(){ } @Override //Once boot completed,start server public void onReceive(Context context, Intent intent) { //从这里可以看到是否接受到了广播 String action = intent.getAction(); if(action.equals("mobi.acpm.inspeckage.MyReceiver")) { //loadSelectedApp(intent.getStringExtra("string")); //getStringExtra就是获取传入的字符串 Toast.makeText(context, "" + intent.getStringExtra("string"), Toast.LENGTH_SHORT).show(); } } }