(原创)在service中定时执行网络操作的几点说明

时间:2022-02-02 06:49:00

执行网络操作是耗时操作,即便是在service中也要放到子线程中执行

这里我用到了async-http-client框架来执行异步请求操作

计时用的java原生Timer和TimerTask类

本来这两者分开操作各没有问题

但是如果把异步操作写到TimerTask的run方法里就会出错

E/AndroidRuntime(5799): java.lang.IllegalArgumentException: Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead.

解决办法之一就是把AsyncHttpClient换成SyncHttpClient.

下面是修改过的代码:

计时部分:

public void countTime(){

        TimerTask task = new TimerTask() {
public void run() {
cityWeather(url, key, "深圳");
}
};
Timer timer = new Timer(true);//true:守护线程
timer.schedule(task, 1000, 10000); // 延时1000ms后执行,10000ms执行一次
// timer.cancel(); //退出计时器
}

请求网络部分:

public void cityWeather(String url,String key,String cityName){
String httpArg = "cityname="+cityName;
String httpUrl = url + "?" + httpArg;
SyncHttpClient client = new SyncHttpClient();//这里改成Synchttpclient
client.addHeader("apikey", key);
client.get(httpUrl, new AsyncHttpResponseHandler(){ @Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
String responseString = new String (responseBody);
try {
JSONObject jsonObject = new JSONObject(responseString);
JSONObject retData = jsonObject.getJSONObject("retData"); String city = retData.getString("city");
String weather = retData.getString("weather");
String temp = retData.getString("temp");
String l_tmp = retData.getString("l_tmp");
String h_tmp = retData.getString("h_tmp");
String WD = retData.getString("WD");
String WS = retData.getString("WS");
resultString = (city+","+weather+" ,气温:"+temp+"度\r\n"+
"最高温度:"+h_tmp+" 最低温度:"+l_tmp+"\r\n"+"风向:"+WD+" , 风力:"+WS);
} catch (JSONException e) {
e.printStackTrace();
}
} @Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MyService.this, ""+statusCode, 0);
}});
}