Search code examples
javaandroidconstructorbroadcastreceiverthis

Is it possible to use this class instance in the constructor?


It's just something that puzzles me. Is it possible to use the current instance of the class within the constructor?

I've created a BroadcastReceiver that registers itself with the context within the constructor of the BroadcastReceiver. In addition it will unregister again. Is this good style?

Here's my example:

public class MyBroadcastReceiver extends BroadcastReceiver {

    protected Context                       context;
    protected MyOnBroadcastReceivedListener listener;
    protected int                           receiverId;
    protected String                        receiverTag;

    public MyBroadcastReceiver(int receiverId, Context context, MyOnBroadcastReceivedListener listener, String receiverTag) {
        super();

        this.context = context;
        this.listener = listener;
        this.receiverId = receiverId;
        this.receiverTag = receiverTag;

        IntentFilter intentFilter = new IntentFilter(receiverTag);

        context.registerReceiver(this, intentFilter);   // <--- Look at the use of this here
    }

    public void detach() {
        if (context != null) {
            context.unregisterReceiver(this);   // <--- Look at the use of this 
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // ...
        if (listener != null) {
            listener.onBroadcastReceived(receiverId, "Bla", "Blub");
        }
    }
}

Solution

  • Yes, no trouble at all.

    Inside the constructor, the object has been created but still no reference has been returned to the rest of the java code. You can use this without worries.

    Anyway, in some frameworks where some attributes may be initialized automatic (Context Dependent Injection, CDI), it is not possible to fully initialize the class in the constructor (because such attributes are still not available and may be needed). These frameworks rely in that you mark a method as @PostConstruct; after all attributes are set that method will be called (just so you know what it means when you find it).