0

i am new to android but i know few thinks but this one is hard for me:

First i want to check if i am connected to the internet: works. then i want to check if the mobile data/wifi i enabled: works. and then i want to turn on the mobile network (if its disabled) to check if i have a (good?) connection to the internet: dont work

I used the code from https://stackoverflow.com/a/8962211/1879409 but i dont know how i can call this methode? I also want to do this in an seperate class file (.java file) and call this function from my main activity.

Can someone give me an example how i can do this??

Thanks for all answers xD

EDIT

Now it looks like this in my Settings.java:

    import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;

public class SettingsHelper {

    static void setMobileDataEnabled(Context context, boolean enabled) {
        try {

            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);
            Log.i("setMobileDataEnabled()","OK");
        } 

        catch (Exception e) 
        {
            e.printStackTrace();
            Log.i("setMobileDataEnabled()","FAIL");
        }         
    }
}

If i call Settings.setMobileDataEnabled(context, true); from my MainActivity i get:

    02-01 14:51:19.680: W/System.err(23318): java.lang.NullPointerException
02-01 14:51:19.700: W/System.err(23318):    at at.htlmbprojekt.wksimonsfeld.iceapp.SettingsHelper.setMobileDataEnabled(SettingsHelper.java:15)
02-01 14:51:19.700: W/System.err(23318):    at at.htlmbprojekt.wksimonsfeld.iceapp.MainActivity.checkIfStorageAvailable(MainActivity.java:83)
02-01 14:51:19.700: W/System.err(23318):    at at.htlmbprojekt.wksimonsfeld.iceapp.MainActivity.access$4(MainActivity.java:81)
02-01 14:51:19.700: W/System.err(23318):    at at.htlmbprojekt.wksimonsfeld.iceapp.MainActivity$2.onClick(MainActivity.java:76)
02-01 14:51:19.700: W/System.err(23318):    at android.view.View.performClick(View.java:4211)
02-01 14:51:19.700: W/System.err(23318):    at android.view.View$PerformClick.run(View.java:17267)
02-01 14:51:19.700: W/System.err(23318):    at android.os.Handler.handleCallback(Handler.java:615)
02-01 14:51:19.700: W/System.err(23318):    at android.os.Handler.dispatchMessage(Handler.java:92)
02-01 14:51:19.700: W/System.err(23318):    at android.os.Looper.loop(Looper.java:137)
02-01 14:51:19.700: W/System.err(23318):    at android.app.ActivityThread.main(ActivityThread.java:4898)
02-01 14:51:19.700: W/System.err(23318):    at java.lang.reflect.Method.invokeNative(Native Method)
02-01 14:51:19.700: W/System.err(23318):    at java.lang.reflect.Method.invoke(Method.java:511)
02-01 14:51:19.700: W/System.err(23318):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
02-01 14:51:19.700: W/System.err(23318):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
02-01 14:51:19.700: W/System.err(23318):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:103)
02-01 14:51:19.700: W/System.err(23318):    at dalvik.system.NativeStart.main(Native Method)

Maybe because the context is null? If yes what should i do with he context? If anyone can solve my problem pls send me the WHOLE code and not only some snippets i am a beginner and i dont know what i should do with these snippets xD

Community
  • 1
  • 1
Pali
  • 1,337
  • 1
  • 14
  • 40
  • well calling setMobileDataEnabled method in mentioned post seems to be very straight forward, calling it is no different then calling any other method. What seems to be the problem? – Waqas Jan 30 '13 at 14:14

3 Answers3

1

First of all, in order to make your code easily readable you can use 'generic' exceptional handler but why using generic exceptional handler isn't a good idea instead of specific exceptions is a different topic about which you can read here: http://www.javaworld.com/javaworld/jw-10-2003/jw-1003-generics.html

Anyway now regarding your actual question, try the code given below, i didn't make change except formatted it to make it more readable and the reason why you are getting NULL exception because you are trying to use an object outside the scope it was instantiated in.

private void setMobileDataEnabled(Context context, boolean enabled) {
    try {

        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);

    } catch (Exception e) {
        e.printStackTrace();
    }         
}
Waqas
  • 6,812
  • 2
  • 33
  • 50
  • see my edit pls ... if i would write it in a comment some admin would remind me of posting a NEW question ... THANK you for your time and help :) – Pali Feb 01 '13 at 15:10
  • 1
    @Waqas: On Android L, the above solution returns `NoSuchMethodException`, even though the method is there in the source codes. I think Google has closed a lot of options for using Reflection - which is a shame really. Also, you should mention in your answer that your solution only works on Android 2.3+. Older Android versions will not work with this solution. – ChuongPham Jul 09 '14 at 06:05
  • @ChuongPham were you able to find a way to get it working on Android L? – Flyview Sep 15 '14 at 20:25
  • @Flyview: No. Unless Google reverse their decision to not export the `setMobileDataEnabled()` method in Android L firmware, then there's no way of enabling/disabling mobile network from Android L onwards. Reflection will be useless. – ChuongPham Sep 16 '14 at 08:00
  • @ChuongPham What do you mean they exported it into the firmware? Do you have some links with info? Thanks! – Flyview Sep 16 '14 at 22:42
  • @Flyview: Just download the source codes of Android L via Android SDK Manager, then create an Android L emulator and test it for yourself. So, even though the `setMobileDataEnabled()` is available in codes, it's not possible to call this method in an Android L emulator without getting the `NoSuchMethodException` error. – ChuongPham Sep 18 '14 at 12:41
  • @ChuongPham Yes, I did that before and hence why I'm looking for another solution. I'm trying to understand how that can be the case (the method is there in the source code) but is not there through reflection. Send me an email so we can discuss further? teqtic@gmail.com – Flyview Sep 18 '14 at 16:06
0

Please check your manifest and make sure permission "CHANGE_NETWORK_STATE" has been added.

superarts.org
  • 7,009
  • 1
  • 58
  • 44
  • FYI, it's not an answer but should be a comment. FYI, you should leave a comment if you would want to more clarification regarding issue. – Paresh Mayani Feb 21 '14 at 06:32
  • "Is xxx already added" is not a question but a way to suggest people doing something. Anyway, I edited my answer so that people will not get confused. – superarts.org Feb 21 '14 at 09:20
  • Thanks for the kind words :) I just tried to share a SO standard and common practice that we all should follow, rest choice is yours! – Paresh Mayani Feb 21 '14 at 09:41
0

If you want to create a class to use your code, do the following:

Create a new class, in the same package of the MainActivity.

Give it any name, for example: MyNetwork.

Write the following:

public class MyNetwork {

    setMobileDataEnabled(Context context, boolean enabled){

        ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        Method setMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);

        setMobileDataEnabledMethod.setAccessible(true);
        setMobileDataEnabledMethod.invoke(conman, enabled);

        }

}

Now just call it from anywhere:

MyNetwork mn;

mn.setMobileDataEnabled(getBaseContext(), true) //or false to disable your data.

You can create any methods inside your class, to call it, just call as:

mn.yourMethod()

Check if you have declared the right permissions in your Manifest.xml.

Murillo Ferreira
  • 1,423
  • 1
  • 16
  • 31