Android Broadcastlistener to start from code at some specifc event

孤人 提交于 2019-12-12 03:43:53

问题


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

Regard's Saurabh


回答1:


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


来源:https://stackoverflow.com/questions/4344136/android-broadcastlistener-to-start-from-code-at-some-specifc-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!