Tuesday, August 25, 2015

Enable or Disable an Android Button at Runtime (with network check)

While I was working with an Android application for a customer, there was a use case to disable a button at runtime and enable it after some action. This is straightforward in Android. Below I show the XML for the button, how to reference it in your activity, and how to enable/disable it based on network status using a small NetworkUtil helper (link provided).

Button XML

Use a standard Button in your layout (example):

<Button
    android:id="@+id/about_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="64dp"
    android:text="@string/about_label" />

Reference the Button in your Activity

In onCreate(), find the button and keep a reference. Using the Button type makes intentions clearer and provides button-specific APIs:

Button aboutButton = findViewById(R.id.about_button);

Note: on older Android APIs you may need a cast, e.g. Button aboutButton = (Button) findViewById(R.id.about_button);, but with modern SDKs the generic signature is available.

Enable and disable the Button

You can enable or disable a View (including Button) using setEnabled(true/false):

  • To enable:
aboutButton.setEnabled(true);
  • To disable:
aboutButton.setEnabled(false);

Disabling a button via setEnabled(false) also prevents it from receiving click events. For improved UX you may also want to change the visual appearance (alpha, color) so users can see the disabled state:

aboutButton.setEnabled(false);
aboutButton.setAlpha(0.5f); // visual cue
// when enabling back:
aboutButton.setEnabled(true);
aboutButton.setAlpha(1f);

Remember to make UI changes on the main thread.

Enable based on network status (using NetworkUtil)

I use a small helper class NetworkUtil to check network connectivity. You can download it here:

Create an instance and call getConnectivityStatus with a Context. Example usage (corrected and formatted):

NetworkUtil net = new NetworkUtil();
int status = net.getConnectivityStatus(getApplicationContext());
if (status != 0) {
    aboutButton.setEnabled(true);
    aboutButton.setAlpha(1f);
} else {
    aboutButton.setEnabled(false);
    aboutButton.setAlpha(0.5f);
}

Notes:

  • The original article had a typo setEnabled(flase); ensure you use false.
  • The meaning of status values depends on NetworkUtil implementation. Keep your app logic consistent with that helper's return values.

Accessibility and UX considerations

  • When disabling interactive elements, ensure assistive technologies can convey the change. Consider adding content descriptions for non-textual controls and ensuring focus behavior is appropriate.
  • Adjust visual indicators (alpha, color) so users can perceive the disabled state.

Alternatives and further improvements

  • For production apps consider using Android's ConnectivityManager and NetworkCallback APIs to observe connectivity changes rather than polling.
  • In modern architectures, expose connectivity status via LiveData, Flow, or other observable streams and observe from the Activity/Fragment to update UI reactively.

NetworkUtil download link (same as above): https://sites.google.com/site/karjolblogs/downloads/NetworkUtil.java?attredirects=0&d=1

That’s it. Happy Coding..

Saturday, August 22, 2015

Android: Detect when an AdMob ad has loaded (AdListener + network check)

Overview

In some Android apps you need to take action when an AdMob ad successfully loads and a different action when it does not. This post shows how to detect both cases using AdView.setAdListener and how to avoid requesting ads when there is no network connection.

The original examples and links are preserved below, followed by a short checklist and an updated example to match newer Google Mobile Ads SDK patterns.


Detecting ad load with AdListener (original example)

Use AdView.setAdListener and override onAdLoaded() and onAdFailedToLoad(…). This is the code from the original post:

ad.setAdListener(new AdListener() {            
    @Override
    public void onAdLoaded() {
        Log.d(TAG, "Ad Received");
        //Code implementation if the ad is loaded
        ………
        ………
    }

    @Override
    public void onAdFailedToLoad(int errorcode) {
        Log.d(TAG, "Ad Not Loaded Received");
        //Code implementation if the ad is NOT loaded
        ………
        ………
    }
});

Explanation

  • onAdLoaded(): called when the ad has been successfully loaded into the AdView — put the code you want executed on success here (e.g., show the ad container).
  • onAdFailedToLoad(…): called when the ad request failed — put fallback behavior here (e.g., hide the ad container, log the error, schedule a retry).

Note: the snippet above is the original form used in the article. Later SDK versions changed the parameter type for onAdFailedToLoad; see the updated example below.


Check network connectivity before requesting ads

The article recommends checking network status before attempting to fetch ads so the app does not continuously try to fetch when offline. You can use ConnectivityManager as shown in the official Android docs: https://developer.android.com/training/basics/network-ops/managing.html

Original illustrative code from the post:

private static final String DEBUG_TAG = "NetworkStatusExample";
...
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConn = networkInfo.isConnected();

networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = networkInfo.isConnected();

Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn);
Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn);

The author provided a helper class NetworkUtil; you can download it here: https://sites.google.com/site/karjolblogs/downloads/NetworkUtil.java?attredirects=0&d=1

Use it like this (from the original post):

NetworkUtil net = new NetworkUtil();
int status = net.getConnectivityStatus(getApplicationContext());
if (status != 0) {
    // Code if the network connection is there
    ad.loadAd(new AdRequest.Builder().build());
    ad.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            Log.d(TAG, "Ad Received");
            // code when the ad loaded
        }

        @Override
        public void onAdFailedToLoad(int errorcode) {
            Log.d(TAG, "Ad Not Loaded Received");
            // code if the ad loading is failed
        }
    });
} else {
    // Code if the network connection is NOT there
}

Required permission

To check network status at runtime you must have the following permission in AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

(Ensure your NetworkUtil implementation relies on this permission.)


Updated notes for newer Google Mobile Ads SDKs

The post originates from 2015; Google Mobile Ads SDK APIs have evolved. Two practical points to add for modern readers:

  • Initialize the Mobile Ads SDK early in your app (for example in Application.onCreate()):
// Example initialization (SDK versions may vary)
MobileAds.initialize(context, initializationStatus -> { /* optional callback */ });
  • In recent SDK versions, onAdFailedToLoad has a different signature and provides richer error information (for example via LoadAdError). Here is an example that shows both an updated listener and how to inspect the error for troubleshooting:
// Updated example (SDK may require different imports; check your SDK docs)
adView = findViewById(R.id.adView);
MobileAds.initialize(this, initializationStatus -> {});
AdRequest adRequest = new AdRequest.Builder().build();

adView.setAdListener(new AdListener() {
    @Override
    public void onAdLoaded() {
        Log.d(TAG, "Ad Received");
        // show ad view or update UI
    }

    @Override
    public void onAdFailedToLoad(LoadAdError adError) {
        Log.d(TAG, "Ad Not Loaded Received: " + adError.toString());
        // Inspect adError.getCode() or adError.getMessage() for debugging
        // hide ad view or implement retry/backoff
    }
});

adView.loadAd(adRequest);

Refer to the official Google Mobile Ads documentation for the SDK version you use (the original article linked the AdView docs: https://developers.google.com/android/reference/com/google/android/gms/ads/AdView).


Practical tips and recommended behavior

  • Hide the ad container when no ad is available to avoid empty space in your UI.
  • Implement exponential backoff for retries rather than continuous immediate retries.
  • Log errors with enough detail to diagnose (error code/message) but avoid leaking sensitive user data.
  • Ensure you comply with AdMob policies when changing ad behavior.

References and downloads


Final notes

That’s it. Happy Coding..

Friday, August 21, 2015

Integrating Google AdMob Banner Ads in Android (Step‑by‑Step)

I was wondering how to integrate Ads from Google in my Android applications. AdMob is a widely used mobile advertising platform that you can integrate with your Android app fairly easily.

In this post you will learn how to show AdMob banner ads in your Android application. This write‑up is divided into three parts:

  • Getting an Ad Unit ID from the AdMob site
  • Installing Google Play Services in the Android SDK (Eclipse instructions as originally used)
  • Integrating AdSense/AdMob code into your Android app

Note: this article preserves the original Eclipse/SDK Manager workflow used when it was written. Most developers today should use Android Studio and the Google Mobile Ads SDK via Gradle. See the “Modern tooling” note at the end for guidance.

1) Getting Ad Unit Id from the AdMob site

  1. Go to the AdMob site: https://www.google.com/admob/
  2. Create a new account (or log in if you already have one).
  3. Select the “Monetize new app” option.
  4. Search your Android application (from Google Play) or add the app details manually.

AdMob step 1

  1. After filling the app information, AdMob shows setup instructions and lets you create an ad unit and get the Ad Unit ID.

AdMob select app

  1. Your app will be added in AdMob. In the Monetize tab you can select the app, create a banner ad, and copy the Ad Unit ID (it looks like):
ca-app-pub-50xxxx69xxxxxxxx/34xxxxxxxx
  1. You will use this Ad Unit ID in your project later.

2) Installing Google Play Services in Android SDK (Eclipse era instructions)

