Android的Broadcastlistener从code。在一些specifc活动启动 [英] Android Broadcastlistener to start from code at some specifc event
本文介绍了Android的Broadcastlistener从code。在一些specifc活动启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
作为的问题,我想开始对某些事件的广播接收器描述说,点击一个按钮,所以我不想在XML中使用它。任何想法如何做到这一点我搜索净,但大多数的例子都使用这个XML
As described in question I want to start a broadcast receiver on some event say a button click so I don't want to use it in xml. Any idea how to do this I searched on net but most of example are using xml for this
方面的
SAURABH
Regard's Saurabh
推荐答案
将这个code到您的按钮的onClick监听器。它创建了一个接收器,处理器和意图过滤器,设置你的接收机应进行注册和注册它的动作。不要'忘了注销其所有的工作都会做了。
Put this code to your button onClick listener. It creates a receiver, handler, and intent filter, sets the action your receiver should be registered for and register it. Dont' forget to unregister it after all the work will be done.
// this goes before onCreate()
private static final String ACTION = "YOUR_ACTION_HERE";
/// in button listener:
Handler mHandler = new Handler();
BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Handle reciever
String mAction = intent.getAction();
if(mAction.equals(ACTION) {
// Do your thing
}
}
IntentFilter intentToReceiveFilter = new IntentFilter();
intentToReceiveFilter.addAction(ACTION);
this.registerReceiver(mIntentReceiver, intentToReceiveFilter, null, mHandler);
这篇关于Android的Broadcastlistener从code。在一些specifc活动启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文