
- Android Basics
- Android - Home
- Android - Overview
- Android - Environment Setup
- Android - Architecture
- Android - Application Components
- Android - Hello World Example
- Android - Resources
- Android - Activities
- Android - Services
- Android - Broadcast Receivers
- Android - Content Providers
- Android - Fragments
- Android - Intents/Filters
- Android - User Interface
- Android - UI Layouts
- Android - UI Controls
- Android - Event Handling
- Android - Styles and Themes
- Android - Custom Components
- Android Advanced Concepts
- Android - Drag and Drop
- Android - Notifications
- Location Based Services
- Android - Sending Email
- Android - Sending SMS
- Android - Phone Calls
- Publishing Android Application
- Android Useful Examples
- Android - Alert Dialoges
- Android - Animations
- Android - Audio Capture
- Android - AudioManager
- Android - Auto Complete
- Android - Best Practices
- Android - Bluetooth
- Android - Camera
- Android - Clipboard
- Android - Custom Fonts
- Android - Data Backup
- Android - Developer Tools
- Android - Emulator
- Android - Facebook Integration
- Android - Gestures
- Android - Google Maps
- Android - Image Effects
- Android - ImageSwitcher
- Android - Internal Storage
- Android - JetPlayer
- Android - JSON Parser
- Android - Linkedin Integration
- Android - Loading Spinner
- Android - Localization
- Android - Login Screen
- Android - MediaPlayer
- Android - Multitouch
- Android - Navigation
- Android - Network Connection
- Android - NFC Guide
- Android - PHP/MySQL
- Android - Progress Circle
- Android - ProgressBar
- Android - Push Notification
- Android - RenderScript
- Android - RSS Reader
- Android - Screen Cast
- Android - SDK Manager
- Android - Sensors
- Android - Session Management
- Android - Shared Preferences
- Android - SIP Protocol
- Android - Spelling Checker
- Android - SQLite Database
- Android - Support Library
- Android - Testing
- Android - Text to Speech
- Android - TextureView
- Android - Twitter Integration
- Android - UI Design
- Android - UI Patterns
- Android - UI Testing
- Android - WebView Layout
- Android - Wi-Fi
- Android - Widgets
- Android - XML Parsers
- Android Useful Resources
- Android - Questions and Answers
- Android - Useful Resources
- Android - Discussion
How to check internet connection in android?
This example demonstrate about how to check the state of internet connection through broadcast Receiver.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − To find the internet status we have to add network state permission to AndroidManifest.xml file as shown below.
<?xml version="1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <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>
Step 3 − Following is the content of the modified main activity file MainActivity.java. This file can include each of the fundamental life cycle methods. We have created a text view, when use click on text view it going to call broadcastIntent() method to broadcast a CONNECTIVITY_ACTION intent.
import android.content.BroadcastReceiver; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private BroadcastReceiver MyReceiver = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyReceiver = new MyReceiver(); TextView click=findViewById(R.id.click); click.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { broadcastIntent(); } }); } public void broadcastIntent() { registerReceiver(MyReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } @Override protected void onPause() { super.onPause(); unregisterReceiver(MyReceiver); } }
Step 4 − Create a NetworkUtil class to find the net work status as show below.
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; class NetworkUtil { public static String getConnectivityStatusString(Context context) { String status = null; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { status = "Wifi enabled"; return status; } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { status = "Mobile data enabled"; return status; } } else { status = "No internet is available"; return status; } return status; } }
Step 5 −Create a broadcast receiver class and named as MyReceiver.java .This broadcast receiver going to update the ui from NetworkUtil class.
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String status = NetworkUtil.getConnectivityStatusString(context); if(status.isEmpty()) { status="No Internet Connection"; } Toast.makeText(context, status, Toast.LENGTH_LONG).show(); } }
Step 6 −Update your broadcast receiver in manifest file as shown below.
<?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <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> <receiver android:name = "MyReceiver"> <intent-filter> <action android:name = "android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name = "android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver> </application> </manifest>
Step 7 −Following will be the content of res/layout/activity_main.xml file to include a textview to broadcast connectivity state intent.
<?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <TextView android:id="@+id/click" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click here" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
The above screen we have selected wifi connection and the output should be like this −
The above screen we have selected wifi connection and the output should be like this −
Click here to download the project code
- Related Articles
- How to check Internet connection availability on Android?
- How to get current internet connection type in android?
- How to check internet connection availability and the network type on Android using Kotlin?
- Tips to Increase Internet Speed without 4G Connection
- How to Check Internet Connectivity in Java?
- How to Transfer Files Using Wi-Fi Pair Connection in Android?
- How to get current date and time from internet in android?
- How to Use TRAI’s MySpeed App to Check Internet Speed
- How to check whether you are connected to Internet or not in C#?
- How to check current running applications in Android?
- How to check android mobile supports magnetometer?
- How to check Android Phone Model programmatically?
- How to get the current date and time from the internet in Android using Kotlin?
- How to check element is available in android ConcurrentLinkedDeque?
- How to check current wifi always discoverable in android?
