在android上打开和关闭以太网

在android上打开和关闭以太网,android,networking,ethernet,Android,Networking,Ethernet,是否有一种方法可以通过编程打开和关闭以太网,类似于如何通过WiFiManager类打开和关闭WiFi?我相信ifconfig down/up不会工作,因为它需要root。我在终端仿真器中执行ifconfig wlan0 down,这给了我被拒绝的权限 我使用的是非根设备。首先,您应该知道,由于android Q,WifiManager类不起作用 此方法在API级别29中被弃用。 从Build.VERSION_code#Q开始,应用程序不允许启用/禁用Wi-Fi。兼容性说明:对于目标为Build.

是否有一种方法可以通过编程打开和关闭以太网,类似于如何通过
WiFiManager
类打开和关闭WiFi?我相信ifconfig down/up不会工作,因为它需要root。我在终端仿真器中执行
ifconfig wlan0 down
,这给了我被拒绝的权限


我使用的是非根设备。

首先,您应该知道,由于android Q,
WifiManager
类不起作用

此方法在API级别29中被弃用。 从Build.VERSION_code#Q开始,应用程序不允许启用/禁用Wi-Fi。兼容性说明:对于目标为Build.VERSION\u code.Q或更高版本的应用程序,此API将始终返回false,并且不会产生任何效果。如果应用程序的目标是较旧的SDK(Build.VERSION\u CODES.P或更低版本),它们可以继续使用此API

对于网络和wifi,我建议您显示一个权限对话框,让用户打开它,它与android权限管理器匹配

您可以使用以下代码打开设置

Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setComponent(new ComponentName("com.android.settings",
                "com.android.settings.Settings$DataUsageSummaryActivity"));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

如果目标SDK低于Q,可以尝试使用反射方式

private void setMobileDataEnabled(Context context, boolean enabled) throws Exception{
    final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    Class conmanClass = null;
    try {
        conmanClass = Class.forName(conman.getClass().getName());
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    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);
}

我希望在没有用户干预的情况下,有计划地关闭和打开以太网。此外,我使用Wifi Manager作为API的一个示例,可以通过编程启用/禁用网络通信。我不确定您建议的对话框会做什么。对于9以上的SDK,这些方法不起作用。见comment@StealthRabbi,我给出了一个实现它的反射方法,如果它仍然有效,你可以尝试一下。我不认为启用移动数据与启用/禁用以太网具有相同的效果。