Paramclasses Academy - Blog

Tutorials Details

←
Post 25 of 40
→

How to Connect an Android App to the Internet and Handle Network Permissions ?

How to Connect an Android App to the Internet and Handle Network Permissions ?

November 3, 2026

1. Introduction

Most modern Android applications need an internet connection to access online information.

For example:

  • Weather applications retrieve weather information from online services.

  • Shopping applications load products from a server.

  • News applications download the latest articles.

  • Social media applications send and receive user information.

  • Banking applications communicate with secure backend servers.

Android applications can communicate with remote servers using HTTP and HTTPS requests.

In this tutorial, you will learn how to connect an Android application to the internet using Java.

You will also learn how to:

  • Add internet permissions in AndroidManifest.xml.

  • Understand network permissions.

  • Check internet connectivity.

  • Use ConnectivityManager and NetworkCapabilities.

  • Perform HTTP GET requests.

  • Use HttpURLConnection.

  • Execute network operations on a background thread.

  • Display server responses in an Android application.

  • Handle network errors and connection timeouts.

2. Understanding Internet Connectivity in Android

An Android application communicates with a remote server through a network connection.

The basic communication process looks like this:

        Android Application
                |
                v
          HTTP Request
                |
                v
          Internet Network
                |
                v
           Web Server
                |
                v
          HTTP Response
                |
                v
        Android Application

For example, when a user opens a weather application, the app sends a request to a weather API.

The server processes the request and returns the weather information.

The Android application receives that response and displays it on the screen.

3. Understanding Android Network Permissions

Before an Android application can perform network operations, the required permissions must be declared in its manifest file.

Android provides two important permissions for basic network access.

INTERNET Permission

This permission allows an application to open network connections and communicate with remote servers.

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

Without this permission, the application cannot perform normal internet communication.

ACCESS_NETWORK_STATE Permission

This permission allows an application to inspect network connectivity information.

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

It is useful when checking whether a network connection is available.

Important Permission Information

Both INTERNET and ACCESS_NETWORK_STATE are normal permissions.

They do not require a runtime permission dialog. Declaring them in AndroidManifest.xml is sufficient.

4. Add Permissions in AndroidManifest.xml

Open your Android Studio project.

Navigate to:

app > manifests > AndroidManifest.xml

Add these permissions inside the manifest element and before the application element.

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

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

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

    <application
        android:allowBackup="true"
        android:label="InternetConnectionApp"
        android:supportsRtl="true"
        android:theme="@style/Theme.InternetConnectionApp">

        <activity
            android:name=".MainActivity"
            android:exported="true">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

</manifest>

Important: Keep your existing application theme and other project-generated settings if their names are different. The important part is adding both uses-permission elements before application.

5. Create a New Android Studio Project

Now create a practical application.

Follow these steps:

  1. Open Android Studio.

  2. Click New Project.

  3. Select Empty Views Activity.

  4. Enter the project name: InternetConnectionApp.

  5. Select Java as the programming language.

  6. Choose your required Minimum SDK.

  7. Click Finish.

Wait for Android Studio to complete the project setup.

6. Understand HTTP and HTTPS

HTTP stands for Hypertext Transfer Protocol.

It is a communication protocol used by applications and web servers to exchange information.

HTTPS is the secure version of HTTP. It uses TLS to encrypt communication between the client and server.

HTTP Methods

Some commonly used HTTP methods are:

GET

Used to retrieve information from a server.

Example:

GET /posts/1

POST

Used to send data to a server.

Example: Sending registration information to a backend API.

PUT

Used to replace or update a resource.

PATCH

Used to partially update a resource.

DELETE

Used to remove a resource from a server.

In this tutorial, we will use the GET method to retrieve information from a sample API.

7. Understand HttpURLConnection

Android provides the HttpURLConnection class for making HTTP requests.

It allows an application to:

  • Open a connection to a URL.

  • Select an HTTP request method.

  • Set connection timeouts.

  • Read server responses.

  • Send request headers.

  • Disconnect from the server.

Example:

URL url = new URL("https://example.com");

