how to check internet connection programmatically in
kotlin android
In this article, today learn how to check internet
connection programmatically in kotlin android. visit the StackOverflow.com
In android, by using the ConnectivityManager class we can easily determine whether
the device connected to the network/internet or not and also we can determine
the type of internet connection currently available i.e. whether it’s mobile
data or Wi-Fi.
<manifest>
....
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
....
</manifest>
Following is the code snippet of using the ConnectivityManager class to know whether the internet connection is available or not.
Check Internet Connection Status:
var cm =
getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE) as
ConnectivityManager
var nInfo = cm.getActiveNetworkInfo()
var connected = nInfo != null &&
nInfo.isAvailable() && nInfo.isConnected()
Determine the Type of Internet Connection:
var cm =
getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE) as
ConnectivityManager
var nInfo = cm.getActiveNetworkInfo()
var isWiFi = nInfo.getType() ===
ConnectivityManager.TYPE_WIFI
1.MainActivity.kt:
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
class MainActivity:AppCompatActivity() {
val
isConnected:Boolean
get() {
val connected =
false
try
{
val cm =
getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE) as
ConnectivityManager
val nInfo = cm.getActiveNetworkInfo()
connected =
nInfo != null && nInfo.isAvailable() && nInfo.isConnected()
return
connected
}
catch
(e:Exception) {
Log.e("Connectivity Exception", e.message)
}
return
connected
}
protected fun
onCreate(savedInstanceState:Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnStatus =
findViewById(R.id.btnCheck) as Button
btnStatus.setOnClickListener(object:View.OnClickListener() {
fun
onClick(v:View) {
// 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()
}
}
})
}
}
No comments:
Post a Comment