Skip to content Skip to sidebar Skip to footer

Ask User To Activate Mobile Network/3g Via A Dialog Type Alert In Android

I am developing an Android Application and I need to make sure that the user is connected to the internet somehow. I can already check for WiFi, however, not everyone will be near

Solution 1:

First of all, you have to use this permission:

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

After that, with this code, you can know whether it connected to internet by mobile data or not:

publicstaticbooleanisConnectedMobile(Context context){
    NetworkInfoinfo= Connectivity.getNetworkInfo(context);
    return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}

UPDATE 1: If you want to enable/disable the mobile network in your app, you can use this solution:

privatevoidenableMobileData(Context context, boolean enabled)throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    finalConnectivityManagercm= (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
    finalClassconmanClass= Class.forName(cm.getClass().getName());
    finalFieldconnectivityManagerField= conmanClass.getDeclaredField("mService");
    connectivityManagerField.setAccessible(true);
    finalObjectconnectivityManager= connectivityManagerField.get(cm);
    finalClassconnectivityManagerClass=  Class.forName(connectivityManager.getClass().getName());
    finalMethodsetMobileDataEnabledMethod= connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);

    setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
}

And don't forget to use this permission:

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

Post a Comment for "Ask User To Activate Mobile Network/3g Via A Dialog Type Alert In Android"