如何将Exception消息传播到Activity?

时间:2018-02-11 18:11:36

标签: java android exception-handling

我正在使用多层课程从互联网上获取数据并在Android应用中显示。

活动 - ViewModel - 存储库 - NetworkDataSource ---- // Internet

我在NetworkDataSource中处理HTTP错误消息,我在其中尝试/ catch块。但是,我想将此错误消息传播到Activity,我将在其中显示Toast。

如何从NetworkDataSource类中激活Activity中的事件?

static String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    String response = "";
    try {
        urlConnection.setConnectTimeout(5000);
        int responseCode = urlConnection.getResponseCode();

        switch (responseCode) {
            case HttpURLConnection.HTTP_OK:
                response = getPayload(urlConnection);
                break;
            case HttpURLConnection.HTTP_UNAVAILABLE:
                throw new IOException("HTTP_UNAVAILABLE");
            case HttpURLConnection.HTTP_NOT_FOUND:
                throw new IOException("HTTP_NOT_FOUND");
            case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
                throw new IOException("HTTP_GATEWAY_TIMEOUT");
        }

    } catch (IOException e) {
        Log.v(TAG, e.getMessage());
        throw new IOException(e.getMessage());
    } finally {
        urlConnection.disconnect();
    }
    return response;
}

2 个答案:

答案 0 :(得分:0)

您可以使用eventbus。通过eventbus,您可以发送事件,并且可以在应用程序中的任何位置接收任何您想要的任何位置。

https://github.com/greenrobot/EventBus

答案 1 :(得分:0)

如Kirtan所指出,除了EventBus之外,你还可以使用Interface callbacks / RxJava。