martes, 25 de febrero de 2014

Android: Simple broadcast (Notifications)

I now started using broadcast to "hear" when my user in session is null which shouldn't happen but I have worked with application where this did happen and this came handy.

You could use this very same approach when handling errors like no available connection.

Global Approach

The receiver
public class NullUserBroadcastReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
  
  // Do something
 }
}

Session class

If I try to retrieve some value out of the session and find out that my user is null I just call this method.

private void nullUserHandler() {

 // Log if you want...

 Intent intent = new Intent(NullUserBroadcastReceiver.class.getName());

  // The action is the same as the one defined in the manifest
 intent.setAction("my.project.nulluser"); 

  Context context = Application.getContext();
 context.sendBroadcast(intent);
} 

Manifest


  



Note: Local broadcast should be used instead. Check

Local Approach

Activity
@Override
public void onResume() {

  super.onResume();

  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("my-event"));
}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {

  @Override
  public void onReceive(Context context, Intent intent) {

       String message = intent.getStringExtra("message");
    // ...
  }
};

@Override
protected void onPause() {

  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
} 

Some class
private void sendMessage() {

  Intent intent = new Intent("my-event");
  intent.putExtra("message", "data");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
} 

No hay comentarios:

Publicar un comentario