如何使用Toast警告用户OkHttp请求返回200以外的其他内容?

Nap*_*ead 9 android okhttp android-toast

我正在使用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();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

这是崩溃:

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

Lei*_*Guo 16

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

像这样的代码适用于您:

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();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)