Android连续调用网络操作?

时间:2015-05-10 08:27:01

标签: android multithreading wait

在我的Android应用程序中,我必须在每30秒后调用一次网络操作。

现在我从活动的onresume中调用以下代码。

new Thread(new Runnable() {
        public void run() {
            while(true){
                try {
                    HTTPConnection httpConnection = new HTTPConnection();
                    httpConnection.extendSession(userId);
                    wait(30000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();

但它会导致以下异常

java.lang.IllegalMonitorStateException: object not locked by thread before wait().

如何实现上述功能?

1 个答案:

答案 0 :(得分:3)

我会在你的情况下使用Timer / TimerTask。 Timer在不同的线程上运行,并将其安排在固定的时间间隔内。 E.g。

class MyTimerTask extends TimerTask {
  public void run() {
     HTTPConnection httpConnection = new HTTPConnection();
     httpConnection.extendSession(userId);
  }
}

和onCreate

Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), new Date(), 30000);

关于您的例外

wait()需要synchronized块和锁定对象。常见的用法是通过wait() / notify()对,并且由于它们通常在不同的步骤上调用,因此需要synchronized块来保证对锁本身的正确访问。

public static final Object mLock = new Object();

new Thread(new Runnable() {
        public void run() {
          synchronized(mLock) {
            while(true){
                try {
                    HTTPConnection httpConnection = new HTTPConnection();
                    httpConnection.extendSession(userId);
                    mLock.wait(30000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
          }
        }
    }).start();