0

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

ingsaurabh
  • 15,249
  • 7
  • 52
  • 81

1 Answers1

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);
Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
  • sorry If ask a stupid question but I had to listen for incoming sms and I already extends a class for it and overrided its onCreate does this work in that situation also – ingsaurabh Dec 03 '10 at 09:40
  • of course. And, generally, nothing stops you from checking it right now. – Vladimir Ivanov Dec 03 '10 at 09:42
  • its giving me this The method registerReceiver(SMSReceiver, IntentFilter, null, Handler) is undefined for the type new Handler(){} I used following code SMSReceiver mSmsReceiver = new SMSReceiver(); IntentFilter intentToReceiveFilter = new IntentFilter(); intentToReceiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); this.registerReceiver(mSmsReceiver, intentToReceiveFilter, null, mHandler); – ingsaurabh Dec 03 '10 at 09:47
  • This is the error that I am getting on register receiver line " The method registerReceiver(SMSReceiver, IntentFilter, null, Handler) is undefined for the type new View.OnClickListener(){}" I had used the same syntax that you told me – ingsaurabh Dec 03 '10 at 10:18