Android Short Codes

How To Restrict App To Use WiFi Only

There are some reasons you prevent download or access internet without WiFi connection. Data connection using Mobile Phone Network Provider can be costly. Some applications download data constantly and running out our data plan, so we need to limit this plan.

Note : Make sure you have assign following permissions in your manifest file.


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

Two important class is used to check this functionality available in android.net package.

  • ConnectivityManager
  • NetworkInfo

You can achieve the functionality with following method.

private boolean isOnline() {

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    //Checking if your connected to Internet.
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {

        //Checking if you are connected to wifi.
        if(netInfo.getType() != ConnectivityManager.TYPE_WIFI) {
            Toast.makeText(MainActivity.this, "You must need to enable wifi in order to download", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
    else {
        return false;
    }
}

 

You can implement the logic by simply using conditional block in your app.

 

if(isOnline()) {
    
    //do something when internet is connected to WiFi.
    
    }else {
    
   //do something when internet is connected.
 }

 

That’s it 🙂

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

Leave a Comment