Wednesday, 11 June 2014

CHECK INTERNET AVAILABILITY AND NOTIFY WHEN AVAILABLE IN ANDROID

If you want to develop an android application that will fetch information from internet, its better to check first if there is any internet connection available or not to handle exceptions.

You may also want to check when internet connection available to perform task or what type of connection is available (like WiFi or Mobile Data).




Download Source Code Download
  • First of all add permission in AndroidManifest.xml
Internet Permission 
<uses-permission android:name="android.permission.INTERNET" />
Network State Permission 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  • Create a new java file Network.java  and write down the following code:

Network.java

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

public class Network {

      private int NOT_CONNECTED = -1;
      private int MOBILE = 0;
      private int WIFI = 1;
      private Context context;

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

      public boolean isInternetAvailable() {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm != null) {
                  NetworkInfo[] ni = cm.getAllNetworkInfo();
                  if (ni != null) {
                        for (int i = 0; i < ni.length; i++) {
                              if (ni[i].getState() == NetworkInfo.State.CONNECTED) {
                                    return true;
                              }
                        }
                  }
            }
            return false;
      }

      public int getConnectionType() {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm != null) {
                  NetworkInfo ni = cm.getActiveNetworkInfo();
                  if (null != ni) {
                        if (ni.getType() == ConnectivityManager.TYPE_MOBILE)
                              return MOBILE;

                        if (ni.getType() == ConnectivityManager.TYPE_WIFI)
                              return WIFI;
                  }
            }
            return NOT_CONNECTED;
      }

      public String getConnectionString() {
            int type = getConnectionType();
            String status = null;
            if (type == MOBILE) {
                  status = "Mobile data enabled";
            } else if (type == WIFI) {
                  status = "Wifi enabled";
            } else if (type == NOT_CONNECTED) {
                  status = "Not connected to Internet";
            }
            return status;
      }
}

  • For checking any type of internet connection available or not on device use:
Network net = new Network(getApplicationContext());
net.isInternetAvailable();

  • For checking what type of internet connection is available on device use:
Network network = new Network(context);
String status = network.getConnectionString();

  • Use Broadcast receiver to check Network state, which will notify which network is available.
  • Create New java file NetworkStatusChangeReceiver.java and write down following code:

NetworkStatusChangeReceiver.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class NetworkStatusChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
      Network network = new Network(context);
        String status = network.getConnectionString();
        showToast(context,status);
    }
     
    //Custom toast message
      private void showToast(Context context, String status) {
        LayoutInflater mInflater = LayoutInflater.from(context);
        View myView = mInflater.inflate(R.layout.custom_toast, null);
        TextView text = (TextView) myView.findViewById(R.id.text);
        text.setText(status);
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(myView);
        toast.show();
      }
}

  • Register BroadcastReceiver in AndroidManifest.xml
AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorialsface.networkstatus"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name="com.tutorialsface.networkstatus.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".NetworkStatusChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>


  • Custom Toast xml
custom_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/rounded_rect"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:padding="10dp"
        android:textColor="#FFF" />
</LinearLayout>

  • Make rounded_rect.xml file in drawable folder as toast background.
rounded_rect.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <gradient
        android:angle="360"
        android:centerColor="#FF0000"
        android:endColor="#FF0000"
        android:startColor="#FF0000" />

    <corners
        android:bottomLeftRadius="10dp"
        android:bottomRightRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp" />
</shape>

  • Create MainActivity.java
MainActivity.java

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

      Button buttonCheck;
      TextView textStatus;
      Network net;
      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            init();
      }

      private void init() {
            getViews();
            setListeners();
            net = new Network(getApplicationContext());
      }

      private void setListeners() {
            buttonCheck.setOnClickListener(new OnClickListener() {
                  @Override
                  public void onClick(View v) {
                        if(net.isInternetAvailable()){
                              textStatus.setText("Connected to Internet");
                              textStatus.setTextColor(Color.GREEN);
                        }else{
                              textStatus.setText("Not connected to Internet");
                              textStatus.setTextColor(Color.RED);
                        }
                  }
            });
      }

      private void getViews() {
            buttonCheck = (Button) findViewById(R.id.buttonCheck);
            textStatus = (TextView) findViewById(R.id.textStatus);
      }
}

  • Create activity_main.xml
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/buttonCheck"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Get Internet status" />

    <TextView
        android:id="@+id/textStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        android:textSize="25dp" />
</LinearLayout>

Project hierarchy


1 comment:

  1. By the way, in Crimea I had a funny case related to the fact that the payment comes from the mobile account of MegaFon. I had been there for a couple of months, and I didn't need a connection from MegaFon. The bill naturally went into negative territory, because I did not pay the subscription fee, since I did not consume anything. When it came time to write off the funds for https://sound-library.net/ Yandex.Music, the operator naturally wrote off the subscription fee for his services first, and only then — for using the service. It remained only to regret the absence of a postpaid tariff or at least the ability to pay exclusively for the services actually consumed.

    Another point is no longer connected with Crimea, but with the very binding of the service to MegaFon. It is also implemented in a strange way. This is exactly the binding of Yandex.Music to the tariff package of the mobile operator. That is, the service is not even from Yandex, but from MegaFon. To change the payment method, you need to perform manipulations in the operator's personal account, from the Yandex.Music application I can only disable the service completely.

    Disconnections, work with unstable communication
    What is less funny is how Yandex.Music works in an environment where the mobile Internet is unstable. Forests, mountains, highways in a deserted area — this is normal if you like to travel, but it is completely alien to Yandex.Music. And here's why.

    Firstly, if you have chosen HQ sound quality, then the application does not bother at all that traffic barely passes. The music will falter, be interrupted, but there is simply no option to choose the sound quality depending on the channel width. You listen either always with high quality, or always with a minimum bitrate.

    ReplyDelete