Android Broadcast Listener从某些特定事件的代码开始

时间:2010-12-03 09:31:11

标签: android broadcastreceiver

如我所述,我想在某些事件上启动广播接收器,例如按一下按钮,所以我不想在xml中使用它。任何想法如何做到这一点我在网上搜索,但大多数例子都使用xml这个

方面的 SAURABH

1 个答案:

答案 0 :(得分:1)

将此代码放在按钮onClick监听器上。它创建一个接收器,处理程序和intent过滤器,设置接收器应该注册的操作并注册它。不要忘记在完成所有工作后取消注册。

// 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);