These steps describe the older Eclipse + SDK Manager workflow used when this post was written.

  1. Open Eclipse and go to Window -> SDK Manager.

SDK Manager

  1. In the packages list select Extras -> check Google Play Services and install it.

Install Google Play Services

  1. Import the Google Play Services project/library into your workspace.
  2. Add the Google Play Services library to the project where you want to integrate AdMob.

Add library to project

3) Integrating AdSense / AdMob code into the Android app

  1. Open your layout XML and add the Ads XML namespace (required to use ads: attributes):
xmlns:ads="http://schemas.android.com/apk/res-auto"
  1. Add an AdView to the layout. Example:
<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ads:adSize="BANNER"
    ads:adUnitId="YOUR_AD_UNIT_ID" />
  1. In your Activity Java file initialize the AdView object:
AdView ad = (AdView) findViewById(R.id.adView);
  1. Load an ad from Google:
ad.loadAd(new AdRequest.Builder().build());
  1. Modify AndroidManifest.xml: add required permissions, metadata for Google Play Services, and the AdActivity entry.

Add permissions:

<!-- Used to request banner ads. -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Used to avoid sending an ad request if there is no connectivity. -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Add Google Play Services metadata (inside ):

<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

Add the AdActivity which is required to show ad overlays:

<activity android:name="com.google.android.gms.ads.AdActivity"
    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />

The original article includes a sample manifest; here is the final manifest excerpt reproduced for reference:

xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.marutsoft.sudoku"
    android:versionCode="3"
    android:versionName="1.3">

    <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="19"/>

    <!-- Used to request banner ads. -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- Used to avoid sending an ad request if there is no connectivity. -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity android:name="com.marutsoft.sudoku.Splash"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Activity required to show ad overlays. -->
        <activity android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />

    </application>

</manifest>

Now run your application and check that the Google ad is shown in the Activity where you have added it. Please note you need to have internet connectivity.

Also you can add code to check the availability of connectivity and then load the ad — we will add that part in my next blog.

That’s it. Happy Coding..


Modern tooling note (recommended)

This article preserves the original Eclipse instructions. If you are using Android Studio (recommended):

  • Use the Google Mobile Ads SDK via Gradle (implementation 'com.google.android.gms:play-services-ads:…') and follow current AdMob docs.
  • Newer SDKs require an application-level AdMob App ID meta‑data entry in AndroidManifest.xml and explicit MobileAds.initialize(…) in your application code before loading ads. Also always use test ads or register test device IDs while developing.

If you want, I can provide a modern, Android Studio + Gradle version of these steps with updated code samples and a short checklist for publishing with AdMob.

Thursday, August 20, 2015

How to Upload and Make a Downloadable ZIP File in Blogger (Using Google Sites)

I wanted to make some files available to download for my readers. Blogger does not provide native attachments, but you can host files elsewhere and link to them from your blog. Below I show how I used Google Sites and the File Cabinet page template to host files and then link to them from a Blogger post.

Quick summary

Host the file on Google Sites using the File Cabinet page template, right-click the Download link to copy the file URL, then paste that URL into your Blogger post as a link (example below).

What you need

  • A Google account
  • A Google Site (create one if you don’t have it)
  • The file(s) you want readers to download (ZIP, PDF, etc.)

Steps

1. Go to Google Sites

Login with your Google account. If you don’t have a Google Site yet, create one using the CREATE button.

2. Create a new site

Choose a template, fill in the site name and location, complete the CAPTCHA if prompted, and click CREATE.

3. Add a new page using the File Cabinet template

Create a new page and select the File Cabinet page template (this template is designed to host downloadable files).

File cabinet template image

4. Upload files

Use the File Cabinet page controls to add the files you want to provide for download.

Upload files image

5. Copy the file link

After uploading, locate the Download link for the file. Right-click the Download link and choose "Copy link address" to copy the direct URL to the file.

Copy link address image

6. Add the link to your Blogger post

In the Blogger post editor, add a link to the text where readers will click to download. You can paste the URL directly using the editor's link tool, or use raw HTML like this:

<a href="PASTE_COPIED_LINK_HERE">Download ZIP</a>

If your editor supports it, select a descriptive anchor text such as "Download ZIP — contains sample code".

7. Publish and test

Publish your Blogger post and click the link to confirm the file downloads correctly. If users report access issues, check the sharing/permission settings on the Google Site (make sure the file/page is publicly accessible if you want anyone to download it).

Helpful screenshots

Create site screenshot

Created file cabinet screen

Notes and alternatives

  • Google Sites UI may change over time — if you cannot find a File Cabinet template, look for a page template that supports file uploads or use another file-hosting service.
  • As an alternative, you can host files in Google Drive or another file host and link to them from Blogger. If you use a different host, be sure to verify public access permissions before publishing.

That’s it. Happy Coding..

Thursday, August 13, 2015

MySQL: Query by Month & Day in PHP — Find Today's Birthdays and Anniversaries

While we were working on a web portal, one of the use cases was to send greeting emails to members on their birthday and anniversaries.

Problem

We needed to get all email IDs from the database whose birthday or anniversary is today. The script runs from a cron job every morning at 9:00. Birth and anniversary dates in the database are stored in YYYY-MM-DD format. If you compare the full date with today (including year) you won't get matches because the years differ.

Simple idea

Query only by month and day. First, get today's month and day in PHP (without the year), then match the date column in the database by month-day.

Original code (as published)

The original article used this approach. (Note: this preserves the author's original example.)

//Setting the time zone
 date_default_timezone_set("Asia/Kolkata");

//Get today's date without year
 $today=date('m-d');
 echo  $today;

//add "%-" to the today's date in the place of year
 $today1= "%-".$today;
 echo $today1;

//Now write the SQL query using LIKE statement

//Note members is the table and dob&anniversary are cloumns.

$query_res="SELECT fname,email FROM `members` WHERE `dob` LIKE '$today1' or `anniversary` LIKE '$today1'";
$result_res=mysql_query($query_res);


while($row_res=mysql_fetch_array($result_res))
{
//code to send the email
}

Why this works

Dates stored as 'YYYY-MM-DD' will end with '-MM-DD'. By prepending '%-' to the month-day string you match the tail of the date string. Example: for today = '08-21', '%-08-21' matches '1987-08-21' or '2010-08-21'.

Important notes and improvements (do this instead)

  1. Deprecated API: The original code uses the old mysql_* API. These functions are removed in modern PHP versions. Use mysqli or PDO with prepared statements.
  2. Performance: Using a function or LIKE on a date column prevents MySQL from using an index. On large tables this can become slow. Consider storing a computed month-day column (or separate month and day columns) that you can index, or use a generated (virtual/stored) column in MySQL 5.7+.
  3. Correct SQL alternatives: Rather than string matching with LIKE, use DATE_FORMAT or the MONTH()/DAY() functions for clarity.
  4. Edge cases: Decide how to handle Feb 29 birthdays on non-leap years (send on Feb 28 or skip). Also confirm server timezone vs. PHP timezone.
  5. Security: Even though this query comes from server-side logic, always prefer prepared statements to avoid injection risks if you later introduce user input.

Recommended SQL approaches

Option A — DATE_FORMAT (clear and direct):

SELECT fname, email
FROM members
WHERE DATE_FORMAT(dob, '%m-%d') = '08-21'
   OR DATE_FORMAT(anniversary, '%m-%d') = '08-21';

Option B — MONTH() and DAY():

SELECT fname, email
FROM members
WHERE MONTH(dob) = 8 AND DAY(dob) = 21
   OR MONTH(anniversary) = 8 AND DAY(anniversary) = 21;

Both of these use functions on the column (so they will not use a plain index on the date column). To improve performance, add a computed/generated column or store month/day separately and index that column.

Modern, secure PHP example using PDO and DATE_FORMAT

// Set timezone
date_default_timezone_set('Asia/Kolkata');

// Get today's month-day
$md = date('m-d'); // e.g. '08-21'

// Using PDO and a parameterized query with DATE_FORMAT
$dsn = 'mysql:host=DB_HOST;dbname=DB_NAME;charset=utf8mb4';
$user = 'DB_USER';
$pass = 'DB_PASS';

try {
    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);

    $sql = "SELECT fname, email FROM members
            WHERE DATE_FORMAT(dob, '%m-%d') = :md
               OR DATE_FORMAT(anniversary, '%m-%d') = :md";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([':md' => $md]);

    while ($row = $stmt->fetch()) {
        // code to send the email
        // $row['fname'], $row['email']
    }
} catch (PDOException $e) {
    // handle error (log it)
    error_log($e->getMessage());
}

Example using a computed column for better performance

If you have MySQL 5.7+ you can create a generated column and index it:

ALTER TABLE members
  ADD COLUMN md CHAR(5) GENERATED ALWAYS AS (DATE_FORMAT(dob, '%m-%d')) VIRTUAL,
  ADD INDEX (md);

