Showing posts with label Network connection. Show all posts
Showing posts with label Network connection. Show all posts

Monday 3 September 2012

Check Network Connection in Android

Check Network Connection in Android
Hello Friends,


Note: Declare following network permission in your  
           Androidmanifest.xml file:  
         
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  























1. MainActivity.java


package com.mukesh.networkcheck;

import com.mukesh.netwoekcheck.R;

import android.net.ConnectivityManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {

    private static final int REQUEST_CODE = 0;

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

        boolean isEnabled = isNetworkEnable();

        displayNetworkState(isEnabled);

        if (!isEnabled) {
            buildAlertMessageNoGps();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE) {
            displayNetworkState(isNetworkEnable());
        }
    }

    private void displayNetworkState(boolean isEnabled) {
        String status = "Your Network is "
                + (isEnabled ? "Enabled" : "Disabled");

        ((TextView) findViewById(R.id.text_gpsstatus)).setText(status);
    }

    private boolean isNetworkEnable() {
        ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        // ARE WE CONNECTED TO THE NET

        if (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected()) {

            return true;

        } else {

            Log.v("TAG", "Internet Connection Not Present");

            return false;

        }
    }

    private void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle(R.string.network_availability_title);
        builder.setMessage(R.string.network_availability_message);
        builder.setCancelable(false);

        builder.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog,
                            final int id) {
                        launchNetworkOptions();
                    }
                });

        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(final DialogInterface dialog, final int id) {
                dialog.cancel();
            }
        });

        builder.create().show();
    }

    private void launchNetworkOptions() {
        startActivityForResult(new Intent(
                android.provider.Settings.ACTION_WIRELESS_SETTINGS),
                REQUEST_CODE);
    }
}


2. AndroidManifest.xml


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

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

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

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

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

</manifest>


Download Source Code: Network Check





Friday 3 August 2012

Network reachability code in Phone gap-Android

Phone Gap network check


Hello Friends,

Have you searching for how to check network connection in your
Phone Gap  Application ?

Here , I am sharing my network reachability code in phone gap
application.

Note:
        In some of the devices if you are trying to connect your app using GPRS.
In this case the connection type will be  'Unknown connection' so in my code i am
only checking following condition to show confirm dialogue.


if(networkStatusType == 'undefined' || networkStatusType == 'No network    
                     connection'){
         showConfirm();
}




Code:
Index.html

  <!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, height=device-height" />
  <title>Login Form</title>
  <link rel="stylesheet" href="css/style.css">
  

<link rel="stylesheet" href="css/jquery.mobile-1.0b3.min.css" />


<script type="text/javascript" src="js/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.0b3.min.js"></script>

<script type="text/javascript" src="js/phonegap-1.0.0.js"></script>
<script type="text/javascript" src="js/SQLStore.js"></script>
<script type="text/javascript" src="js/NWReachability.js"></script>
<script type="text/javascript">
var DEBUG_ANDROID_THEME=true;
$(document).ready(function() {
//initDB();
});

</script
</head>

<body>
<div data-dom-cache="true" data-role="page" id="page">
 <div data-role="header" data-position="inline" data-theme="b">
<h1>LOGIN</h1>
         </div>

  <div class="container">
    <section class="login">
      <!--  <h1>Login to VEO App</h1>  -->
      <form>
        <p>
          <input type="text" name="txtName" id="loginName" value="" placeholder="Username">        
        </p>
        <p>
          <input type="password" name="txtPassword" id="password" value="" 
          placeholder="Password" > 
        </p>
        <p class="submit" style="width: 100px;">
           <input type="button" name="commit" value="Login" onclick="loginvalidation();">
        </p>
      </form>
    </section>    
  </div>
</div>
  
</body>
</html>



In my NetworkReachability.js


/*function for login validation */


function loginvalidation() {
        var msg="";
        //msg="Wrong Input";
        var ck_name = /^[A-Za-z0-9_.]{3,20}$/;
        var name_int = /[0-9]/;
        var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{5,20}$/;
        var userName =$("#loginName").val();
        var password =$("#password").val();
        if(userName == "" || password == ""){
        msg="Please fill User Name and Password ";
            showErrorToast(msg);
        $("#loginName").focus();
        }
        else {
        var pos=userName.search(name_int);
        if(pos==0){
        msg="Invalid User Name "
        showErrorToast(msg);
        $("#loginName").focus();
                $("#loginName").val("");
        }
        else if(!ck_name.test(userName)){
        msg="Invalid User Name "
                $("#loginName").focus();
                $("#loginName").val("");
                showErrorToast(msg);
                }
        else if(!ck_password.test(password))
        {
        msg="Invalid Password "
                $("#password").focus();
                $("#password").val("");
                showErrorToast(msg);
               
        }
        else {
        var networkStatusType = checkConnection();
        alert(networkStatusType);
       
        if(networkStatusType == 'undefined' || networkStatusType == 'No network    
                     connection'){
        showConfirm();
        }
        else{
        //Your own call
        }
        
        
        }
        
     }
  }





//check network connection 
function checkConnection() {
    var networkState = navigator.network.connection.type;

    var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.NONE]     = 'No network connection';

    //alert('Connection type: ' + states[networkState]);
    var  networkStatus=states[networkState];
    return networkStatus;

}

function showConfirm() {
    navigator.notification.confirm(
        'No network connection'// message
        onConfirm,              // callback to invoke with index of button pressed
        'Please Check Network Setting.',            // title
        'Ok,Cancel'          // buttonLabels
    );
}

//process the confirmation dialog result
function onConfirm(button) {
    if(button==1){
     //your code
    }else {
       //your code
    }
}


I think this will help you... 
Enjoy Coding :)

Please Comment if you have any query.

 

Copyright @ 2013 Android Developers Blog.