Android长轮询 - 超时执行服务

时间:2011-04-08 16:55:06

标签: android asynchronous comet long-integer polling

我正在尝试在Android应用程序中实现LongPolling。 Long Polling

如果LongPolling需要很长时间才能得到答案我的android服务崩溃了。

我尝试使用Threads和Async。一般来说,我尝试了很多员工,但我没有得到它。

public class PollingService extends Service {

String TAG = "AndroidPolling";
int CONNECTION_TIMEOUT = 900000;
int mHeartbeat = 10000;
int TIMEOUT_TOLERANCE = 5000;
String mPushURL = "http://192.168.0.115:8080/de.test.jersey.cti/rest/todos/";


@Override
public void onCreate() {
    super.onCreate();    
    Log.i( TAG, "RestService Service-Class created");  

}

   public void onStart(Intent intent, int startId) {
    Log.i(TAG, "onStart"); 

    new makepolling().doInBackground("http://192.168.0.115:8080/de.test.jersey.cti/rest/todos/");

}


@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}
}

class makepolling extends AsyncTask<String, String, String> {

String TAG = "AndroidPolling";
int CONNECTION_TIMEOUT = 900000;
int mHeartbeat = 10000;
int TIMEOUT_TOLERANCE = 5000;
String mPushURL = "http://192.168.0.115:8080/de.test.jersey.cti/rest/todos/";

@Override
protected String doInBackground(String... arg0) {
    String result = null;
    DefaultHttpClient def = new DefaultHttpClient();
    HttpParams httpParams = def.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);

    ConnManagerParams.setTimeout(httpParams, CONNECTION_TIMEOUT);
    HttpGet httpGet = new HttpGet(mPushURL);
    httpGet.addHeader("Accept", "application/json");

    try {
        Log.i(TAG, "Executing GET(PUSH) request " + httpGet.getRequestLine());

        HttpResponse httpResponse = def.execute(httpGet);
        Log.i(TAG, result);
        Log.i(TAG, String.valueOf(httpResponse.getProtocolVersion()));
        Log.i(TAG, String.valueOf(httpResponse.getEntity().getContent())); //For testing purposes


    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;

}

@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub

    super.onPostExecute(result);
}

}

1 个答案:

答案 0 :(得分:4)

您不应该显式调用doInBackground()。要启动AsyncTask,您必须创建它的实例并在其上调用execute()方法。 This文章很好地解释了AsyncTask。