How do I pause the UI thread?
I have a background thread that isn't receiving enough time, and DoEvents doesn't process anything in the background.
I don't want to come up with some complicated method to do it with a Timer either.
This is a roadblock to my app. Without this problem licked, it won't work.
Your problem is a bit vague without further explanation. So here's a theoretical answer:
From the Google doc: "Ensure you do any disk access, network access, or SQL access in a separate thread." Why? Because the result and duration of these accesses is uncertain. They can last a long time and let the system think that the application is hung or unresponsive (the famous ANR: application not responding).
That being said, how to stop the flow of the program and wait until the access is completed?
One of the ideas that come to mind is to add the following code to the main thread:
MyFlag = false
do until MyFlag = true
DoEvents
loop
...and to change the flag state in the event handler of the operation. Thus, the loop in the main thread waits until MyFlag becomes true and, in theory, should exit as soon as the event is received, but the problem is that most events are not fired by B4A during a DoEvents. It's obvious if you try to rotate the device while the loop is running. No Activity_Create, no Activity_Resume, and a weird display.
The simplest solution is to reorganize your code.
Example:
Sub MyMainSub
DoA
WaitForAccess
DoB
End Sub
...is split into two subs:
Sub MyMainSub
DoA
WaitForAccess
End Sub
Sub AfterAccess
DoB
End Sub
AfterAccess is called by the event handler of WaitForAccess when the operation is successful. In this way, you can wait for ages without risking ANR.
Fine, but this does not prevent the user from clicking buttons, scrolling lists, etc. As we saw, you cannot block the main thread while you wait for the access completion, and the main thread is the UI thread. So, what to do? One possible solution is to disable all views while waiting. Set Enabled to false or/and ignore click and touch events. You can also display a Cancel button.
A last useful thing: setting a Timer for timeouts. After a defined period, it cancels the access and displays an error message to the user.