0

我正在 TimerTask 中使用 kSoap 进行 http 调用,因此我可以每五分钟更新一次数据。从 Web 服务获取数据后,我通过函数 procecssData() 将它们提供给接口。这是第一次完美地工作,但是尽管每次数据保持不变时都会触发计时器。所以事实上,我的 UI 每五分钟绘制一次,但它总是使用来自第一个 http 调用的数据。有人知道为什么会发生这种情况吗?在我看来,httpCall() 函数中的变量没有被更新。

public class ConnectionThread extends Thread {

SoapObject request;
SoapObject result;
SoapSerializationEnvelope envelope;

String[][] resultArray;
int resultLength;

public ConnectionThread(ConnectionCallback conCallback) {

    callbackObj = conCallback;

    refreshTask = new TimerTask() {
        public void run() {
            httpCall();
        }
    };

    new Timer().schedule(refreshTask, 0, 50000);
}

public void httpCall() {

    request = new SoapObject(serviceNamespace, methodName);
    result = null;

    envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);

    http = new HttpTransport(serviceUrl);

    try {
        http.call(soapAction, envelope);
        result = (SoapObject) envelope.getResponse();
        resultLength = result.getPropertyCount();
    } catch (final InterruptedIOException ex) {
        Dialog.alert("No Internet Connection!");
        _isConnected = false;
    }
    // some other catch blocks
    finally {
        http.reset();
    }

    resultArray = new String[resultLength][resultLength * 8];
    // put result into own Stringarray

    if (_isConnected) {
        callbackObj.processData(resultArray, resultLength);
    }
}
}

任何帮助将不胜感激!:) 干杯,Musipoo

4

1 回答 1

1

In the first place I'd advise you not to extend Thread unless you need to override custom threading behavior (that is often not the case and it would be too scary a thing to do). Instead, the recommended approach is to implement a Runnable and pass it to the Thread constructor. In JavaSE they have introduced a new Executors framework that gets rid of instantiating threads the old way. With timers it's similar but here you implement a TimerTask which is pretty much a Runnable (inherits from it), and then you schedule it.

Another issue with your code is that it starts a thread from within a the constructor, which is a dangerous thing to do, because every new instance created will spawn a new thread (the one asociated with the Timer). This is considered an antipattern. Never do this, and if you do, please document it and make sure everyone using this class will know about it. (More info here). Also it is confusing that a class extending Thread launches a Timer in its constructor, and it doesn't even override run (what is the inheritance for?).

These are just tips to make your code clearer and a bit safer, but that won't fix your problem. I think the problem might be in that you are updating the result variable but you are not putting it into resultArray (or maybe you ommited that code?).

于 2013-08-30T08:33:17.353 回答