2

I've checked this example of how to handle network connectivity changes: Android Check Internet Connection and found a very nice piece of code of how to handle this changes:

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {

        String status = NetworkUtil.getConnectivityStatusString(context); //some internal class to determinate which type is connected

        Toast.makeText(context, status, Toast.LENGTH_LONG).show();
    }
}

To make this thing work I need to declare this BroadcastReceiver inside my manifest file:

<application  ...>
     ...
        <receiver
            android:name="net.viralpatel.network.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
      ...
</application>

Now I want to update UI, when wifi/mobile data is connected.

I can either make the NetworkChangeReceiver class inner static or external. But what I need is that I can work with my MainActivity UI from public void onReceive. How I can do this?

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
nutella_eater
  • 3,393
  • 3
  • 27
  • 46
  • 1
    Possible duplicate of [How to update UI in a BroadcastReceiver](http://stackoverflow.com/questions/14643385/how-to-update-ui-in-a-broadcastreceiver) – OBX Aug 10 '16 at 15:02
  • 1
    I register this reciever in manifest so I don't have an access to the constructor. – nutella_eater Aug 11 '16 at 07:00

1 Answers1

2

The answer was easy. I don't need to register my broadcast in order to get broadcast about connectivity change:

private BroadcastReceiver networkConnectivityReciever = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            NetworkInfo currentNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (dialog != null) {
                if(currentNetworkInfo.isConnected()){
                    dialog.dismiss();
                    webView.reload();
                }else{
                    dialog.show(((MainActivity) context).getSupportFragmentManager(), "");
                }
            }
        }
    };

@Override
    protected void onResume() {
        super.onResume();
        registerReceiver(networkConnectivityReciever,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

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

And only thing I need in manifest is this:

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
nutella_eater
  • 3,393
  • 3
  • 27
  • 46