application stops working when I try to connect to the internet with broadcasts

Viewed 32

I'm building an application that when started, it checks if the device is connected to the internet, if not the app will show a snack bar telling the user to connect to the internet. On the other hand, if the device is connected to the internet, the app will go to another layout. I want my app to detect if the internet connection was lost after the device was detected to be connected to the internet.

This feature was working only when the app was started and after starting it , if the connection was lost the app wouldn't detect it. Now I have registered the broadcast to the manifest file and the app keeps stopping whenever I change the wifi state. Can you please help?

This is the WifiBroadcastReceiver:

public class WifiBroadcastReceiver extends BroadcastReceiver {
    Context ctx;

    public WifiBroadcastReceiver(){
        super();
    }
    public WifiBroadcastReceiver(Context iCtx){
        ctx = iCtx;
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        NetworkInfo info = intent.getParcelableExtra((WifiManager.EXTRA_NETWORK_INFO));
        if(info != null && info.isConnected()){
           ((Activity)context).setContentView(R.layout.activity_home);
            ctx.unregisterReceiver(this);

        }

This is the main activity:

public class MainActivity extends AppCompatActivity {
    Snackbar wifiSnackbar = null;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        WifiManager wifi = (WifiManager) getSystemService(this.WIFI_SERVICE);
        if (!wifi.isWifiEnabled()) {
            wifiSnackbar = Snackbar.make(findViewById(R.id.activity_main),
                    " not connected", Snackbar.LENGTH_INDEFINITE);
            wifiSnackbar.setAction("Connect", new WifiButtonListener(this));
            wifiSnackbar.show();

            registerReceiver(new WifiBroadcastReceiver(this), new IntentFilter("android.net.wifi.STATE_CHANGE"));


        } else {
    setContentView ( R.layout.activity_home );
            registerReceiver(new WifiBroadcastReceiver(this), new IntentFilter("android.net.wifi.STATE_CHANGE"));

        }

The following is the WifiButtonListener:

public class WifiButtonListener implements View.OnClickListener {

    Context ctx;

    public WifiButtonListener(Context iCtx){
        ctx = iCtx;
    }

    @Override
    public void onClick(View view) {
        WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        wifi.setWifiEnabled(true);
    }
}

And this is the code for the registered receiver in the manifest:

<receiver android:name="WifiBroadcastReceiver" >
    <intent-filter>
        <action android:name="android.net.wifi.STATE_CHANGE" >
        </action>
    </intent-filter>
</receiver>
0 Answers
Related