Skip to content
PerfectCarl edited this page May 29, 2014 · 17 revisions

Since AndroidAnnotations 3.1

The @Receiver annotation let your code be notified of 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.

Registration

The annotation creates and registers programmatically a BroadcastReceiver during the lifecycle of the parent class (Activity, Fragment or Service) according to the registerAt optional parameter.

@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) {
  }

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

Local broadcasting

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

@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;
  }

}

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Clone this wiki locally