The solution of calling addFlags()
in FormCreate()
with FLAG_KEEP_SCREEN_ON
doesn't work in Delphi 10.1 Berlin in combination with Android 6 (and probably other combinations).
You will get the following exception:
exception class EJNIException with message
'android.view.ViewRootImpl$CalledFromWrongThreadException: Only the
original thread that created a view hierarchy can touch its views.'.
Somehow the threading of Android/Delphi has changed because this used to work (according to lots of messages). The only way I got it to work (with that one line) was putting this line in the main project-code under Application.Initialize;
.
uses
Androidapi.Helpers,
Androidapi.JNI.GraphicsContentViewText;
begin
Application.Initialize;
SharedActivity.getWindow.addFlags(TJWindowManager_LayoutParams.JavaClass.FLAG_KEEP_SCREEN_ON);
Application.CreateForm(TMainForm, MainForm);
Application.Run;
end.
But when you want to switch this flag on and off during your program you need to be able to execute it in your form-code. In that case you can use CallInUIThreadAndWaitFinishing()
to let this command run in the UIThread. Then you don't get the mentioned exception and the flag works.
uses
FMX.Helpers.Android,
Androidapi.Helpers,
Androidapi.JNI.GraphicsContentViewText;
procedure TMainForm.btnKeepScreenOnAddClick(Sender: TObject);
begin
CallInUIThreadAndWaitFinishing(
procedure
begin
SharedActivity.getWindow.addFlags(
TJWindowManager_LayoutParams.JavaClass.FLAG_KEEP_SCREEN_ON);
end);
end;
procedure TMainForm.btnKeepScreenOnClearClick(Sender: TObject);
begin
CallInUIThreadAndWaitFinishing(
procedure
begin
SharedActivity.getWindow.clearFlags(
TJWindowManager_LayoutParams.JavaClass.FLAG_KEEP_SCREEN_ON);
end);
end;