Tuesday, 6 March 2018

Network Connection is Available or Not

Detecting internet connection status in your Android Application is very easy and won’t take more than few seconds to check your device is connected to network or not. In this Example you will learn how to detect internet connection or Network is available or not in your device. In order to perform network operations in your application, your manifest must include the following permissions:- <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> Java File: - MainActivity.java package jeevan.karan.newworkcheck; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { isOnline(); } }); } public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if(netInfo != null && netInfo.isConnectedOrConnecting()){ Toast.makeText(MainActivity.this, "Network is Available", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(MainActivity.this, "Network is not Available", Toast.LENGTH_SHORT).show(); } return true; } } Xml File activity_main: - <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="jeevan.karan.newworkcheck.MainActivity"> <Button android:id="@+id/button" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="#aaaa" android:gravity="center" android:padding="8dp" android:text="Click me" android:textSize="20dp" /> </RelativeLayout>

No comments:

Post a Comment