Skip to content Skip to sidebar Skip to footer

Unable To Toggle Airplane Mode, Espresso

I am trying to toggle airplane mode on kitkat version, on rooted emulator. I am using espresso for automation and i have scenario in which i have to switch on airplane mode and do

Solution 1:

Simply create method as follows and call wherever required:

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

        setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
    }

Calling the method:

try {
            CommonUtil.setMobileDataEnabled(mActivityTestRule.getActivity().getApplicationContext(),true);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

Please note, this will set Data enabled = Off.. which is my requirement.

Post a Comment for "Unable To Toggle Airplane Mode, Espresso"