In android, by using ConnectivityManager class we can easily determine whether the network or internet connected or not and also we can determine the type of internet connection currently available i.e. whether it’s mobile data or Wi-Fi.
To get the internet connection status, our app must acquire the INERTNET and ACCESS_NETWORK_STATE permissions. For that, we need to add the following permissions in android manifest file like as shown below.
<manifest>
....
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
....
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
....
</manifest>
</manifest>
Check Internet Connection Status
In android, we can determine the internet connection status easily by using getActiveNetworkInfo() method of ConnectivityManager object.
Following is the code snippet of using ConnectivityManager class to know whether internet connection available or not.
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();boolean connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
NetworkInfo nInfo = cm.getActiveNetworkInfo();boolean connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
If you observe above code snippet, we used getActiveNetworkInfo() method of ConnectivityManager object to know whether internet connection available or not.
Determine the Type of Internet Connection
In android, we can easily determine the type of internet connection currently available i.e. either WI-FI or mobile data by using getType() method of NetworkInfo object.
Following is the code snippet to get the type of internet connection in android application.
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();boolean isWiFi = nInfo.getType() == ConnectivityManager.TYPE_WIFI;
NetworkInfo nInfo = cm.getActiveNetworkInfo();boolean isWiFi = nInfo.getType() == ConnectivityManager.TYPE_WIFI;
If you observe above code snippet, we used getType() method of NetworkInfo object to know the type of internet connection.
Now we will see how to save files directly on the device’s internal memory and read the data files from device internal memory by using FileOutputStream and FileInputStream objects in android application with examples.
Android Internet Connection Example
Following is the example of checking whether the internet connection available or not using android ConnectivityManager object.
Create a new android application using android studio and give names as InternalConnectionExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:text="Check Internet Connection" />
</LinearLayout>
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:text="Check Internet Connection" />
</LinearLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.internalstorageexample path and write the code like as shown below
MainActivity.java
package com.tutlane.internetconnectionexample;import android.content.Context;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStatus = (Button)findViewById(R.id.btnCheck);
btnStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Check for Internet Connection
if (isConnected()) {
Toast.makeText(getApplicationContext(), "Internet Connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean isConnected() {
boolean connected = false;
try {
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
return connected;
} catch (Exception e) {
Log.e("Connectivity Exception", e.getMessage());
}
return connected;
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStatus = (Button)findViewById(R.id.btnCheck);
btnStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Check for Internet Connection
if (isConnected()) {
Toast.makeText(getApplicationContext(), "Internet Connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean isConnected() {
boolean connected = false;
try {
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
return connected;
} catch (Exception e) {
Log.e("Connectivity Exception", e.getMessage());
}
return connected;
}
}
If you observe above code, we are getting the internet connection status by using ConnectivityManager object.
Now we need to acquire the permissions of INTERNET and ACCESS_NETWORK_STATE for our android application for that open AndroidManifest.xml file and add the permissions like as shown below.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.internetconnectionexample">
<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:roundIcon="@mipmap/ic_launcher_round"
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>
package="com.tutlane.internetconnectionexample">
<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:roundIcon="@mipmap/ic_launcher_round"
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>
If you observe above example, we are getting the internet connection status and added required permissions in AndroidManifest.xml file.
Output of Android Internet Connection Example
When we run above example in android emulator we will get a result like as shown below.
If you observe above result, When we click on Check Internet Connection button it will fetch the status of internet connection whether the internet available not.
This is how we can check the internet connection status in android applications using ConnectivityManager object based on our requirements.
No comments:
Post a Comment