文档章节

Robotium todolist.test.utils

c
 children009
发布于 2016/10/18 10:49
字数 870
阅读 8
收藏 0

NetworkUtil

package com.example.todolist.test.utils;

import java.lang.reflect.Method;

import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.telephony.TelephonyManager;
import android.util.Log;

/**
 * Class is used for working with network (switch on/off Airplane mode, mobile Network, Wifi)
 */
public class NetworkUtil {

    private static final String DISABLE_DATA_CONNECTION_METHOD = "disableDataConnectivity";
    private static final String ENABLE_DATA_CONNECTION_METHOD = "enableDataConnectivity";
    private static final String I_TELEPHONY_METHOD = "getITelephony";
    private static final String TAG = "NetworkSwitcher";

    /**
     * Switch off AirplaneMode, mobile network and wifi
     * 
     * @param context
     * @throws Exception
     */
    public static void setAllPossibleNetworksOn(Context context) throws Exception {
        if (isAirplaneModeOn(context)) {
            boolean success = setAirplaneModeOff(context);
            if (!success) {
                throw new IllegalStateException("AirplaneMode was NOT turned ON");
            }
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        byte numberOfErrors = 0;
        try {
            setNetworkOn(context);
        } catch (Exception e) {
            numberOfErrors++;
        }
        try {
            setWifiOn(context);
        } catch (Exception e) {
            numberOfErrors++;
        }
        if (numberOfErrors == 2) {
            throw new Exception("Wifi and Network are not turned on");
        }
    }

    /**
     * Switch off Wifi network
     * 
     * @param context
     *            - Context
     * @return true if Wifi was switched off successfully
     * @throws SettingNotFoundException
     *             if Wifi settings were not found
     */
    public static boolean setWifiOff(Context context) throws SettingNotFoundException {
        WifiManager wifiMng = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiMng == null) {
            return false;
        }
        if (!wifiMng.isWifiEnabled()) {
            return true;
        }
        Settings.System.putInt(context.getContentResolver(), Settings.Secure.WIFI_ON, 0);
        try {
            wifiMng.setWifiEnabled(false);
            Settings.System.putInt(context.getContentResolver(), Settings.Secure.WIFI_ON, 0);
            return !wifiMng.isWifiEnabled();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * Switch On Wifi network
     * 
     * @param context
     *            - Context
     * @return true if Wifi successfully switched on
     * @throws SettingNotFoundException
     *             if Wifi settings were not found
     */
    public static boolean setWifiOn(Context context)  {
        WifiManager wifiMng = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiMng == null) {
            return false;
        }
        if (wifiMng.isWifiEnabled()) {
            return true;
        }
        Settings.System.putInt(context.getContentResolver(), Settings.Secure.WIFI_ON, 1);
        try {
            wifiMng.reassociate();
            wifiMng.reconnect();
            wifiMng.setWifiEnabled(true);
            Settings.System.putInt(context.getContentResolver(), Settings.Secure.WIFI_ON, 1);
            Thread.sleep(5000);
            return wifiMng.isWifiEnabled();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * Verify is Wifi network on now
     * 
     * @param context
     *            - Context
     * @return true if Wifi is switched on
     * @throws SettingNotFoundException
     */
    public static boolean isWifiOn(Context context) throws SettingNotFoundException {
        int value = Settings.System.getInt(context.getContentResolver(), Settings.Secure.WIFI_ON);
        return value == 0 ? false : true;
    }

    /**
     * @param context
     *            - Context
     * @return true if Network switched off successfully
     * @throws SettingNotFoundException
     */
    public static boolean setNetworkOff(Context context) throws SettingNotFoundException {
        boolean isEnabled = true;
        if (!isNetworkOn(context)) {
            return true;
        }
        isEnabled = changeNetworkState(context, DISABLE_DATA_CONNECTION_METHOD);
        return !isEnabled;
    }

    /**
     * @param context
     *            - Context
     * @return true if Network switched on successfully
     * @throws SettingNotFoundException
     */
    public static boolean setNetworkOn(Context context) throws SettingNotFoundException {
        boolean isEnabled = false;
        if (isNetworkOn(context)) {
            return true;
        }
        isEnabled = changeNetworkState(context, ENABLE_DATA_CONNECTION_METHOD);
        return isEnabled;
    }

    /**
     * @param context
     *            - Context
     * @return true if it is mobile network connection
     */
    public static boolean isNetworkOn(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        return telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED ? true : false;
    }

    /**
     * 
     * @param context
     * @return true if AirplaneMode is switched successfully
     * @throws SettingNotFoundException
     */
    public static boolean setAirplaneModeOn(Context context) throws SettingNotFoundException {
        if (isAirplaneModeOn(context)) {
            return true;
        }
        boolean success = Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 1);
        if (!success) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", true);
        context.sendOrderedBroadcast(intent, null);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
        }
        return success;
    }

    /**
     * @param context
     * @return true if Airplane mode is on
     * @throws SettingNotFoundException
     */
    public static boolean isAirplaneModeOn(Context context) throws SettingNotFoundException {
        int value = Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON);
        return value == 0 ? false : true;
    }

    /**
     * 
     * @param context
     * @return true if airplane mode is switched successfully
     * @throws SettingNotFoundException
     */
    public static boolean setAirplaneModeOff(Context context) throws SettingNotFoundException {
        if (!isAirplaneModeOn(context)) {
            return true;
        }
        boolean success = Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0);
        if (!success) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", false);
        context.sendOrderedBroadcast(intent, null);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }
        return success;
    }

    private static boolean changeNetworkState(Context context, String method) throws SettingNotFoundException {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        try {
            Method dataConnSwitchmethod = null;
            Class<?> telephonyManagerClass;
            Object ITelephonyStub;
            Class<?> ITelephonyClass;

            telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
            Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod(I_TELEPHONY_METHOD);
            getITelephonyMethod.setAccessible(true);
            ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
            ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());
            Log.i(TAG, "changeNetworkState(): " + "ITelephonyStub = " + ITelephonyStub.toString());
            dataConnSwitchmethod = ITelephonyClass.getDeclaredMethod(method);
            Log.i(TAG, "changeNetworkState(): " + "ITelephonyClass = " + ITelephonyClass.getName());
            Log.i(TAG, "changeNetworkState(): " + "dataConnSwitchmethod = " + dataConnSwitchmethod.getName());
            dataConnSwitchmethod.setAccessible(true);
            dataConnSwitchmethod.invoke(ITelephonyStub);
            Thread.sleep(5000);
        } catch (Exception e) {
            Log.i(TAG, "changeNetworkState(): Exception: " + e);
            if (method == DISABLE_DATA_CONNECTION_METHOD) {
                setAirplaneModeOn(context);
            }
        }
        return telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED;
    }

    /**
     * Switch on all types of connection
     * 
     * @param context
     */
    public static void setAirplaneModeOffAndNetworkOn(Context context) {
        try {
            if (isAirplaneModeOn(context)) {
                setAirplaneModeOff(context);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    Log.e("[TestRC]", "setAirplaneModeOffAndNetworkOn() : " + e);
                }
            }
        } catch (Exception e) {
            // do nothing
        }
        try {
            setNetworkOn(context);
        } catch (Exception e) {
            // do nothing
        }
        try {
            setWifiOn(context);
        } catch (Exception e) {
            // do nothing
        	e.printStackTrace();
        }
    }

    /**
     * Switched Off all types of connection
     * 
     * @param context
     * @throws NetworkSwitchException
     * @throws SettingNotFoundException
     */
    public static void setAllPossibleNetworksOff(Context context) throws SettingNotFoundException {
        setWifiOff(context);
        try {
            waitForWifiOff(context);
        } catch (Exception e1) {
            Log.e(TAG, e1.getMessage());
        
        setNetworkOff(context);
        try {
            Thread.sleep(6000);
        } catch (Exception e) {
            // ignore
        }
        }
    }

    private static void waitForWifiOff(Context context) throws Exception {
        boolean isWifiOff = false;
        long startTime = System.currentTimeMillis();
        do {
            Thread.sleep(500);
            isWifiOff = !isWifiOn(context);
        } while (!isWifiOff && (System.currentTimeMillis() - startTime < 10000));
        if (!isWifiOff) {
            throw new Exception("Wifi is not turned off");
        }
    }

    public static void waitForWifiOrNetworkOn(Context context) throws Exception {
        boolean isWifiOrNetworkOn = false;
        long startTime = System.currentTimeMillis();
        do {
            Thread.sleep(500);
            isWifiOrNetworkOn = isWifiOn(context) || isNetworkOn(context);
        } while (!isWifiOrNetworkOn
                && (System.currentTimeMillis() - startTime < 10000));
        if (!isWifiOrNetworkOn) {
            throw new Exception("Wifi and Network is not turned on");
        }
    }

}

Util

package com.example.todolist.test.utils;

import android.app.Instrumentation;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.test.InstrumentationTestCase;
import android.util.Log;

public class Util {
	
	/**
	 * 唤醒设备的方法
	 * @param owner
	 * @return
	 */
	public static WakeLock wakeScreen(InstrumentationTestCase owner) {
		PowerManager pm = (PowerManager) owner.getInstrumentation()
				.getTargetContext().getSystemService(Context.POWER_SERVICE);
		WakeLock wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
				| PowerManager.FULL_WAKE_LOCK
				| PowerManager.ACQUIRE_CAUSES_WAKEUP, owner.getClass()
				.getSimpleName());
		wakeLock.acquire();
		return wakeLock;
	}

	/**
	 * 解锁的方法
	 * @param instr
	 */
	public static void unlock(Instrumentation instr) {
		try {
			Context targetContext = instr.getTargetContext();
			KeyguardManager keyGuardManager = (KeyguardManager) targetContext
					.getSystemService(Context.KEYGUARD_SERVICE);
			KeyguardLock mLock = keyGuardManager.newKeyguardLock("");
			mLock.disableKeyguard();
		} catch (Throwable e) {
			Log.e("TEST", "unlock failed:", e);
		}
	}
}

 

© 著作权归作者所有

c
粉丝 1
博文 18
码字总数 6231
作品 0
广州
私信 提问
Android集成测试框架--Robotium

robotium 是 Android 平台上类似 Selenium 的集成测试工具。有JUnit基础的开发者,还是非常容易上手的。 Robotium 是一款国外的Android自动化测试框架,主要针对Android平台的应用进行黑盒自...

匿名
2011/02/24
20K
0
Robotium 5.2.1 发布,Android 集成测试框架

Robotium 5.2.1 发布,下载地址: robotium-solo-5.2.1.jar robotium-solo-5.2.1-javadoc.jar ExampleTestProject_v5.2.1.zip 新特性: Solo(Instrumentation instrumentation, Config confi......

oschina
2014/07/01
11.2K
11
android robotium获取相同id的的控件

android robotium获取相同id的的控件:http://blog.csdn.net/busjb/article/details/16808551 robotium中同一id的怎么确定点击哪一个:http://zhidao.baidu.com/link?url=QMTQ86nIqfGS8l1xki......

智能小松鼠
2015/07/31
71
0
android 自动化测试的傻瓜实践之旅(UI篇) -----小试身手

导言 很早以前就开始折腾android的自动化测试,不过,本人毫无测试基础,只能,从google那里搜索到仅有的一些资源,和目前,唯一一本讲android测试的书(应该是吧,如果还有希望告之). 从google那里...

打杂程序猿
2012/03/17
2.6K
13
Robotium 测试多个activity

How to test two activities with Robotium:http://stackoverflow.com/questions/16019011/how-to-test-two-activities-with-robotium...

智能小松鼠
2015/05/07
132
0

没有更多内容

加载失败,请刷新页面

加载更多

关于AsyncTask的onPostExcute方法是否会在Activity重建过程中调用的问题

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/XG1057415595/article/details/86774575 假设下面一种情况...

shzwork
今天
6
0
object 类中有哪些方法?

getClass(): 获取运行时类的对象 equals():判断其他对象是否与此对象相等 hashcode():返回该对象的哈希码值 toString():返回该对象的字符串表示 clone(): 创建并返此对象的一个副本 wait...

happywe
今天
6
0
Docker容器实战(七) - 容器中进程视野下的文件系统

前两文中,讲了Linux容器最基础的两种技术 Namespace 作用是“隔离”,它让应用进程只能看到该Namespace内的“世界” Cgroups 作用是“限制”,它给这个“世界”围上了一圈看不见的墙 这么一...

JavaEdge
今天
8
0
文件访问和共享的方法介绍

在上一篇文章中,你了解到文件有三个不同的权限集。拥有该文件的用户有一个集合,拥有该文件的组的成员有一个集合,然后最终一个集合适用于其他所有人。在长列表(ls -l)中这些权限使用符号...

老孟的Linux私房菜
今天
7
0
面试套路题目

作者:抱紧超越小姐姐 链接:https://www.nowcoder.com/discuss/309292?type=3 来源:牛客网 面试时候的潜台词 抱紧超越小姐姐 编辑于 2019-10-15 16:14:56APP内打开赞 3 | 收藏 4 | 回复24 ...

MtrS
今天
6
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部