I want to keep the screen on for a minute on WearOS.
This simple task is such a difficult to handle on Android/WearOS, and all online solutions are simply doesn't work:
class MyActivity: ComponentActivity() {
var mAlarmManager: AlarmManager? = null;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { ... }
mAlarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
d(TAG, "onCreate")
}
override fun onResume() {
super.onResume()
d(TAG, "onResume")
// Let's keep the screen ON ...
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
// ... but listen for a timeout and release the lock
registerReceiver(screenTimeoutReceiver, IntentFilter(ACTION_RELEASE_SCREEN_WAKELOCK));
// Fire this intent with the alarm manager
val releaseScreenIntent = PendingIntent.getBroadcast(
this, 0, Intent(ACTION_RELEASE_SCREEN_WAKELOCK),
FLAG_UPDATE_CURRENT
)
// Define a 1 minute later date and time for alarm manager
val calendar = Calendar.getInstance()
calendar.timeInMillis = System.currentTimeMillis()
calendar.add(Calendar.MINUTE, 1)
// And ask for an exact timer
mAlarmManager?.setExact(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
releaseScreenIntent
)
}
val screenTimeoutReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
d(TAG, "clearFlags")
}
}
}
Desired goal:
- Lock the screen turned ON (OK)
- After 1 minute release it (NOK)
Here is the logcat with my debug notions:
2023-03-19 21:20:28.617 30730-30730 HelloWorld com.example.helloworld D onCreate
2023-03-19 21:20:28.633 30730-30730 HelloWorld com.example.helloworld D onResume
2023-03-19 21:25:47.935 30730-30730 HelloWorld com.example.helloworld D clearFlags
2023-03-19 21:26:03.220 30730-30730 HelloWorld com.example.helloworld D onPause
As you can see this alarm manager is everything but not exact.
Manifest contains the necessary permissions (based on my best knowledge):
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
So, how can I release the screen lock after 1 minute on WearOS?