DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Checking an Internet Connection in Android

Checking an Internet Connection in Android

In this tutorial, we will discuss how to check for an Internet connection before performing any network operations.

Navneet Goel user avatar by
Navneet Goel
·
Sep. 20, 16 · Tutorial
Like (5)
Save
Tweet
Share
49.71K Views

Join the DZone community and get the full member experience.

Join For Free

Almost all Android Apps connect to the Internet to perform some kind of network access. However, to do so we must ensure that the phone has a working internet connection. In this tutorial, we will discuss how to check for an internet connection before performing any network operations.

For this purpose, Android SDK comes with a class that answers all queries about the state of network connectivity. It also notifies applications when network connectivity changes.

Let's create a simple app to understand how to check for a working Internet Connection.

Creating a New Project

Go to File → New → New Project and enter your Application Name. I named it CheckNetworkConnection

Enter the company domain — this is used to uniquely identify your App’s package worldwide.

Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code ourselves. Then click on Next.

Choose an Activity Name. Make sure Generate Layout File check box is selected, otherwise, we have to generate it ourselves. Then click on Finish. We have left Activity Name as MainActivity.

Open AndroidManifest.xml (You can see this file in the project tool window AndroidStudioProjects/tab/app/src/main/)

Use the following code in the AndroidManifest.xml :

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

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

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

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

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" >

        <activity android:name=".MainActivity" >

            <intent-filter>

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

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

            </intent-filter>

        </activity>

    </application>

</manifest>

Please note that we have used the INTERNET and ACCESS_NETWORK_STATE permissions.

INTERNET permission is required by an Android application to connect to the Internet.
ACCESS_NETWORK_STATE required by ConnectivityMannager to use getActiveNetworkInfo().

Create a Layout File

We will use a button to get the network status. So we have used a LinearLayout
with a button in the center.

Open activity_main.xml and paste following code:

activity_main.xml :

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button android:id="@+id/checkInternetButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingRight="10dp" android:paddingLeft="10dp" android:text="@string/checkInternetConnection"/>

</LinearLayout>

Check for Internet in MainActivity.java

Open MainActivity.java and paste the following code.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private Button checkIntrnetButton;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        checkIntrnetButton = (Button)findViewById(R.id.checkInternetButton);

        checkIntrnetButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                checkConnection();

            }

        });

    }

    protected boolean isOnline() {

        ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        if (netInfo != null && netInfo.isConnectedOrConnecting()) {

            return true;

        } else {

            return false;

        }

    }

    public void checkConnection(){

        if(isOnline()){

            Toast.makeText(MainActivity.this, "You are connected to Internet", Toast.LENGTH_SHORT).show();

        }else{

            Toast.makeText(MainActivity.this, "You are not connected to Internet", Toast.LENGTH_SHORT).show();

        }

    }

}

Test your app by turning off the Internet and clicking on the Check Internet Connection!! button. You should get a message that you are not connected to the Internet as shown below:

Image title


Next, connect to the Internet by turning ON your Wi-Fi or mobile data and click on the button again, you should get a message that you are connected to Internet.

Image title

Congratulations. It’s done. If you have any queries or suggestions, then please comment. Happy Coding!

Internet (web browser) Android (robot) Connection (dance) mobile app

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Why It Is Important To Have an Ownership as a DevOps Engineer
  • Top Five Tools for AI-based Test Automation
  • AWS Cloud Migration: Best Practices and Pitfalls to Avoid
  • A Real-Time Supply Chain Control Tower Powered by Kafka

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: