CONNECTIVITY_CHANGE deprecated in target of Android N

Pratik Butani picture Pratik Butani · Nov 11, 2016 · Viewed 14.8k times · Source

I am getting warning of deprecated declaration of Broadcast Receiver.

<!-- NETWORK RECEIVER... -->
<receiver android:name=".utils.NetworkUtils" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

WARNING:

Declaring a broadcastreceiver for android.net.conn.CONNECTIVITY_CHANGE is deprecated for apps targeting N and higher. In general, apps should not rely on this broadcast and instead use JobScheduler or GCMNetworkManager.

Is there any other way to use it without deprecated methods?

Answer

Tahir Ferli picture Tahir Ferli · Apr 27, 2017

I had the same problem, i did something like that. It worked for me, i hope it helps.

public class NewActivity extends AppCompatActivity {
    final static String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
    IntentFilter intentFilter;
    MyReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new);

        intentFilter = new IntentFilter();
        intentFilter.addAction(CONNECTIVITY_ACTION);
        receiver = new MyReceiver();

        if(checkForInternet()){
            loadData();
        }else{
            updateUI();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    // Self explanatory method
    public boolean checkForInternet() {
        ConnectivityManager cm =
                (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();
    }

    void loadData(){
        // do sth
    }

    void updateUI(){
        // No internet connection, update the ui and warn the user
    }


    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            String actionOfIntent = intent.getAction();
            boolean isConnected = checkForInternet();
            if(actionOfIntent.equals(CONNECTIVITY_ACTION)){
                if(isConnected){
                    loadData();
                }else{
                    updateUI();
                }
            }
        }
    }
}

Don't add the receiver in the manifest so that it only lives in this activity.