Search code examples
androiddelphifiremonkey

does this code need to be run in the android UI thread?


In the delphi source code i see for exemple this procedure :

procedure TAndroidVideo.RetreiveVideoSize;
var
  MediaPlayer: JMediaPlayer;
begin
  MediaPlayer := TJMediaPlayer.JavaClass.init;
  MediaPlayer.setDataSource(StringToJString(FileName));
  MediaPlayer.prepare;
  FVideoSize := TSize.Create(MediaPlayer.getVideoWidth, MediaPlayer.getVideoHeight);
  MediaPlayer := nil;
end;

that can be run from the main thread. but i think it's a mistake and this procedure must be run from the android UI thread no ? or i miss something ?


Solution

  • According to the docs for MediaPlayer, The call to MediaPlayer.prepare should not be executed on the UI thread. If this code might be running on the UI thread, the call should be changed to MediaPlayer.prepareAsync.

    P.S. In Android, the UI thread and the main thread are the same thing. See, for instance, this post.

    P.P.S. I didn't realize that in Delphi, main thread was something different. My guess, though, is that it's just as bad an idea to block the main thread in Delphi as it to block the UI/main thread in Android. The code you posted will block whatever thread is executing it until prepare returns.

    Regarding your question about using the async methods (prepareAsync, etc.): the call-backs (OnPreparedListener.onPrepared(MediaPlayer), etc), will happen on the UI thread. the thread that called the original asynchronous method, whatever thread that is (which need not be the UI thread but probably needs to be a HandlerThread). This is not bad, because in the call-back handler methods, you typically either call another async method or call a low-latency method (such as MediaPlayer.start).