Sunday 31 May 2015

Mobile data on/off android example

2 comments
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:










2 comments :

  1. dataon source is showing error in main activity please tell me how should i remove this error...

    ReplyDelete
  2. I'am geting e : java.lang.NoSuchMethodException: setMobileDataEnabled [boolean] exception from try-catch block of toggleMobileDataConnection method

    ReplyDelete

Follow me Share