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