HttpURLConnection connection =
        (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

connection.connect();

This code creates an HTTP connection and sends a GET request.

For HTTPS URLs, the platform uses the secure HTTPS connection implementation.

8. Check Internet Connectivity Using ConnectivityManager

Before making a network request, it is useful to check the current network status.

Android provides the ConnectivityManager class to access network connectivity information.

For modern Android versions, use NetworkCapabilities instead of deprecated connectivity APIs.

Example:

ConnectivityManager connectivityManager =
        (ConnectivityManager) getSystemService(
                CONNECTIVITY_SERVICE);

Network network =
        connectivityManager.getActiveNetwork();

if (network != null) {

    NetworkCapabilities capabilities =
            connectivityManager.getNetworkCapabilities(network);

    if (capabilities != null &&
            capabilities.hasCapability(
                    NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
            capabilities.hasCapability(
                    NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {

        // Internet connection is available.

    }
}

Understanding the Code

ConnectivityManager

Provides information about the device's network connections.

getActiveNetwork()

Returns the currently active default network, if available.

getNetworkCapabilities()

Returns information about the capabilities of that network.

NET_CAPABILITY_INTERNET

Indicates that the network is configured for internet access.

NET_CAPABILITY_VALIDATED

Indicates that Android has successfully validated internet connectivity for that network.

A network can have internet capability without having working internet access. Therefore, checking both capabilities gives a more useful connectivity check.

9. Design the Application Layout

Now open:

activity_main.xml

Replace the existing layout with the following code:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Internet Connection App"
        android:textSize="24sp"
        android:textStyle="bold"
        android:gravity="center"
        android:padding="15dp" />

    <Button
        android:id="@+id/btnCheck"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Check Internet Connection" />

    <Button
        android:id="@+id/btnFetch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetch Server Data" />

    <TextView
        android:id="@+id/tvStatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Connection status will appear here."
        android:textSize="16sp"
        android:padding="12dp" />

    <TextView
        android:id="@+id/tvResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Server response will appear here."
        android:textSize="16sp"
        android:padding="12dp" />

</LinearLayout>

Understanding the Layout

The application contains:

  • A title TextView.

  • A Check Internet Connection button.

  • A Fetch Server Data button.

  • A TextView to display network status.

  • A TextView to display the server response.

10. Write MainActivity.java Code

Now open:

MainActivity.java

Add the following complete code:

package com.example.internetconnectionapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    Button btnCheck, btnFetch;

    TextView tvStatus, tvResult;

    ExecutorService executorService =
            Executors.newSingleThreadExecutor();

    Handler mainHandler =
            new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        btnCheck = findViewById(R.id.btnCheck);

        btnFetch = findViewById(R.id.btnFetch);

        tvStatus = findViewById(R.id.tvStatus);

        tvResult = findViewById(R.id.tvResult);

        // CHECK INTERNET CONNECTION
        btnCheck.setOnClickListener(v -> {

            if (isInternetAvailable()) {

                tvStatus.setText("Internet is Connected");

            } else {

                tvStatus.setText("Internet is Not Available");

            }
        });

        // FETCH SERVER DATA
        btnFetch.setOnClickListener(v -> {

            if (!isInternetAvailable()) {

                Toast.makeText(this,
                        "Please Check Internet Connection",
                        Toast.LENGTH_SHORT).show();

                return;
            }

            tvResult.setText("Loading Data...");

            btnFetch.setEnabled(false);

            executorService.execute(() -> {

                String response = fetchData();

                mainHandler.post(() -> {

                    tvResult.setText(response);

                    btnFetch.setEnabled(true);

                });
            });
        });
    }

    // CHECK INTERNET CONNECTIVITY
    private boolean isInternetAvailable() {

        ConnectivityManager connectivityManager =
                (ConnectivityManager) getSystemService(
                        CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        }

        Network network =
                connectivityManager.getActiveNetwork();

        if (network == null) {
            return false;
        }

        NetworkCapabilities capabilities =
                connectivityManager.getNetworkCapabilities(network);

        return capabilities != null &&
                capabilities.hasCapability(
                        NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
                capabilities.hasCapability(
                        NetworkCapabilities.NET_CAPABILITY_VALIDATED);
    }

    // FETCH DATA FROM SERVER
    private String fetchData() {

        HttpURLConnection connection = null;

        try {

            URL url = new URL(
                    "https://jsonplaceholder.typicode.com/posts/1"
            );

            connection = (HttpURLConnection)
                    url.openConnection();

            connection.setRequestMethod("GET");

            connection.setConnectTimeout(10000);

            connection.setReadTimeout(10000);

            int responseCode = connection.getResponseCode();

            InputStream inputStream;

            if (responseCode >= 200 && responseCode < 300) {

                inputStream = connection.getInputStream();

            } else {

                inputStream = connection.getErrorStream();

                if (inputStream == null) {
                    return "Server Error: HTTP " + responseCode;
                }
            }

            StringBuilder result = new StringBuilder();

            try (BufferedReader reader =
                         new BufferedReader(
                                 new InputStreamReader(inputStream))) {

                String line;

                while ((line = reader.readLine()) != null) {

                    result.append(line);
                }
            }

            if (responseCode >= 200 && responseCode < 300) {

                return "Server Response:\n\n" + result;

            } else {

                return "HTTP Error " + responseCode +
                        "\n\n" + result;
            }

        } catch (Exception e) {

            return "Network Error: " + e.getMessage();

        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    @Override
    protected void onDestroy() {

        executorService.shutdown();

        super.onDestroy();
    }
}

Important: Replace com.example.internetconnectionapp with your actual application package name.

Understanding the MainActivity Code

ExecutorService

ExecutorService executorService =
        Executors.newSingleThreadExecutor();

This creates a background worker thread for network operations.

Network requests should not run on the main UI thread because slow requests can freeze the application.

Handler

Handler mainHandler =
        new Handler(Looper.getMainLooper());

This allows the background task to post the result back to the main UI thread.

isInternetAvailable()

This method checks whether the active network has internet capability and has been validated by Android.

fetchData()

This method:

  1. Creates a URL.

  2. Opens an HTTP connection.

  3. Sets the request method to GET.

  4. Configures connection and read timeouts.

  5. Sends the request.

  6. Reads the server response.

  7. Returns the response as a String.

  8. Disconnects the connection.

getResponseCode()

This method returns the HTTP status code.

For example:

  • 200 – Request successful.

  • 400 – Bad request.

  • 401 – Unauthorized.

  • 404 – Resource not found.

  • 500 – Internal server error.

Error Handling

The code reads the error response when the server returns a non-success HTTP status.

It also handles exceptions such as connection failures and timeouts.

11. Understand the Sample API

In this project, we are using:

https://jsonplaceholder.typicode.com/posts/1

JSONPlaceholder is a public testing API that provides sample JSON data.

A successful response looks similar to:

{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident",
    "body": "quia et suscipit suscipit recusandae"
}

Our Android application retrieves this response and displays the JSON text inside the TextView.

The example does not require a login or API key.

12. Run and Test the Application

Now run the application on an Android emulator or a real Android phone.

Test 1: Check Internet Connection

  1. Turn on Wi-Fi or mobile data.

  2. Open the application.

  3. Click Check Internet Connection.

  4. Check the status displayed on the screen.

Expected output:

Internet is Connected

Test 2: Fetch Server Data

  1. Keep the internet connection active.

  2. Click Fetch Server Data.

  3. Wait for the server response.

  4. Check the JSON information displayed on the screen.

Expected output:

Server Response:

{
    "userId": 1,
    "id": 1,
    "title": "...",
    "body": "..."
}

Test 3: Test Without Internet

  1. Turn off Wi-Fi and mobile data.

  2. Click Check Internet Connection.

  3. The application should display that internet is unavailable.

  4. Click Fetch Server Data.

  5. The application should show a connection warning instead of attempting the request.

13. Important Network Security Best Practices

When developing an internet-connected Android application, follow these security practices:

  1. Prefer HTTPS instead of HTTP.

  2. Never send passwords or sensitive information through unencrypted connections.

  3. Do not hardcode secret API keys in the application.

  4. Validate server responses before using them.

  5. Configure connection and read timeouts.

  6. Handle network errors properly.

  7. Do not perform network operations on the main UI thread.

  8. Avoid transmitting unnecessary personal information.

  9. Use secure authentication when communicating with protected APIs.

14. Common Network Errors and Solutions

Error 1: NetworkOnMainThreadException

Reason: A network request is running on the main UI thread.

Solution: Execute the network request using ExecutorService or another appropriate background execution mechanism.

Error 2: UnknownHostException

Reason: The application cannot resolve the server hostname.

Solution: Check internet connectivity, DNS availability, and the server URL.

Error 3: SocketTimeoutException

Reason: The server did not respond within the configured timeout.

Solution: Check the network and server status. Adjust timeouts where appropriate.

Error 4: Permission Error

Reason: The INTERNET permission is missing from AndroidManifest.xml.

Solution: Add the INTERNET permission inside the manifest element and rebuild the application.

Error 5: HTTP 404 Error

Reason: The requested API endpoint or resource does not exist.

Solution: Verify the URL and API endpoint.

Error 6: Server Error

Reason: The server may be unavailable or may have encountered an internal problem.

Solution: Check the server response code and retry only when appropriate.

15. Conclusion

In this tutorial, you learned how to connect an Android application to the internet using Java.

You added INTERNET and ACCESS_NETWORK_STATE permissions, checked connectivity using ConnectivityManager and NetworkCapabilities, and performed an HTTP GET request using HttpURLConnection.

You also learned how to execute network requests on a background thread, handle server responses, configure timeouts, and manage common network errors.

Internet connectivity is an important foundation for modern Android applications because it allows applications to communicate with remote servers and online APIs.

Practice Task: Modify the application to fetch a different post by changing the API endpoint from /posts/1 to /posts/2. Run the application and compare the returned JSON response.

←
Post 25 of 40
→