Then query with an equality on md (this can use the index):

SELECT fname, email FROM members WHERE md = '08-21';

Or maintain a small VARCHAR column populated at insert/update time with the month-day to get an indexable column on older MySQL versions.

Handling Feb 29

Decide whether Feb 29 birthdays should receive greetings on Feb 28 during non-leap years. Implement that logic in PHP if desired:

$md = date('m-d');
if ($md === '02-28' && !date('L')) { // not a leap year
    // also include '02-29' birthdays
}

Cron and timezone

  • Make sure the server timezone and PHP timezone are correct for your audience. The script will use PHP's timezone setting when calling date().
  • Cron runs in the system timezone by default — ensure alignment or use UTC.

Final notes

  • Keep the original simple approach if your table is small and traffic is low. For production systems, prefer PDO/mysqli and consider an indexed computed column for scalability.

Happy Coding..

Wednesday, August 12, 2015

How to Determine Connectivity Status in Android — ConnectivityManager & NetworkCapabilities

While developing Android applications, a common use case is to schedule regular updates of application data from Internet resources, cache data, or execute long-running downloads. But if you aren't connected to the Internet, or the connection is too slow to complete your download, you should avoid waking the device or starting a network operation. So before you trigger any of these activities you need to check the connectivity status.

You can use the ConnectivityManager to check that you're actually connected to the Internet, and if so, what type of connection is in place (Wi‑Fi, cellular, ethernet, etc.). The Android docs are here: https://developer.android.com/reference/android/net/ConnectivityManager

Permissions

Make sure the following permission is declared in AndroidManifest.xml so your app can query connectivity state:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Legacy example (NetworkInfo)

The following snippet shows how to use ConnectivityManager to query the active network and determine if it has connectivity. This is the original/legacy approach and uses NetworkInfo (deprecated in API 29):

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

You can also check the type of the active network to determine whether it is Wi‑Fi:

boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

Notes about the legacy approach:

  • NetworkInfo and isConnectedOrConnecting were commonly used in older Android versions, but NetworkInfo is deprecated starting in API level 29. Prefer the modern NetworkCapabilities approach on newer devices.

Modern approach (API 29+): NetworkCapabilities

On Android Q (API 29) and later, use NetworkCapabilities and getActiveNetwork() to inspect the currently active network in a more accurate way. NetworkCapabilities lets you check both transport type and capabilities such as NETCAPABILITYINTERNET and NETCAPABILITYVALIDATED.

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = cm.getActiveNetwork(); // may be null
NetworkCapabilities nc = cm.getNetworkCapabilities(network);

boolean hasInternet = nc != null && nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
boolean validated = nc != null && nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
boolean isWifi = nc != null && nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);

Explanation:

  • NETCAPABILITYINTERNET means the network can reach the Internet in principle.
  • NETCAPABILITYVALIDATED indicates the platform has validated that the network can actually reach the Internet (often more useful to decide whether to attempt network IO).
  • Use hasTransport(…) to detect TRANSPORTWIFI, TRANSPORTCELLULAR, TRANSPORTETHERNET, TRANSPORTVPN, etc.

Listening for changes: registerNetworkCallback

If you need to be notified of connectivity changes (rather than polling), register a NetworkCallback:

NetworkRequest request = new NetworkRequest.Builder()
        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        .build();

ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        // network became available
    }

    @Override
    public void onLost(Network network) {
        // network lost
    }
};

cm.registerNetworkCallback(request, callback);
// Remember to unregister when appropriate: cm.unregisterNetworkCallback(callback);

Testing and troubleshooting

  • In the emulator you can simulate network conditions or disable the network.
  • Use adb to toggle airplane mode or modify network rules if needed.
  • Prefer checking NETCAPABILITYVALIDATED when you need a reliable indication that the network can reach the public Internet.

Summary

  • The original ConnectivityManager + NetworkInfo approach works on older devices but is deprecated (API 29+).
  • Use NetworkCapabilities.getNetworkCapabilities(getActiveNetwork()) and check capabilities and transports on modern Android.
  • Always declare ACCESSNETWORKSTATE in the manifest.

It's also possible to determine the type of Internet connection currently available. Device connectivity can be provided by mobile data, WiMAX, Wi‑Fi, and ethernet connections. By querying the type of the active network you can adjust behavior (for example, refresh rate or large downloads) based on bandwidth.

If "isWiFi" is true then the device is using Wi‑Fi connection. That's it. Happy coding.

References: