0

i would like to get data from my host server by using a data connection in mobile. when my app is open it should connect to host server by data connection automatically. when in case of connection lost ... my service should automatically connect to the host sever by enabling the data connection from mobile not using with Bluetooth or WiFi. please help me from this situation

in my code i am using to check whether data connection is

    ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnectedOrConnecting()) {


    //some task

        return true;                
    }
    else{

    Toast.makeText(this, "No internet connection", Toast.LENGTH_SHORT).show();

    }
    return false;
Vinod Kumar
  • 312
  • 4
  • 10
  • I would not recommend using this practice. There might be a viable reason for the user to having turned off the data connection. While I am not sure, I believe that in that case, trying to enable it will only result in error. I would propose that you start a service in the background, checking periodically if the connection is available again and letting your app sleep in the mean time. If the user is actively using the app, catch the error I previously mentioned and ask the user to turn on the connection. – Eric Tobias Apr 02 '13 at 07:32

3 Answers3

2

Use this class as it is and call it methods when ever you want to Enalbe /Disable DataConnection

package com.AZone.eabc;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import android.net.ConnectivityManager;
import android.util.Log;
import android.content.Context;

public class InternetControl {



    public static void EnableInternet(Context mycontext)
    {
        try {
            Log.i("Reached Enable", "I am here");
            setMobileDataEnabled(mycontext,true);
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void DisableInternet(Context mycontext)
    {
        try {
            Log.i("Reached Disable", "I am here");
            setMobileDataEnabled(mycontext,false);
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static void setMobileDataEnabled(Context context , boolean enabled) throws NoSuchFieldException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
           final ConnectivityManager conman = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);

           final Class conmanClass = Class.forName(conman.getClass().getName());

           final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
           iConnectivityManagerField.setAccessible(true);
           final Object iConnectivityManager = iConnectivityManagerField.get(conman);
           final Class iConnectivityManagerClass =  Class.forName(iConnectivityManager.getClass().getName());
           final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
           setMobileDataEnabledMethod.setAccessible(true);

           setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
        }

}

Call methods of this class from AnyWhere like this

 InternetControl.EnableInternet(getBaseContext());

ADD following permissions in You AndroidManifest file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET" />
DeltaCap019
  • 6,532
  • 3
  • 48
  • 70
  • just call the methods enable and disable according to your need it will programatically enable or disable Dataconnection – DeltaCap019 Apr 02 '13 at 06:56
  • ---it doesnot enabling my dataconnection, it just executing those methods. is there any problem with the SIM in my phone . i have two SIM'S in my mobile. is it neccessary to mention which SIM dataconnection is to use before it is connecting.. if yes, then please upload the code – Vinod Kumar Apr 02 '13 at 15:26
  • You cant actually target which SIM you want to use thru code.. as android do no support dual SIM by default. Companies customize it before actually making this OS compatible with Dual SIM.. So no scope for that... THIS Code do not work with FROYO... The sim you had selected by default for data connection actually get enabled thru code without specifying any explicitly.. I have checked it with micromax canvas 2 and canvas HD... and it worked there both are Dual SIMS... but have ICS and Jellybean respectivly – DeltaCap019 Apr 03 '13 at 04:24
  • I call it like this InternetControl.EnableInternet(getBaseContext()); from my first activity onCreate method so as to enable internet as soon as you my activity launches – DeltaCap019 Apr 03 '13 at 04:30
  • you are supposed to add permissions also in manifest file see updated answer – DeltaCap019 Apr 03 '13 at 05:40
  • thank you its working... problem is with my default SIM ... you solved my issue thank you so much Abhinav – Vinod Kumar Apr 03 '13 at 10:01
1

Looks like it doesn't work on some phones witn Android 4.1.X. I've been using this approach for a long time but it crashes on Samsung 5282 Android 4.1.2:

"NoSuchFieldException: mService"

Looks like Samsung removed mService field by itself because it still can be found in the GrepCode:

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.2_r1/android/net/ConnectivityManager.java/

vold_by
  • 330
  • 3
  • 7
0

Use this method to check,Is your device connected to Internet or not. public boolean checkInternetConnection() {

    ConnectivityManager conMgr = (ConnectivityManager)activity.getSystemService(Context.CONNECTIVITY_SERVICE);

    // ARE WE CONNECTED TO THE NET

    if (conMgr.getActiveNetworkInfo() != null

    && conMgr.getActiveNetworkInfo().isAvailable()

    && conMgr.getActiveNetworkInfo().isConnected()) {

        return true;

    } else {
        return false;

    }
} 

Put this inside the click event:

boolean Connection;
Connection = checkInternetConnection();
if(Connection==false){
            //No internet connection    

            }
            else{
            //Here do what ever you do next
            }
Yugesh
  • 4,030
  • 9
  • 57
  • 97