The problem My Android automated tests are unreliable, because the tested activities are sometimes running and are sometimes paused.
The cau
In Kotlin,
For Api level 28 or less, you can simply add below method in your activity that needs to be opened:
override fun onAttachedToWindow() {
super.onAttachedToWindow()
toBeShownOnLockScreen()
}
private fun toBeShownOnLockScreen() {
window.addFlags(
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setTurnScreenOn(true)
setShowWhenLocked(true)
} else {
window.addFlags(
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
)
}
}
And to make it work on Android Pie and above, in addition to above step, we need to set in AndroidManifest as well:
<activity
android:name=".view.activity.LockScreenActivity"
android:showOnLockScreen="true"
android:showWhenLocked="true"
android:turnScreenOn="true" />
I have tested this code from Api level 21 to 29, and works like charm!
Update: some Samsung devices (Samsung Galaxy S7 edge in my case) may fail to work if toBeShownOnLockScreen()
is called inside onAttachedToWindow()
. So, there you simply call toBeShownOnLockScreen()
inside onCreate()
of Activity. That's it.
You can disable your lockscreen by using following code.Include this code in oncreate of your activity .
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "INFO");
wl.acquire();
KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
kl = km.newKeyguardLock("name");
kl.disableKeyguard();
In manifest include permission:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
android:keepScreenOn='true'
use this attribute in rootView like this
<LinearLayout
xmlns:android=`http://schemas.android.com/apk/res/android`
xmlns:app=`http://schemas.android.com/apk/res-auto`
android:layout_width=`match_parent`
android:layout_height=`match_parent`
android:keepScreenOn="true">