2
我想在我的Android應用程序中實現LongPolling。 Long PollingAndroid長輪詢 - 超時執行服務
如果LongPolling需要很長時間才能得到答案,我的android服務崩潰。
我嘗試過使用線程和異步。一般來說,我嘗試了很多員工,但我沒有得到它。
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);
}
}
謝謝!這真的是一篇不錯的文章。 – DroidQuelle 2011-04-11 14:32:46