Receiving intents - PerfectCarl/androidannotations GitHub Wiki

Since AndroidAnnotations 3.1

The @Receiver annotation notifies your code about intents without having to manually declare and register a BroadcastReceiver.

@EActivity
public class MyActivity extends Activity {

  @Receiver(actions = "org.androidannotations.ACTION_1")
  protected void onAction1() {
    // Will be called when an org.androidannotations.ACTION_1 intent is sent.
  }

}

The @Receiver annotation supports activities, fragments and services (and intent services).

Registration

The annotation registers and unregisters programmatically a BroadcastReceiver during the lifecycle of the parent class (Activity, Fragment or Service).

The registerAt optional parameter specifies when the registration/unregistration occur. The default value is OnCreateOnDestroy.

The following table lists the values for registerAt, when the registration/deregisration take place and indicates when the value can be used.

Register Unregister Activity Fragment Service
OnCreateOnDestroy onCreate onDestroy x x x
OnStartOnStop onStart onStop x x
OnResumeOnPause onResume onPause x x
OnAttachOnDetach onAttach onDetach x

Here an example of code.

@EFragment
public class MyFragment extends Fragment {

  @Receiver(actions = "org.androidannotations.ACTION_1")
  protected void onAction1RegisteredOnCreateOnDestroy() {
  }

  @Receiver(actions = "org.androidannotations.ACTION_2", registerAt = Receiver.RegisterAt.OnAttachOnDetach)
  protected void onAction2RegisteredOnAttachOnDetach(Intent intent) {
  }

  @Receiver(actions = "org.androidannotations.ACTION_3", registerAt = Receiver.RegisterAt.OnStartOnStop)
  protected void action3RegisteredOnStartOnStop() {
  }

  @Receiver(actions = "org.androidannotations.ACTION_4", registerAt = Receiver.RegisterAt.OnResumeOnPause)
  protected void action4RegisteredOnResumeOnPause(Intent intent) {
  }

}

Local broadcasting

The optional parameter local registers the BroadcastReceiver locally using LocalBroadcastManager instead of the parent context (Activity, Fragment or Service).

The default value for local is false.

@EService
public class MyService extends Service {

  @Receiver(actions = "org.androidannotations.ACTION_1", local = true)
  protected void onAction1OnCreate() {  
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

}
⚠️ **GitHub.com Fallback** ⚠️