服务器发送事件-如何在Android中处理

时间:2019-06-27 14:54:10

标签: java android server-sent-events

我已经创建了一个应用程序(遵循当前使用LiveData和Retrofit的Android MVVM体系结构)。该应用程序可作为照明和进入系统的遥控器。

我已经构造了一个Repository类,该类使用Retrofit实现网络后端,Retrofit调用了我的REST API。当我手动请求(使用GET)状态更新时,我可以获取IO的状态。但是,我需要使用服务器发送的事件来获取另一个URI上相同数据的IO状态更新。

似乎Retrofit不支持此功能。我发现了其他似乎可以处理SSE的API,例如EventSource,EventSource-Android,OkHttp-EventSource和Oksse。所有这些都是EventSource的不同实现吗?它们在功能上有何不同?

我从阅读别人写的代码中学到东西;在哪里可以找到如何实现这些功能的示例?我的搜索结果没有提供任何有用的示例。是否有建议的最佳做法来处理服务器发送的事件?

我真的不想轮询我的服务器以获取更新,并且我感到困惑,为什么Android上几乎不支持SSE。

作为参考,以下是我到目前为止实现的一些类。

数据模型:

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name = "onboardGpio", strict = false)
public class OnboardGPIO
{
    @Element(name = "garageDoorFeedbackState")
    private String garageDoorState;

    @Element(name = "zoneOneState")
    private String zoneOneState;

    @Element(name = "zoneTwoState")
    private String zoneTwoState;

    @Element(name = "zoneThreeState")
    private String zoneThreeState;

    @Element(name = "systemArmedState")
    private String systemArmed;

    @Element(name = "panelTemperature")
    private String panelTemperature;

    @Element(name = "garageDoorRelayState")
    private String garageDoorRelayState;

    @Element(name = "zoneOneRelayState")
    private String zoneOneRelayState;

    @Element(name = "zoneTwoRelayState")
    private String zoneTwoRelayState;

    @Element(name = "zoneThreeRelayState")
    private String zoneThreeRelayState;

    ...getters & setters...
}

存储库类

import androidx.lifecycle.MutableLiveData;
import ca.thirdgear.homeautomation.http.HomeAutomationAPI;
import ca.thirdgear.homeautomation.http.HomeAutomationController;
import ca.thirdgear.homeautomation.model.OnboardGPIO;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DataRepository
{
    private static DataRepository dataRepository;
    private HomeAutomationController homeAutomationController;
    private HomeAutomationAPI homeAutomationAPIService;
    private MutableLiveData<String> zoneOneState;
    private MutableLiveData<String> zoneTwoState;
    private MutableLiveData<String> garageDoorState;

    public static DataRepository getInstance()
    {
        if(dataRepository == null)
        {
            dataRepository = new DataRepository();
        }
        return dataRepository;
    }

    private DataRepository()
    {
        homeAutomationController = HomeAutomationController.getInstance();
        homeAutomationAPIService = homeAutomationController.createService(HomeAutomationAPI.class);
        zoneOneState = new MutableLiveData<>();
        zoneTwoState = new MutableLiveData<>();
        garageDoorState = new MutableLiveData<>();
    }

    //get status of remote API I/O
    public void getIoStatus()
    {
        Call<OnboardGPIO> call = homeAutomationAPIService.getIoStatus();
        call.enqueue(new Callback<OnboardGPIO>() {
            @Override
            public void onResponse(Call<OnboardGPIO> call, Response<OnboardGPIO> response)
            {
                if(response.isSuccessful())
                {
                    zoneOneState.setValue(response.body().getZoneOneState());
                    zoneTwoState.setValue(response.body().getZoneTwoState());
              garageDoorState.setValue(response.body().getGarageDoorState());
                }
            }

            @Override
            public void onFailure(Call<OnboardGPIO> call, Throwable t)
            {
                //TODO
            }
        });

        ... other network calls ...
}

网络课程

import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("deprecation")
public class HomeAutomationController
{
    private static final String BASE_URL = "https://MY_URL/";
    private static HomeAutomationController homeAutomationController;
    private OkHttpClient okHttpClient;
    private Retrofit retrofit;

    public static HomeAutomationController getInstance()
    {
        if(homeAutomationController == null)
        {
            homeAutomationController = new HomeAutomationController();
        }
        return homeAutomationController;
    }

    private HomeAutomationController()
    {
        //create OkHttpClient
        okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();

            Request.Builder builder = originalRequest.newBuilder().header("Authorization",
                    Credentials.basic("USERNAME", "PASSWORD"));

            Request newRequest = builder.build();
            return chain.proceed(newRequest);
            }
        })
            .readTimeout(0, TimeUnit.SECONDS)
            .build();

        //create retrofit object
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .client(okHttpClient)
                .build();
    }

    //create and return http service
    public <S> S createService(Class <S> serviceClass)
    {
        return retrofit.create(serviceClass);
    }

}

0 个答案:

没有答案