android(java)控制http连接超时的问题

"声明一个boolean公共变量,表明当前httpconnection是否得到服务器回应。

你的连接线程中在连接之前置这个变量为false;

另起一个监视线程,拿到那个HttpConnection的连接对象,并循环监视这个boolean公共变量。如果指定时间内(20秒后)你的boolean公共变量还是false,那么就主动置httpconnection=null。这样,那边连接线程就会抛出异常退出来。"  -----zhengyun

写了Timer类来实现.(学习国外一个网站上的写法)

class Timer extends Thread {
  
  protected int m_rate 100;

  
  private int m_length;

  
  private int m_elapsed;

  
  public Timer(int length) {
   // Assign to member variable
   m_length length;

   // Set time elapsed
   m_elapsed 0;
  }
  

  public synchronized void reset() {
   m_elapsed 0;
   System.out.println("reset timer");
  }
  
  public synchronized void setTimeOut()
  {
   m_elapsed m_length+1;
  }

  
  public void run() {
   // 循环

   System.out.println("timer running");
   for (;;) {
    // Put the timer to sleep
    try {
     Thread.sleep(m_rate);
    catch (InterruptedException ioe) {
     continue;
    }

    synchronized (this) {
     // Increment time remaining

  m_elapsed += m_rate;

     // Check to see if the time has been exceeded
     if (m_elapsed > m_length && !isConnActive) { //isConnActive 为全局变量
      // Trigger a timeout
      timeout();
      break;
     }
    }

   }
  }

  
  public void timeout() {
      httpConnection = null;
      System.out.println("conn time > " + TIME_OUT + " ms");
    }
 }


 

在http连接线程调用的同是调用 new Timer(20*1000).start();

需要重新计时时候调用timer.reset();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值