alexpfx
alexpfx

Reputation: 6690

How to access broadcast receiver declared in manifest and change some property

I declared a receiver in AndroidManifest.xml:

    <receiver android:name=".receivers.ConnectionUpdateReceiver">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
    </receiver>



public class ConnectionUpdateReceiver extends BroadcastReceiver {
    private Listener listener;

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (networkInfo != null && networkInfo.isConnected()) {
            if (listener != null) {
                listener.onWifiConnected(networkInfo);
            }
        }
    }

    public interface Listener {
        void onWifiConnected(NetworkInfo networkInfo);
    }
}

I have to register a listener to this class. But I don't know how to access it in my Activity class to set the listener property.

I tried to register this receiver at runtime in the usually way in onResume of my activity:

registerReceiver(connectionUpdateReceiver, new IntentFilter(...));

But I don't know what to pass to IntenetFilter constructor, since

android.net.conn.CONNECTIVITY_CHANGE 

is not accessible there.

Upvotes: 2

Views: 1015

Answers (2)

CommonsWare
CommonsWare

Reputation: 1006869

I have to register a listener to this class

That is not possible, as there is no instance of a manifest-registered BroadcastReceiver until a matching broadcast is sent and processed by Android.

I tried to register this receiver at runtime in the usually way in onResume of my activity:

That would only make sense if you got rid of the manifest entry.

But I don't know what to pass to IntenetFilter constructor, since android.net.conn.CONNECTIVITY_CHANGE is not accessible there.

You are welcome to pass in "android.net.conn.CONNECTIVITY_CHANGE" to the IntentFilter constructor. It is also available as ConnectivityManager.CONNECTIVITY_ACTION.

Upvotes: 2

Dvir
Dvir

Reputation: 3139

To listen for the network change events, your activity must register the broadcast receiver that listens for the CONNECTIVITY_CHANGE:

For example:

public void onCreate(Bundle savedInstanceState) {

    registerReceiver(new BroadcastReceiver() {  

        public void onReceive(Context context, Intent intent) {

            Log.i(TAG, "Hey, net?");
        }}, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
}

I hope that support your issue.

Upvotes: 1

Related Questions