我有一个具有一组操作的 android 服务:
我的服务.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
}
}
我正在调用来自客户端活动的方法,例如,MyClientActivity.java
驻留在同一进程中。
对于每个操作,服务调用一些逻辑并以同步方式等待结果。当服务正在执行所有这些逻辑时,我不希望用户执行任何其他操作而只显示加载屏幕。所以基本上,在我启动一个操作后,我想MyClientActivity
同步等待状态码。现在我知道我不能阻止 UI 线程来避免 ANR。
如何使此操作在单独的线程上执行,然后返回结果,以便我可以通过基于此结果更改 UI 将结果适当地传播回用户。
我对此很陌生,无法真正掌握这些概念。如果有人可以解释一个会有帮助的例子。