Tuesday, 21 June 2016

How to check if Internet is available in android

Hi guys, today I'm going to show you how to check if internet is available in Android.
This one of the key things that you might need when you want to check if the internet is available for you to perform a certain task with the application, and also to prevent you have app from force closing if it's executing a function or method that may rely on the Internet.

Project Structure:




1. Create a project,

- Check out here on how to create your first android app and running it.

2. Coding:

i. Open activity_main.xml file and make the following changes.

<?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="com.ryle_tech.androidmentor.MainActivity">

    <TextView        
android:id="@+id/connectionStatus"        
android:layout_width="wrap_content"        
android:layout_height="wrap_content"        
android:textStyle="bold"        
android:textAppearance="?android:attr/textAppearanceMedium"        
android:text="Connection Status"/>

<Button    
android:id="@+id/checkConnection"    
android:layout_width="wrap_content"    
android:layout_height="wrap_content"    
android:layout_centerInParent="true"   
 android:text="Check Internet Connection"/>

</RelativeLayout>

ii. Right click on the package i.e com.ryle-tech.androidmentor > New > Java Class
        - Enter the name InternetConnection and press ok.


iii. Android studio will open the InternetConnection.java by default, make the following changes

- the method isInternetAvailable() will return either true, if there's internet connection or false, if there's no internet connection. It checks for all the connections: WiFi, cellular data and Bluetooth connection e.t.c

package com.ryle_tech.androidmentor;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/** * Created by kevynashinski on 11/9/2015. */
public class InternetConnection {

    Context context;

    public InternetConnection(Context context) {
        this.context = context;
    }

    public boolean isInternetAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) 
        context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }
}

Preview of the activty_main.xml


iv. Open the MainActivity.java and make the following changes

package com.ryle_tech.androidmentor;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override    
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button checkInternetConnection= (Button) findViewById(R.id.checkConnection);
        final TextView connectionStatus= (TextView) findViewById(R.id.connectionStatus);

        assert checkInternetConnection != null;
        checkInternetConnection.setOnClickListener(new View.OnClickListener() {
            @Override           
 public void onClick(View v) {
                if(new InternetConnection(getBaseContext()).isInternetAvailable()){
                    connectionStatus.setText("internet connection is available!!!");
                }else {
                    connectionStatus.setText("No internet connection");
                }
            }
        });

    }
}

v. Finally add the internet permissions to the AndroidManifest.xml, the code should look like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"   
 package="com.ryle_tech.androidmentor">

    <!--Permissions-->    
<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>

vi. Now run the app and click the button.

a) If internet is available

b) If intenet is not available




0 comments:

Post a Comment