AsyncTask.doInBackground方法在2.3上无法调用,而在4.0及以上版本可以正常工作。

4

我有这个AsyncTask:

public static void login(final String email, final String password,
            final String token, final SocketHandler handler) {
        execute(new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(final Void... params) {
                Log.d("ACEPTAR", "DOINBACKGROUND");
                String url = handler.servidor.getUrl();
                url += "/login-usuario";
                String str;
                try {
                    str = postResponseFromServer(url, "mail", email, "pass",
                            password, "tipo", "1", "token", token);
                    Log.d("ACEPTAR", str);
                    final CustomJSONObject object = new CustomJSONObject(str);
                    final CustomJSONObject object2 = new CustomJSONObject();
                    object2.put("datos", object);
                    final CustomJSONArray array = new CustomJSONArray();
                    array.put(object2);
                    handler.on("resultado-login", array);
                } catch (final Exception ex) {
                    ex.printStackTrace();
                    handler.on("error-login", new CustomJSONArray());
                }
                return null;
            }
        });
    }

    @SuppressLint("InlinedApi")
    private static void execute(final AsyncTask<Void, Void, Void> task) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
        } else {
            task.execute();
        }
    }

我尝试在3G网络下进行操作,一直都能正常工作。然后我连接到Wi-Fi上。AsyncTask在4.0以上的版本中被调用,但在2.3.7以下的版本中没有被调用。

我是否漏掉了什么东西?


从您发布的代码来看,调用doInBackground()方法并不依赖于您是否连接到WiFi或移动数据。您可能需要澄清您的问题。 - Gil Vegliach
我知道,这就是让我发疯的原因。 - Charlie-Blake
是否总是可以重现的?我的意思是,每次通过WiFi尝试都失败了吗?您是否尝试过在其他应用程序中使用WiFi,例如网络浏览器?您是否尝试过在多个设备上进行测试,以查看它是否在所有设备上都会发生这种情况? - nKn
1
@NKN 我理解你的意思,但我认为你没有注意到santirivera92的代码和文章本质上是不同的:santiriviera92有一个等效于只调用execute()的实现。而文章有一个总是并行运行任务的实现。编写一个总是串行执行的实现需要使用您自定义的执行器(SERIAL_EXECUTOR在Gingerbread和Honeycomb之间不存在)。 - Gil Vegliach
请查看此报告的问题:https://code.google.com/p/android/issues/detail?id=68013 - dharmendra
显示剩余5条评论
1个回答

0
尝试创建一个单独的线程,在那里做你的事情,使用Activity.runInUiThread()发布你的结果。看看是否存在问题。如果没有问题,那么可能是由于某些AsyncTask的bug。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接