gpt4 book ai didi

android - loopj RequestHandle 在取消时崩溃

转载 作者:行者123 更新时间:2023-11-29 21:02:21 25 4
gpt4 key购买 nike

我的 android 应用程序中有一个 loopj 异步请求。

代码如下:

private RequestHandle requestFetchAds;
requestFetchAds = HJRestClient.post(getActivity(), encodedURL, params, new JsonHttpResponseHandler() {...});

请求执行得很好,在某些情况下我需要取消请求。这是取消代码:

if (requestFetchAds != null && !requestFetchAds.isFinished() && !requestFetchAds.isCancelled()) {
Log.d(LOG_TAG, String.format("Cancelling request fetch ads"));
Log.d(LOG_TAG, String.format("Cancelling request: ") + (requestFetchAds.cancel(true) ? " succeeded" : " failed"));
}

但是它在 requestFetchAds.cancel(true) 方法上崩溃了,我不知道为什么。

这是日志:

09-04 16:14:42.530    3999-3999/com.haraj.haraj E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1144)
at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.close(OpenSSLSocketImpl.java:996)
at org.apache.http.impl.SocketHttpClientConnection.shutdown(SocketHttpClientConnection.java:183)
at org.apache.http.impl.conn.DefaultClientConnection.shutdown(DefaultClientConnection.java:150)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.shutdown(AbstractPooledConnAdapter.java:169)
at org.apache.http.impl.conn.AbstractClientConnAdapter.abortConnection(AbstractClientConnAdapter.java:378)
at org.apache.http.client.methods.HttpRequestBase.abort(HttpRequestBase.java:159)
at com.loopj.android.http.AsyncHttpRequest.cancel(AsyncHttpRequest.java:169)
at com.loopj.android.http.RequestHandle.cancel(RequestHandle.java:50)
at com.haraj.haraj.HJAdsListFragment.reloadAds(HJAdsListFragment.java:699)
at com.haraj.haraj.HJAdsListFragment$2.onClick(HJAdsListFragment.java:328)
at android.view.View.performClick(View.java:4475)
at android.view.View$PerformClick.run(View.java:18786)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5493)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
at dalvik.system.NativeStart.main(Native Method)

我也曾尝试使用如下上下文取消请求:

HJRestClient.getHTTPClient().cancelRequests(getActivity(), true);

但这也没有帮助。

如有任何帮助,我们将不胜感激。

最佳答案

我能够通过将取消请求包装在 AsyncTask 中来修复崩溃,如下所示。

    AsyncTask.execute(new Runnable() {
@Override
public void run() {
Log.d(LOG_TAG, String.format("Cancelling request: ") + (requestFetchAds.cancel(false) ? " succeeded" : " failed"));

}
});

感谢塞尔文。

关于android - loopj RequestHandle 在取消时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25666596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com