这期内容当中小编将会给大家带来有关Android中怎么实现动态注册,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
第一种写法:
首先新建一个Java类,通过"New/Other/Broadcast Receiver",命名为MyReceiver,添加以下内容
public static String ACTION="learnbroadcastreceive.MyReceive";
然后添加
public MyReceive{public void OnReceive(Context context,Intent intent){Toast.maetText(context,"收到一条广播",toast.LENGTH_LONG).show();}}
然后在MainAcitivity中添加
private Myreceiver receiver=null;
然后添加
public void registeMyReceiver(View view){if(receive==null){receive=new MyReceiver();registerReceiver(receiver,new intentFilter(MyReceive.Action));}}public void unRegisterReceiver(){if (receive!=null){unregistReceive(receiver);receive=null;}}public void sendBc(View view){sendBroadcast(new Intent(this.MyReceive.ACTION));}
然后在xml中修改相应的部分即可
第二种写法:
第二种写法,其实是将所有代码都放在MainAcitivity中
private IntentFlier intentfilerprivate MyReceiver receive
onCreate中添加
receive=new MyReceiver();registerReceiver(receiver,new intentFilter(MyReceive.Action));
新建
public void onDestroy(){super.onDestroyunregistReceive(receiver);}public void OnReceive(Context context,Intent intent){Toast.maetText(context,"收到一条广播",toast.LENGTH_LONG).show();}
上述就是小编为大家分享的Android中怎么实现动态注册了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注编程网行业资讯频道。