【问题标题】:How to alert the user using Toast that the OkHttp request returned something other than 200?如何使用 Toast 提醒用户 OkHttp 请求返回的不是 200?
【发布时间】:2015-04-28 12:01:36
【问题描述】:

我正在使用 OkHttp 并且一切正常,但是,我想考虑以下情况:DNS 解析关闭、服务器关闭、速度缓慢或仅返回 HTTP 状态代码 200 以外的内容。 我试过使用 Toast,但我不能,因为这是在另一个线程上完成的(?)。 如何克服这个障碍,给用户更好的体验? 这是我的代码:

private void getBinary(String text) throws Exception {
    OkHttpClient client = new OkHttpClient();

    String body = URLEncoder.encode(text, "utf-8");
    // Encrypt
    MCrypt mcrypt = new MCrypt();
    String encrypted = MCrypt.bytesToHex(mcrypt.encrypt(body));
    Request request = new Request.Builder()
        .url("http://mysite/my_api.php")
        .post(RequestBody.create(MediaType.parse("text/plain"), encrypted))
        .addHeader("User-Agent", System.getProperty("http.agent"))
        .build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(Response response) throws IOException, RuntimeException {
            if (response.code() != 200){
                Toast.makeText(getSherlockActivity(), "Fail", Toast.LENGTH_LONG).show();
                return;
            }
            saveResponseToFile(response);
        }

        @Override
        public void onFailure(Request arg0, IOException arg1) {
            Toast.makeText(getSherlockActivity(), "Bigger fail", Toast.LENGTH_LONG).show();
        }
    });
}

这是崩溃:

FATAL EXCEPTION: OkHttp Dispatcher
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

【问题讨论】:

  • 确保不从主 Ui 线程调用 getBinary 方法?

标签: android okhttp android-toast


【解决方案1】:

Toast 必须显示在主线程上。您可以使用new Handler(Looper.getMainLooper()) 从任何后台线程生成主线程处理程序,然后使用它将 toast 工作发布到主线程。

这样的代码将适用于您:

public static void backgroundThreadShortToast(final Context context,
        final String msg) {
    if (context != null && msg != null) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

【讨论】:

    猜你喜欢
    • 2020-07-30
    • 2019-06-25
    • 1970-01-01
    • 2019-08-03
    • 2016-08-08
    • 2018-12-26
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多