---
title: "android(java)控制http连接超时的问题"
author: "l62s"
date: "2012-09-10T15:39:09Z"
tags: []
categories: ["移动开发"]
slug: "android-java-http"
draft: false
lastmod: "2012-09-07T16:07:14Z"
id: 1673640
url: "https://l62s.iteye.com/blog/1673640"
---

"声明一个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 &gt; m\_length && !isConnActive) { //isConnActive 为全局变量  
      // Trigger a timeout  
      timeout();  
      break;  
     }  
    }

   }  
  }

    
  public void timeout() {  
      httpConnection = null;  
      System.out.println("conn time &gt; " + TIME\_OUT + " ms");  
    }  
 }

 

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

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