Checking an Internet Connection in Android
In this tutorial, we will discuss how to check for an Internet connection before performing any network operations.
Join the DZone community and get the full member experience.
Join For FreeAlmost 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:
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.
Congratulations. It’s done. If you have any queries or suggestions, then please comment. Happy Coding!
Opinions expressed by DZone contributors are their own.
Comments