Lilian Sorlanski
Lilian Sorlanski

Reputation: 435

How to set a TextView visibile in activity and not in CustomBroadcastReceiver class?

I have the following custom broadcast receiver class to check if wi-fi is connected:

public class CustomBroadcastReceiver extends BroadcastReceiver {
    private TextView textView;

    public NetworkStateReceiver(TextView textView) {
        this.textView = textView;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        for (Network network : connectivityManager.getAllNetworks()) {
            NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
            if (networkInfo != null) {
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    boolean isWifiConnected = networkInfo.isConnected();
                    if (isWifiConnected) {
                        textView.setVisibility(View.VISIBLE);
                    }
                }
            }
        }
    }
}

As you can see, I'm passing to the constructor a TextView object so it can be set visible if the the device is connected to wi-fi. In my MainActivity I'm creating an object like so:

CustomBroadcastReceiver receiver = new CustomBroadcastReceiver(textView);

The problem is that I don't want to make this operation on text view in this class, I want to make it in MainActivity class. How can I solve this?

Upvotes: 1

Views: 27

Answers (1)

David Wasser
David Wasser

Reputation: 95578

Create an interface that contains a single method like setIsConnected(Boolean)

In MainActivity, implement this interface. The method will be called from your BroadcastReceiver and in this method you can do whatever you want with the UI.

Have the constructor of the BroadcastReceiver take the interface as a parameter instead of a TextView.

In onReceive(), call setIsConnected() on the interface with the boolean depending on the state of the WIFI.

Upvotes: 1

Related Questions