0

I want to check whether mobile data is on/off, and for this I use the below code:

ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
Class cmClass = Class.forName(cm.getClass().getName());
        Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
        method.setAccessible(true); // Make the method callable
        // get the setting for "mobile data"
        mobileDataEnabled = (Boolean) method.invoke(cm);

However, this code does not work on some devices, and throws an exception that no such method exists. I have found it is not working in Android 4.1.x. Why is it throwing this execption, and how can I fix it?

User10001
  • 1,295
  • 2
  • 18
  • 30

1 Answers1

0

connection.java

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
        this._context = context;
    }

    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //return (connectivity != null && connectivity.getActiveNetworkInfo().isConnectedOrConnecting()) ? true : false;
        if (connectivity.getActiveNetworkInfo() != null && connectivity.getActiveNetworkInfo().isAvailable() &&    connectivity.getActiveNetworkInfo().isConnected()) 
        {

               return true;
         } else {
               //System.out.println("Internet Connection Not Present");
             return false;

         }
    }
}

internetchecking.java

Boolean isInternetPresent = false;
    ConnectionDetector cd;

cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
 if(isInternetPresent)
{

dotask();

}
else
{
    display("No Internet Connection...");
}

In emulator use F8 key for on of Internet connection

learner
  • 3,092
  • 2
  • 21
  • 33