Monday, December 29, 2014

Android Connectivity State Change notifications

The basic intention was to create an app that sends a message to someone automatically when get home or reach office. 

Initially two broadcast relievers were included 
android.net.conn.CONNECTIVITY_CHANGE
and 
android.net.conn.WIFI_STATE_CHANGE

This worked well, but there was a problem that whenever user manually change the wifi switch, the WIFI_STATE_CHANGE get reported immediately. This is a big problem when wifi is getting connected. If we try to read the SSID after getting the WIFI_STAGE_CHANGE callback, it doesn’t give the SSID. To reliably know which SSID the device s connected, Just need to implement the CONNECTIVITY_CHANGE broadcast. The code was something like below 

also in order to use the above broadcasts, below permissions had to be specified in the manifest file 

    
   
   

The boot completed event was just to identify if switched on in a different region than the last reported one. 

public void notifyNetworkChange(Context context, boolean gain)
    {
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, MainActivity.class), 0);

        String ssidStr = "none";
        String bssid = null;
        Log.v("RR:","value for gain is:"+gain);
        if(gain)
        {
            WifiManager wifiManager = (WifiManager)context.getSystemService (Context.WIFI_SERVICE);
            if(wifiManager != null)
            {
                Log.v("RR:","wifiManager not null");
                WifiInfo info = wifiManager.getConnectionInfo ();
                if(info != null) {
                    Log.v("RR:","info not null");
                    ssidStr = info.getSSID();
                    bssid = info.getBSSID();
                }
            }
        }
        if(ssidStr != null)
        {
            Log.v("RR:","ssid not null");
        }
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle(gain? "WiFi Connected" : "WiFi Lost")
                        .setContentText(bssid == null ? "Disconnected from WiFi" :"Connected to "+ ssidStr +" Wifi.");
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());

    }


No comments:

Post a Comment