Performing network operations is a time-consuming operation, even in a service where it is executed in a child thread
Here I use the Async-http-client framework to perform asynchronous request operations
Java Native timer and TimerTask class for timing
It would have been a separate operation.
But if you write the asynchronous operation into the TimerTask run method, it will go wrong.
E/androidruntime (5799): java.lang.IllegalArgumentException:Synchronous ResponseHandler used in asynchttpclient. You should create your response handler with a looper thread or use synchttpclient instead.
One solution is to replace asynchttpclient with Synchttpclient.
The following is the modified code:
Timing section:
Public voidCounttime () {timertask task=NewTimerTask () { Public voidrun () {cityweather (URL, key,Shenzhen); } }; Timer Timer=NewTimer (true);//true: Daemon threadTimer.schedule (Task, 1000, 10000);//delay 1000ms After execution, 10000ms execution once//Timer.cancel ();//Exit Timer}
Request Network section:
Public voidcityweather (String url,string key,string cityname) {string Httparg= "Cityname=" +CityName; String Httpurl= URL + "?" +Httparg; Synchttpclient Client=NewSynchttpclient ();//change it intosynchttpclientClient.addheader ("Apikey", key); Client.get (Httpurl,NewAsynchttpresponsehandler () {@Override Public voidOnsuccess (intStatusCode, header[] headers,byte[] responsebody) {String responsestring=NewString (responsebody); Try{jsonobject Jsonobject=NewJsonobject (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+ ", Temperature:" +temp+ "degrees \ r \ n" + "Maximum temperature:" +h_tmp+ "minimum Temperature:" +l_tmp+ "\ r \ n" + "Wind:" +wd+ ", Wind:" +WS); } Catch(jsonexception e) {E.printstacktrace (); }} @Override Public voidOnFailure (intStatusCode, header[] headers,byte[] responsebody, throwable error) {Toast.maketext (myservice). This, "+statuscode, 0); }}); }
(original) A few notes on how to perform network operations regularly in service