感谢@geob-o-matic发布的代码。
我必须添加一些修改才能工作:
- 带有水平和垂直滚动小部件选择器(由 const 变量更改)
- 带有配置活动
代码中内嵌的额外解释,您可能需要更改某些值,以便查看注释。
const val TIMEOUT: Long = 5000
// WIDGET_SELECTION_AT_X: USE here true or depending
// if you have to scroll at the X or Y axis when
// navigating through widget selection screen.
const val WIDGET_SELECTION_AT_X: Boolean = true
const val WIDGET_NAME: String = "MyAppWigdetName"
@RunWith(AndroidJUnit4::class)
class WidgetAutomatorTest {
private val mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
@Before
fun setWidgetOnHome() {
val screenSize = Point(mDevice.displayWidth, mDevice.displayHeight)
val screenCenter = Point(screenSize.x / 2, screenSize.y / 2)
// showWidgets: This a point on screen between the bottom icons
// and the widgets, its a point that has no objects on a Galaxy S5
// device with stock Launcher. Most probably you have to modify it in
// your device or use an empty homescreen and just long press at
// the center of it.
val showWidgets = Point(825, 1500)
mDevice.pressHome()
val launcherPackage = mDevice.launcherPackageName!!
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), TIMEOUT)
// attempt long press
// Here you can use the screenCenter if you don't have any widget standing/living there!
// ie. mDevice.swipe(arrayOf(showWidgets, screenCenter), 150)
mDevice.swipe(arrayOf(showWidgets, showWidgets), 150)
// Navigate to the system's widget selector, localaize if needed.
mDevice.findObject(By.text("Widgets")).click()
var diment = screenSize.y / 2
if (WIDGET_SELECTION_AT_X) {
diment = screenSize.x / 2
}
var widget = findMyWidget(WIDGET_NAME)
while (widget == null) {
if (WIDGET_SELECTION_AT_X) {
// Swipe left to right
mDevice.swipe(diment, screenCenter.y, 0, screenCenter.y, 150)
} else {
// Swipe top to bottom
mDevice.swipe(screenCenter.x, diment, screenCenter.x, 0, 150)
}
widget = findMyWidget(WIDGET_NAME)
}
// Throw the selected widget on screen
val b = widget.visibleBounds
val c = Point(b.left + 150, b.bottom + 150)
val dest = Point(c.x + 250, c.y + 250)
mDevice.swipe(arrayOf(c, c, dest), 150)
}
private fun findMyWidget(withName: String): UiObject2? {
return mDevice.findObject(By.text(withName))
}
@Test
fun addWidget() {
// Press the button on the Widget Configuration Activity
val okButton = mDevice.findObject(UiSelector()
.text("Add widget")
.className("android.widget.Button"))
okButton.click()
// Find the just added widget
val widget = mDevice.findObject(By.descContains(WIDGET_NAME))
// Click outside the widget in order to added in the screen
mDevice.click(widget.visibleBounds.left - 150, widget.visibleBounds.top - 150)
}
}
笔记。提供的示例在 Galaxy S5、Android 6.0.1、1080x1920 中完美运行。