开发者

Android Broadcastlistener to start from code at some specifc event

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 xm开发者_开发技巧l. Any idea how to do this I searched on net but most of example are using xml for this

Regard's Saurabh


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