Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android N not sending android.net.conn.CONNECTIVITY_CHANGE broadcast?

I have defined a receiver in a sandbox Android N application:

<receiver
    android:exported="true"
    android:name="com.sandboxapplication.NetworkReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

It's rather simple:

public class NetworkReceiver extends BroadcastReceiver {
    private static final String TAG = NetworkReceiver.class.getName();
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "Received Network Change event.");
    }
}

This receiver is working fine if in my build.gradle file my targetSdkVersion is 23. However, if I set my targetSdkVersion to 24, the receiver never receives anything. In fact if I place a debug break point in my receiver Android Studio gives me the visual indication that it looks like the class is never even loaded into memory.

Did I miss something very basic in the Android N documentation? Is there a new way to detect connectivity change events?

like image 385
DanMD Avatar asked Aug 22 '16 10:08

DanMD


People also ask

How to stop broadcast receiver in android?

To stop receiving broadcasts, call unregisterReceiver(android. content. BroadcastReceiver) . Be sure to unregister the receiver when you no longer need it or the context is no longer valid.

How to declare broadcast receiver in manifest?

There are two ways to make a broadcast receiver known to the system: One is declare it in the manifest file with this element. The other is to create the receiver dynamically in code and register it with the Context. registerReceiver() method.


2 Answers

Use this code to register receiver in your Activity or in Application class

IntentFilter intentFilter = new IntentFilter(); 
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTI‌​ON); 
registerReceiver(new NetworkConnectionReceiver(), intentFilter); 

Where NetworkConnectionReceiver is a class extended by BroadcastReceiver. Just add this class in your app and perform action in onReceive(Context context, Intent intent) method.

Note: If you register this receiver in an Activity, don't forget to unregister it.

like image 199
Ambar Jain Avatar answered Oct 13 '22 11:10

Ambar Jain


Apps targeting Android N (Nougat) do not receive CONNECTIVITY_ACTION broadcasts, even if they have manifest entries to request notification of these events. Apps that are running can still listen for CONNECTIVITY_CHANGE on their main thread if they request notification with a BroadcastReceiver.

To see what changed in Android N (Nougat). Please refer below link. Android N Behaviour Changes

like image 32
Kalpesh Patel Avatar answered Oct 13 '22 11:10

Kalpesh Patel