Ethernet Connectivity through Programmatically (Android) (Rooted Device)

醉酒当歌 提交于 2019-12-28 11:46:46

问题


I have a small issue regarding Ethernet.

My three questions are:

  1. Can we programmatically Turn-On/Off Ethernet?

  2. Can we programmatically Enable/Disable Ethernet?

  3. Can we programmatically Connect Ethernet?

The above Questions are done with the Wifi. Like

  1. We can programmatically Turn-On/Off Wifi.

  2. We can programmatically Enable/Disable Wifi.

  3. We can programmatically Connect Wifi using WifiManager.

Does android provides any EthernetManager like as WifiManager to handle Ethernet?

Or, if this doesn't seem feasible, then my original requirement is:

The first thing I am going to clear is "DEVICE IS ROOTED" .

Can I manipulate the Settings (Default)? Like I don't want any other option in the Settings.apk other than WIFI and Ethernet. It should show only Wifi and Ethernet. That's it. Can I disable all the options from the Settings or Can I remove all the other options from the Settings?


回答1:


The solution I will present here is a hack using reflection and does only work on a rooted android system.

Your device might have the popular android.net.ethernet package. In an Activity, try

Object emInstance = getSystemService("ethernet");

It returns an valid instance of the EthernetManager or null. Null means you are out of luck.

An additional requirement might be depending on your device: Ethernet and Wifi might only work exclusively. You might need to disable Wifi to enable Ethernet and vice versa.

To enable Ethernet by reflection use your instance of the EthernetManager. The method you want to invoke is setEthEnabled(boolean enabled)

    Class<?> emClass = null;
    try {
        emClass = Class.forName("android.net.ethernet.EthernetManager");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Object emInstance = getSystemService("ethernet");

    Method methodSetEthEnabled = null;
    try {
        methodSetEthEnabled = emClass.getMethod("setEthEnabled", Boolean.TYPE);
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    methodSetEthEnabled.setAccessible(true);
    try {
        // new Boolean(true) to enable, new Boolean(false) to disable
        methodSetEthEnabled.invoke(emInstance, new Boolean(false));
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Your application manifest needs these permissions

<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />

The permission WRITE_SECURE_SETTINGS can only be acquired by system apps. The app does not need to be signed by a system key. It can be any valid sign (like the regular Android App Export function). Use busybox to remount the system partition for write access and move your apk into the /system/app folder. Reboot the device and it should work.

Can we programmatically Connect Ethernet ?

There is no Access Point to connect you like with Wifi. You either configure it for DHCP or provide static values. This can of course also be done via reflection. You will need the class EthernetDevInfo for that.

The actual implementation of the EthernetManager and EthernetDevInfo might slightly differ between Android versions and devices as it doesn't have to conform to a public api (yet) and might even be a custom version. To get a list of getters and setters you can use a Introspector or reflection in general.




回答2:


Ok here are some methods i made for manipulating with the ETHERNET INTERFACE (eth0).

1) A method for checking if an ethernet interface exists

public static boolean doesEthExist() {
        List<String> list = getListOfNetworkInterfaces();

        return list.contains("eth0");
    }

public static List<String> getListOfNetworkInterfaces() {

        List<String> list = new ArrayList<String>();

        Enumeration<NetworkInterface> nets;

        try {
            nets = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {

            e.printStackTrace();
            return null;
        }

        for (NetworkInterface netint : Collections.list(nets)) {

            list.add(netint.getName());
        }

        return list;

    }

2) A method for checking if the ETHERNET is enabled or ON

public static boolean isEthOn() {

        try {

            String line;
            boolean r = false;

            Process p = Runtime.getRuntime().exec("netcfg");

            BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream()));   
            while ((line = input.readLine()) != null) {   

                if(line.contains("eth0")){
                    if(line.contains("UP")){
                        r=true;
                    }
                    else{
                        r=false;
                    }
                }
            }   
            input.close();

            Log.e("OLE","isEthOn: "+r);
            return r; 

        } catch (IOException e) {
            Log.e("OLE","Runtime Error: "+e.getMessage());
            e.printStackTrace();
            return false;
        }

    }

3) A method for enabling or disabling the Ethernet depending on the state in which it is

public static void turnEthOnOrOff() {

        try {

            if(isEthOn()){
                Runtime.getRuntime().exec("ifconfig eth0 down");

            }
            else{
                Runtime.getRuntime().exec("ifconfig eth0 up");
            }

        } catch (IOException e) {
            Log.e("OLE","Runtime Error: "+e.getMessage());
            e.printStackTrace();
        }
    }

4) A method for connecting via ethernet depending on the chosen type (dhcp/static)

private boolean connectToStaticSettingsViaIfconfig(StaticConnectionSettings scs) {


        try {

            if(typeChosen.equalsIgnoreCase("dhcp")){

                Runtime.getRuntime().exec("ifconfig eth0 dhcp start");
            }
            else{

                Runtime.getRuntime().exec("ifconfig eth0 "+scs.getIp()+" netmask "+scs.getNetmask()+" gw "+scs.getGateway());
            }

        } catch (IOException e) {
            Log.e("OLE","Runtime Error: "+e.getMessage());
            e.printStackTrace();
            return false;
        }

        return true;
    }

There is one more class which i created for storing all the eth values needed. This class is than initialized with the values the user inserts.

public class StaticConnectionSettings {

    private String ip, netmask, dns, mac, gateway, type;

//Getters and Setters
}

This is it ... I will test it shortly... This code lacks a test phase (ping). And maybe it needs setting of DNS. But this can be done easily. I have not included it because i think on our device it will work also without the DNS setting.




回答3:


It works for Android 6.0.1

Class<?> ethernetManagerClass = Class.forName("android.net.ethernet.EthernetManager");

Method methodGetInstance = ethernetManagerClass.getMethod("getInstance");
Object ethernetManagerObject = methodGetInstance.invoke(ethernetManagerClass);

Method methodSetEthEnabled = ethernetManagerClass.getMethod("setEthernetEnabled", Boolean.TYPE);
methodSetEthEnabled.invoke(ethernetManagerObject, isEnabled);



回答4:


Three Answeres to your above questions:

  1. Yes. You could try using ifconfig eth0 down ; ifconfig eth0 up. But i have not tested it by myself yet.
  2. Yes, but you do not have to. Android does the switching for you. If you connect to WiFi, Ethernet disables. If you are already connected to WiFi and you plug your ethernet cable into the device; you need only to disable WiFi (which you know how to) and android switches automatically to ethernet.
  3. Not so easy as you may think. I have the same problem and until now i have found only one solution which i have not yet tested. Since android runs on the linux kernel, we can use ifconfig in order to manipulate the ethernet connection.

An explanation is hidden here: http://elinux.org/images/9/98/Dive_Into_Android_Networking-_Adding_Ethernet_Connectivity.pdf

And the youtube video of this lecture

http://www.youtube.com/watch?v=LwI2NBq7BWM

And a reference on how to use ifconfig for android

Android ethernet configure IP using dhcp

So if you come to a possible solution, please share it!! If i will do it before you i will certenly.



来源:https://stackoverflow.com/questions/21746192/ethernet-connectivity-through-programmatically-android-rooted-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!