使用服务/道层模式的 Android 项目"back-end"的最佳架构



我试图使用Spring Boot(REST(作为后端和Android作为前端启动一个项目。问题出在 android 项目中,因为我想使用服务 - 控制器模式。

当我将用于管理http请求/响应的代码放在其他类中时,例如UserService,位于主线程之外,这无法操作UI。

我正在阅读有关"runonuithread"的信息,但 UI 的元素不在服务类中......在这种情况下我该怎么办?将元素添加到类中还是管理用户服务中的上下文?

这适用于异步呼叫。.但是当我不想进行同步调用时,这是必要的吗?

这是使用 EventBus 的最佳方案。

在活动中,您可以订阅事件,并从服务中发布事件。

活动/片段.java

// ======= EventBus Subscribers =======
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void onEvent(ActionEvent event)
{
    // Maniupulate the UI directly
    titleTextView.setText(event.getTitle());
    messageTextView.setText(event.getMessage());
}

动作事件.class

// A Simple Class with the required properties
public class ActionEvent{
    private final String   title;
    private final String   message;
    public ActionEvent(String title, String message) {
        this.title = title;
        this.message = message;
    }
    ...
    // Getters and any other required stuff 
    ...
}

服务.java

// Appropriately compose and Post the event
ActionEvent event = new ActionEvent("Some Title", "Some Message");
EventBus.getDefault().post(event);