Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my Android app exit suddenly?

I am using Delphi 10.2 to create Android app that uses Rest components to read returning data from post form. When I press on a button to load the data it load them normally after about 3 seconds freeze. The problem if the user try to click (or touch) any control on the form the app exit immediately after the 3 seconds freeze but if the user did not touch the app the data was loaded normally !

What is the reason for that and how I should fix it ?

The code I use for the button is

RESTRequest1.Execute;

I use 3 components RESTClient , RESTRequest and RESTResponse

and here is the code I use to get the data:

procedure TfrmMain.RESTRequest1AfterExecute(Sender: TCustomRESTRequest);
var
return_response: string;
begin
  if RESTResponse1.StatusCode = 200 then begin
    //fill years
    return_response := RESTResponse1.Content;

    memo1.text := return_response;

  end;

end.
like image 926
zac Avatar asked Mar 08 '23 22:03

zac


1 Answers

On mobile platforms you should always use ExecuteAsync because it does not run in the same thread as the UI. Execute instead runs on the same thread as the UI so it freezes while the request is processing. Android closes the app if it is not responsive (= freezed) after some seconds, and this is your problem!

To be more precise, here's the doc:

The use of the ExecuteAsync method is strongly recommended on mobile platforms. iOS (and likely Android) will terminate an application if it considers the main thread to be unresponsive, i.e. if a running request takes more than a second or two to return

You can find more info here.


The function ExecuteAsync, as you can see in the doc, has an useful parameter which takes an anonymous procedure. The code of this procedure will be called once the ExecuteAsync has finished his task. Here's an example:

RESTRequest1.ExecuteAsync(
 procedure
 begin
  ShowMessage('Finished!');
 end;);

This is very easy and also you don't need to type the other parameters since they alrady have a value by default. Again, if you look at the doc you'll see for example ASynchronized: Boolean = True;, so setting the second parameter after the anonymous proc to True would be not relevant.

like image 156
Alberto Miola Avatar answered Mar 16 '23 01:03

Alberto Miola