Thursday, 7 November 2013

Check GPS, Internet and Wifi availability Status in android


Check GPS, Internet and Wifi availability Status in android


Hi guys, here is simple tutorial for frequently used functions as Internet GPS  and WiFi availability in android.
here we created separate utility class and just passing context to the constructor and calling desire functions.
Thats end, simple :)





 have look on code example.
DialogUtility.java

package com.example.availabilitychecker;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;

public class DialogUtility {

       Context context;

       public DialogUtility(Context context) {
              this.context = context;

       }

       /**
        * Function to show settings alert dialog On pressing Settings button will
        * lauch Settings Options
        * */
       public void showGPSSettingsAlert() {
              AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

              // Setting Dialog Title
              alertDialog.setTitle("GPS is settings");

              // Setting Dialog Message
              alertDialog
                           .setMessage("GPS is not enabled. Do you want to go to settings menu?");

              // On pressing Settings button
              alertDialog.setPositiveButton("Settings",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         Intent intent = new Intent(
                                                       Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                         context.startActivity(intent);
                                  }
                           });

              // on pressing cancel button
              alertDialog.setNegativeButton("Cancel",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         dialog.cancel();
                                  }
                           });
              // Showing Alert Message
              alertDialog.show();
       }

       /**
        * Display a dialog that user has no internet connection lauch Settings
        * Options
        * */
       public void showInternetSettingsAlert() {
              AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

              // Setting Dialog Title
              alertDialog.setTitle("Internet Settings");

              // Setting Dialog Message
              alertDialog
                           .setMessage("Internet is not enabled. Do you want to go to settings menu?");

              // On pressing Settings button
              alertDialog.setPositiveButton("Settings",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         Intent intent = new Intent(
                                                       Settings.ACTION_WIRELESS_SETTINGS);
                                         context.startActivity(intent);
                                  }
                           });

              // on pressing cancel button
              alertDialog.setNegativeButton("Cancel",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         dialog.cancel();
                                  }
                           });
              // Showing Alert Message
              alertDialog.show();
       }

       /**
        * Display a dialog that user has no Wifi connection lauch Settings Options
        * */
       public void showBluetoothSettingsAlert() {
              AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

              // Setting Dialog Title
              alertDialog.setTitle("Wifi Settings");

              // Setting Dialog Message
              alertDialog
                           .setMessage("Wifi is not enabled. Do you want to go to settings menu?");

              // On pressing Settings button
              alertDialog.setPositiveButton("Settings",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         Intent intent = new Intent(
                                                       Settings.ACTION_WIFI_SETTINGS);
                                         context.startActivity(intent);
                                  }
                           });

              // on pressing cancel button
              alertDialog.setNegativeButton("Cancel",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         dialog.cancel();
                                  }
                           });
              // Showing Alert Message
              alertDialog.show();
       }

       /**
        * Check Internet Availability and return true or false Require permitions
        * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        * <uses-permission android:name="android.permission.INTERNET" />
        * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
        * />
        *
        * @param context
        * @return
        */
       public boolean isInternetConnected() {

              ConnectivityManager cm = (ConnectivityManager) context
                           .getSystemService(Context.CONNECTIVITY_SERVICE);
              NetworkInfo netinfo = cm.getActiveNetworkInfo();

              if (netinfo != null && netinfo.isConnectedOrConnecting()) {
                     android.net.NetworkInfo wifi = cm
                                  .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                     android.net.NetworkInfo mobile = cm
                                  .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                     if ((mobile != null && mobile.isConnectedOrConnecting())
                                  || (wifi != null && wifi.isConnectedOrConnecting()))
                           return true;
                     else
                           return false;
              } else
                     return false;
       }

       public boolean isWiFiConnected() {
              // Create object for ConnectivityManager class which returns network
              // related info
              ConnectivityManager connectivity = (ConnectivityManager) context
                           .getSystemService(Context.CONNECTIVITY_SERVICE);
              // If connectivity object is not null
              if (connectivity != null) {
                     // Get network info - WIFI internet access
                     NetworkInfo info = connectivity
                                  .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                     if (info != null) {
                           // Look for whether device is currently connected to WIFI
                           // network
                           if (info.isConnected()) {
                                  return true;
                           }
                     }
              }
              return false;
       }

       /**
        * requires <uses-permission
        * android:name="android.permission.ACCESS_FINE_LOCATION" />
        *
        * @param context
        * @return
        */

       public boolean isGPSConnected() {
              LocationManager service = (LocationManager) context
                           .getSystemService(context.LOCATION_SERVICE);
              boolean status = service
                           .isProviderEnabled(LocationManager.GPS_PROVIDER);
              return status;
       }
}





and we use this class functions as in our MainActivity.java file 








package com.example.availabilitychecker;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
       Context context;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              context = MainActivity.this;
              Button button = (Button) findViewById(R.id.button1);
              button.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {

                           DialogUtility dialogUtility = new DialogUtility(context);
                           if (!dialogUtility.isGPSConnected())
                                  dialogUtility.showGPSSettingsAlert();
                           else
                                  Toast.makeText(context, "GPS Available", Toast.LENGTH_SHORT)
                                                .show();
                     }
              });

              Button button2 = (Button) findViewById(R.id.button2);
              button2.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {

                           DialogUtility dialogUtility = new DialogUtility(context);
                           if (!dialogUtility.isInternetConnected())
                                  dialogUtility.showInternetSettingsAlert();
                           else
                                  Toast.makeText(context, "Internet Available",
                                                Toast.LENGTH_SHORT).show();
                     }
              });

              Button button3 = (Button) findViewById(R.id.button3);
              button3.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {

                           DialogUtility dialogUtility = new DialogUtility(context);
                           if (!dialogUtility.isWiFiConnected())
                                  dialogUtility.showBluetoothSettingsAlert();
                           else
                                  Toast.makeText(context, "Wifi Available",
                                                Toast.LENGTH_SHORT).show();
                     }
              });

       }

}



activity xml file as 


<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" >

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:text="Check Internet Availability" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button2"
        android:text="Check Wifi Availability" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/images" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/imageView1"
        android:text="Check GPS Availability " />

</RelativeLayout>


and we use following permissions in our app 


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



and here is complete complete menifest.xml file as




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

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.availabilitychecker.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>




thats end, simple  :)

and Here you can download complete working example.


Happpppppy Codddddding :)







No comments:

Post a Comment