Android automatically detect internet connection status

If you have an android application that needs to sync data with a backend server but doesn't need the internet to be available all the time for it to work then you must know at all times whether your app has access to internet or not. As soon as you have internet connection you can get latest data from the server or post any changes saved in your app using HTTP service. In this example we extend the BroadcastReceiver to listen for any changes in network status and then find out whether the app has internet at that time. Please note that you have to specify the ACCESS_NETWORK_STATE in your android manifest permissions for this to work otherwise you will get java.lang.SecurityException: ConnectivityService: Neither user XXXXX nor current process has android.permission.ACCESS_NETWORK_STATE.

Android automatically detect internet connection status Android Internet connection status

Android Application Manifest

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

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />

    <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.as400samplecode.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Android Application Layout

<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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/networkStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />
   
</RelativeLayout>

Android Application Main Activity

package com.as400samplecode;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

 private static final String LOG_TAG = "CheckNetworkStatus";
 private NetworkChangeReceiver receiver;
 private boolean isConnected = false;
 private TextView networkStatus;

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

  IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
  receiver = new NetworkChangeReceiver();
  registerReceiver(receiver, filter);
  
  networkStatus = (TextView) findViewById(R.id.networkStatus);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
 
 @Override
 protected void onDestroy() {
  Log.v(LOG_TAG, "onDestory");
  super.onDestroy();
  
  unregisterReceiver(receiver);

 }


 public class NetworkChangeReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(final Context context, final Intent intent) {

   Log.v(LOG_TAG, "Receieved notification about network status");
   isNetworkAvailable(context);

  }


  private boolean isNetworkAvailable(Context context) {
   ConnectivityManager connectivity = (ConnectivityManager) 
     context.getSystemService(Context.CONNECTIVITY_SERVICE);
   if (connectivity != null) {
    NetworkInfo[] info = connectivity.getAllNetworkInfo();
    if (info != null) {
     for (int i = 0; i < info.length; i++) {
      if (info[i].getState() == NetworkInfo.State.CONNECTED) {
       if(!isConnected){
        Log.v(LOG_TAG, "Now you are connected to Internet!");
        networkStatus.setText("Now you are connected to Internet!");
        isConnected = true;
        //do your processing here ---
        //if you need to post any data to the server or get status
        //update from the server
       }
       return true;
      }
     }
    }
   }
   Log.v(LOG_TAG, "You are not connected to Internet!");
   networkStatus.setText("You are not connected to Internet!");
   isConnected = false;
   return false;
  }
 }


}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.