Showing posts with label Network & Connectivity. Show all posts

Wednesday, 3 June 2015

Check Network state and type | Wifi | Mobile 2G/3G |

In this android example i show you some interesting code about network state. just write a simple android code to get network information.
  1. Check network connection type WiFi/Mobile data etc.
  2. Check state connected or disconnected
  3. Previously activated network
Before starting example we should know some thing about KEY and Meaning of connectivity manager API.The intent never contains any data or type information, but some possible keys are provided in the ConnectivityManager API:


KEY and MEANING:

EXTRA_EXTRA_INFO : Contains additional information about the network state.

EXTRA_IS_FAILOVER : A Boolean that indicates whether this network is used as a failover for another, previously active network.

EXTRA_NETWORK_INFO : The Network Info object containing all information about the current state of this network type.

EXTRA_NO_CONNECTIVITY :  A Boolean that is set to true if the device has no connectivity at all.
EXTRA_OTHER_NETWORK_INFO : The Network Info object containing all information about the current state of a possible alternative network type.

EXTRA_REASON : The reason of the connectivity change.

CREATE NEW ANDROID PROJECT

Step 1: Write code into activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/tvinfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:text="@string/hello_world"
        android:textSize="20sp" />

</LinearLayout>


Step 2: Write code into MainActivity.java

package dev.androidapplink.connectionstatusapp;

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.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.TextView;


public class MainActivity extends Activity {
private ConnectivityReceiver receiver = null;
private TextView txtNetworkInfo = null;

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

txtNetworkInfo = (TextView) findViewById(R.id.tvinfo);
receiver = new ConnectivityReceiver();

registerReceiver(receiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}

@Override
protected void onDestroy() {
unregisterReceiver(receiver);

super.onDestroy();
}

private String getNetworkStateString(NetworkInfo.State state) {
String stateString = "Unknown";

switch (state) {
case CONNECTED:
stateString = "Connected";
break;
case CONNECTING:
stateString = "Connecting";
break;
case DISCONNECTED:
stateString = "Disconnected";
break;
case DISCONNECTING:
stateString = "Disconnecting";
break;
case SUSPENDED:
stateString = "Suspended";
break;
default:
stateString = "Unknown";
break;
}

return stateString;
}

private class ConnectivityReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// In this example i using " EXTRA_NETWORK_INFO " The NetworkInfo object containing all information about the current state of this network type

NetworkInfo info = intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

if (null != info) {
String state = getNetworkStateString(info.getState());
String stateString = info.toString().replace(',', '\n');

String infoString = String.format(
"Network Type: %s\nNetwork State: %s\n\n%s",
info.getTypeName(), state, stateString);

Log.i("ConnTest", info.getTypeName());
Log.i("ConnTest", state);
Log.i("ConnTest", info.toString());

txtNetworkInfo.setText(infoString);
}
}
}
}

NOTE:Give permission in AndroidManifest.xml

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


Step 3: Run your project:


WiFi Connected Or Disconnected:




 Bobile data 2G and 3G connection:







Sunday, 31 May 2015

Turn Wifi On/Off using WifiManager and get current state

In this tutorial we learn hoe to write code for turn on/off wifi using WifiManager in android example.Here not only turn on/off wifi,but get current state of wifi and change image according to state.

CREATE NEW ANDROID PROJECT

Step 1: Write code into activity_main.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/hello_world" />

    <ImageButton
        android:id="@+id/onwifi"
        android:layout_width="130dp"
        android:layout_height="130dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:contentDescription="@null"
        android:src="@drawable/wifproc" />

    <ImageButton
        android:id="@+id/offwifi"
        android:layout_width="130dp"
        android:layout_height="130dp"
        android:layout_alignTop="@+id/onwifi"
        android:layout_marginLeft="18dp"
        android:layout_toRightOf="@+id/onwifi"
        android:contentDescription="@null"
        android:src="@drawable/wifiisoff" />


</RelativeLayout>

Step 2: Write code into MainActivity.java

package dev.androidapplink.wifiapp;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends Activity {

ImageButton OnWifi;
ImageButton OffWifi;

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

// wifi on off control
OnWifi = (ImageButton) findViewById(R.id.onwifi);
OffWifi = (ImageButton) findViewById(R.id.offwifi);

// call state change receiver
this.registerReceiver(this.WifiStateChangedReceiver, new IntentFilter(
WifiManager.WIFI_STATE_CHANGED_ACTION));
// set button click event
OnWifi.setOnClickListener(new Button.OnClickListener() {

@Override
public void onClick(View arg0) {

// TODO Auto-generated method stub
// get wifi service

WifiManager wifiManager = (WifiManager) getBaseContext()
.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
});
// set button click event
OffWifi.setOnClickListener(new Button.OnClickListener() {

@Override
public void onClick(View arg0) {

// TODO Auto-generated method stub
// get wifi service
WifiManager wifiManager = (WifiManager) getBaseContext()
.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}
});

}
// call state change receiver on button click
//set image according to wifi state
private BroadcastReceiver WifiStateChangedReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub

int extraWifiState = intent.getIntExtra(
WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);

switch (extraWifiState) {
case WifiManager.WIFI_STATE_DISABLED:

OnWifi.setImageResource(R.drawable.wifioff);
OffWifi.setImageResource(R.drawable.wifiison);
break;
case WifiManager.WIFI_STATE_DISABLING:

OffWifi.setImageResource(R.drawable.wifproc);
break;
case WifiManager.WIFI_STATE_ENABLED:

OnWifi.setImageResource(R.drawable.wifion);
OffWifi.setImageResource(R.drawable.wifiisoff);

break;
case WifiManager.WIFI_STATE_ENABLING:

OnWifi.setImageResource(R.drawable.wifproc);
break;
case WifiManager.WIFI_STATE_UNKNOWN:

break;
}

}
};


}

