android-studio
  1. android-studio-network-connectivity-services

Android Studio Network Connectivity Services

Syntax

ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

if (networkInfo != null && networkInfo.isConnected()) {
  // network connection is available
} else {
  // no network connection available
}

Example

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            Toast.makeText(this, "Network connection is available", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "No network connection available", Toast.LENGTH_LONG).show();
        }
    }
}

Output

If a network connection is available, the message "Network connection is available" will be displayed. Otherwise, the message "No network connection available" will be displayed.

Explanation

The Android SDK provides various classes to work with network connectivity. The ConnectivityManager class is used to check for network availability and the NetworkInfo class is used to obtain information about the current network connection.

Use

Android apps often need to communicate with servers or other devices over the internet. It is important to check for network connectivity before attempting to make any network requests. This can be done using the ConnectivityManager class.

Important Points

  • The ConnectivityManager class is used to check for network availability.
  • The NetworkInfo class is used to obtain information about the current network connection.
  • It is important to check for network connectivity before attempting to make any network requests.

Summary

Android Studio provides network connectivity services through the ConnectivityManager and NetworkInfo classes. Checking for network availability is important before making network requests.

Published on: