如何在Espresso中读取Android设备的系统时区
问题描述
我需要编写一个Espresso测试用例来读取设备的时区。我知道可以通过adb shell命令在命令行输出设备时间戳(示例如下):
c:>adb shell date
Mon Aug 8 17:46:23 EDT 2022
从中可以提取时区信息EDT。但如何在Espresso中实现该功能呢?我尝试在Espresso代码中执行上述adb shell命令,如下所示,但测试仅执行完成却未得到预期结果:
package com.mycompany.ui.activity; import java.io.IOException; import org.junit.Test; public class FindTimeZone { @Test public void findTimeZone() throws InterruptedException { String command = "cmd.exe /c adb shell date"; try { Process process = Runtime.getRuntime().exec(command); } catch ( IOException ignored) { } }//findTimeZone() }//class FindTimeZone
解决方案
你的代码存在两个核心问题:一是启动进程后未读取输出内容,自然拿不到结果;二是直接在测试代码中调用主机端的adb shell并非最佳实践——Espresso测试运行在设备进程中,无法直接依赖主机环境。以下是两种可行的实现方式:
方法一:直接调用Android系统API(推荐)
无需依赖adb,直接通过Android系统API获取时区,这是最可靠的方式:
package com.mycompany.ui.activity; import java.util.TimeZone; import org.junit.Test; import static org.junit.Assert.assertNotNull; public class FindTimeZone { @Test public void findTimeZone() { // 获取系统默认时区实例 TimeZone timeZone = TimeZone.getDefault(); // 获取时区ID(如"America/New_York") String timeZoneId = timeZone.getID(); // 获取时区简称(如夏令时的"EDT"或标准时间的"EST") String timeZoneShortName = timeZone.getDisplayName(timeZone.inDaylightTime(new java.util.Date()), TimeZone.SHORT); System.out.println("时区ID: " + timeZoneId); System.out.println("时区简称: " + timeZoneShortName); assertNotNull("时区信息不能为空", timeZoneShortName); } }
方法二:通过Instrumentation执行设备端命令
如果一定要通过date命令的方式获取,可以用Instrumentation在设备端直接执行shell命令,而非依赖主机的adb:
package com.mycompany.ui.activity; import android.app.Instrumentation; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.junit.Test; import androidx.test.platform.app.InstrumentationRegistry; public class FindTimeZone { @Test public void findTimeZone() throws IOException { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); // 在设备端执行date命令 Process process = instrumentation.getUiAutomation().executeShellCommand("date"); // 读取命令输出内容 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; StringBuilder output = new StringBuilder(); while ((line = reader.readLine()) != null) { output.append(line); } reader.close(); // 从输出中提取时区信息(按空格分割后取第5个元素) String dateOutput = output.toString(); String timeZone = dateOutput.split(" ")[4]; System.out.println("提取的时区: " + timeZone); } }
内容的提问来源于stack exchange,提问作者Jamil Rahman
相关产品推荐
相关产品推荐

