如何从相关线程外部取消改造调用?

How is it possible to cancel a retrofit call from outside the respected thread?

我正在创建这样一个改造的在线问题:

new Thread(new Runnable() {
                @Override
                public void run() {
                    mService.uploadFile(body)
                            .enqueue(new Callback<String>() {
                                @Override
                                public void onResponse(final Call<String> call, Response<String> response) {

                                    progressDialog.dismiss();
                                    Toast.makeText(MainActivity.this, "uploaded!", Toast.LENGTH_SHORT).show();

                                }

                                @Override
                                public void onFailure(Call<String> call, Throwable t) {
                                    Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                }
            }).start();

我需要通过 progressDialog.setButton()Thread 外部取消 onResponse 中的 call。这怎么可能?

感谢任何帮助!

您需要获取 mService.uploadFile(body) 的实例。这是 retrofit2.Call<T> 接口与 public 方法 cancel()

   ...{
    call = mService.uploadFile(body)
    call.enqueue(new Callback<String>() {
   ...

然后像这样使用它

  void cancel() {
        if (!call.isCanceled && call.isExecuted) call.cancel()
    }

还有方法enqueue(Callback<T> callback)

Asynchronously send the request and notify callback of its response or if an error occurred talking to the server, creating the request, or processing the response.

不需要用Thread()来处理