NOTE:Give permission in AndroidManifest.xml
Its allow to change wifi network state according to setting.

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

Step 3: Now Run Your Project:










Mobile data on/off android example

In this tutorial we learn how to write code for Enable or Disable mobile data connection in android.here not only Enable or Disable data but also get current state of mobile data and set view according to  current sate of Data connection.

CREATE NEW ANDROID PROJECT


Step 1: Write code into activity_mail.xml


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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <ImageButton
        android:id="@+id/tBMobileData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:src="@drawable/dataoff" />

</RelativeLayout>

Step 2: Write code into MainActivity.java

package com.example.dataconnectionapp;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class MainActivity extends Activity {

// controls
ImageButton tBMobileData;
boolean state;

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

// load controls
tBMobileData = (ImageButton) findViewById(R.id.tBMobileData);
// check current state first of mobile data

mobilecheack();

// set click event for button
tBMobileData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

mobilecheack();
// toggle state and set image according to state
if (state) {

toggleMobileDataConnection(false);

tBMobileData.setImageResource(R.drawable.dataoff);

} else {

toggleMobileDataConnection(true);
tBMobileData.setImageResource(R.drawable.dataon);
}

}
});

}

private void mobilecheack() {
// TODO Auto-generated method stub

state = isMobileDataEnable();

// toggle state and set image according to state
if (state) {
tBMobileData.setImageResource(R.drawable.dataon);
} else {
tBMobileData.setImageResource(R.drawable.dataoff);
}

}

public void updateUI1(boolean state) {
// set image according to state
if (state) {
tBMobileData.setImageResource(R.drawable.dataoff);

} else {
tBMobileData.setImageResource(R.drawable.dataon);

}
}

public boolean isMobileDataEnable() {

boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // method is callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean) method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API and do whatever error
// handling here as you want..
}
return mobileDataEnabled;
}

public boolean toggleMobileDataConnection(boolean ON) {
try {
// create instance of connectivity manager and get system service
final ConnectivityManager conman = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
// define instance of class and get name of connectivity manager
// system service class
final Class conmanClass = Class
.forName(conman.getClass().getName());
// create instance of field and get mService Declared field
final Field iConnectivityManagerField = conmanClass
.getDeclaredField("mService");
// Attempt to set the value of the accessible flag to true
iConnectivityManagerField.setAccessible(true);
// create instance of object and get the value of field conman
final Object iConnectivityManager = iConnectivityManagerField
.get(conman);
// create instance of class and get the name of iConnectivityManager
// field
final Class iConnectivityManagerClass = Class
.forName(iConnectivityManager.getClass().getName());
// create instance of method and get declared method and type
final Method setMobileDataEnabledMethod = iConnectivityManagerClass
.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
// Attempt to set the value of the accessible flag to true
setMobileDataEnabledMethod.setAccessible(true);
// dynamically invoke the iConnectivityManager object according to
// your need (true/false)
setMobileDataEnabledMethod.invoke(iConnectivityManager, ON);
} catch (Exception e) {
}
return true;
}

}

NOTE:Give below permissions in AndroidManifest.xml
it allow to access settings and change state according to set.

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

Step 3: Now Run Your Project:










Flight mode or Airplane mode android example

Hello friends,Let understand what is Airplane mode ?
             It will cut of all signal transmissions from mobile called flights mode.In such cases people can put their phone on Flight mode instead of switching it off mobile and continue using other features.
             Airplane mode is an setting in any mobile that suspends all the signal transmitting functions like calls, messaging,DATA connection, Bluetooth, WI-FI etc.in this tutorial is to show you how to switch Airplane mode ON/OFF. In Android Airplane Mode is something like a toggle button, it should be set to 1 - ON, 0 - OFF. 

Step 1: Write code into activity_main.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <ImageButton
        android:id="@+id/tBAirplane"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginTop="104dp"
        android:src="@drawable/flightmodeoff" />

</RelativeLayout>


Step 2: Write code into MainActivity.java


package dev.Androidapplink.flightmodeapp;

import dev.Androidapplink.flightmodeapp.R;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class MainActivity extends Activity {
// controls
ImageButton tBAirplane;

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

tBAirplane = (ImageButton) findViewById(R.id.tBAirplane);

// update UI at first time loading
updateUI(isAirplaneMode());
// set click event for button

tBAirplane.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

// check current state first
boolean state = isAirplaneMode();
// toggle the state
if (state)
toggleAirplaneMode(0, state);
else
toggleAirplaneMode(1, state);
// update UI to new state
updateUI(!state);
}
});
}

// Airplane mode version code
@SuppressLint("NewApi")
public void toggleAirplaneMode(int value, boolean state) {
// toggle airplane mode
// check the version
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { // if
// less
// then
// version
// 4.2

Settings.System.putInt(getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, value);
} else {
Settings.Global.putInt(getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, value);
}
// broadcast an intent to inform
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !state);
sendBroadcast(intent);
}

public void updateUI(boolean state) {
// set image according to state
if (state) {

tBAirplane.setImageResource(R.drawable.flightmodeon);
} else {
tBAirplane.setImageResource(R.drawable.flightmodeoff);
}
}

@SuppressLint("NewApi")
public boolean isAirplaneMode() {
// check the version
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {// if
// less
// than
// version
// 4.2

return Settings.System.getInt(getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
} else {
return Settings.Global.getInt(getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;

}
}

}


NOTE: Give permission in AndroidManifest.xml
Its allow to change setting of device.

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


Step 3: Now Run Project:






Follow me Share