Thursday, December 25, 2014

Android Getting connection state changes

The intention was to create an app which sends a message to my wife when i reach home or when reach office network. For this, below are the items done 


               
                   
                   
               
           

Now create the class the extends the broadcast receiver. 

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable()) {
            // Do something
            Log.d("RR::Netowk Available ", "Flag No 1");
            Toast.makeText(context, "Network Available Do operations", Toast.LENGTH_LONG).show();
        }
        else
        {
            Toast.makeText(context, "Network Not available.", Toast.LENGTH_LONG).show();
        }
    }
}

However, the above did not really work out as expected. It was not getting the broadcast receiver call backs. Yet to investigate more on this. 

Finally, found the root cause,  the error was simple, that the receiver xml tag was not right under the application element in the AndroidManifest.xml file. Once i made this, it was able to properly get invoked on network state changes! 

No comments:

Post a Comment