在服务中同步执行 long 运行 方法

Synchronously executing long running methods in a Service

我有一个具有一组操作的 android 服务:

MyService.java

public class MyService extends Service {

    public int login() {
      //Invokes yet another logic to initiate login and waits for result 
      //synchronously and returns status code based on result of operation
    }

    public int logout() {
      //Invokes yet another logic to initiate logout and waits for result 
      //synchronously and returns the status code
    }
}

我正在调用客户端 activity 的方法,例如,MyClientActivity.java 驻留在同一进程中。

对于每个操作,服务调用一些逻辑并以同步方式等待结果。当服务执行所有这些逻辑时,我不希望用户执行任何其他操作,只显示一个加载屏幕。所以基本上,在我启动一个操作后,我希望 MyClientActivity 同步等待状态代码。现在我知道我不能阻止 UI 线程来避免 ANR。
我怎样才能让这个操作在一个单独的线程上执行,然后取回结果,这样我就可以通过根据这个结果更改 UI 来适当地将结果传播回用户。

我对此很陌生,无法真正理解这些概念。如果有人可以解释并举例说明会有帮助。

在 Android 中有很多方法可以像您描述的那样进行 异步 工作。您可以使用 Service, a Loader, if you're using Retrofit library for network requests, than it has async requests built in, so follow the documentation。此外,还有 RxJava,但它的学习曲线非常陡峭。

我通过使用 HandlerThread 创建一个 Handler 来完成此操作,我将 Runnables 发布到该 Handler 以执行后台任务。
要执行该主线程任务(UI 任务),我正在使用 mainLooper 创建另一个 Handler,我向其发布 Runnables 以对视图进行操作。
代码的粗略表示:

mBackgroundHandler.post(new Runnable() {

    @Override
    public void run() {
        //Do background operation in synchronous manner as usual.

    mMainHandler.post(new Runnable() {
        @Override
        public void run() {
            //Remove loader, update UI
        }
    });
  }
});