1

我正在创建一个 J2ME 应用程序,它使用 j2me(HttpConnection) 连接/访问远程服务器中的一些 php 文件。由于某些网络问题有时会长时间阻塞连接。给定超时 10 秒,我将如何创建一个线程来尝试连接。如果连接在 10 秒内没有响应,则线程再等待 5 秒并重试。在警告用户没有可用的网络连接之前,最大重试次数应为 3。

4

1 回答 1

0

您可以以任何一种方式使用 TimerTask 类,检查 10 秒的超时间隔,如下所示,

// First do your HttpConnection and open your URL
HttpConnection httpConnection = (HttpConnection) Connector.open(URL);

responseCode = httpConnection.getResponseCode(); // responseCode is class variable

// Now create a timertask that invokes after 10 seconds,
Timer timer = new Timer(); 

timer.schedule ( new TimeoutTask(), 10 * 1000 ); 

...
private class TimeOutTask extends TimerTask
{
    public void run()
    {
      // check reponseCode's value here, if it is not 200 then there is problem in network connection.
    }
}
于 2012-10-17T15:04:09.593 回答