I try using TimerTask to download data from the server api, the task loops in background app.
I have a service class:
public class RequestNewInvoice extends Service {
private Timer timer;
private CheckTask checkTask;
private Handler handler;
private JSONParser jsonParser;
private JSONObject jsonObject;
private boolean startService = true;
private void init(){
this.handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Log.e("Message: ",msg.obj+"");
return false;
}
});
this.timer = new Timer();
this.checkTask = new CheckTask();
this.startService = true;
timer.scheduleAtFixedRate(checkTask, 5000, 20 * 1000);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(final Intent intent, int flags, final int startId) {
init();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("SERVICE STOP", "true");
startService = false;
checkTask.cancel();
timer.cancel();
timer.purge();
}
private class CheckTask extends TimerTask{
@Override
public void run() {
funcCheckInvoice();
}
}
public void funcCheckInvoice(){
try{
if(startService){
Log.e("SERVICE START", "true");
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, SuperVAR.GET_CURRENT_SHIPMENT_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, SuperVAR.GET_CURRENT_SHIPMENT_TIMEOUT);
httpClient = new DefaultHttpClient(httpParameters);
HttpGet httpGet = new HttpGet(SuperVAR.URL_GET_LIST_INVOICE_IN_CURRENT_SHIPMENT+"?"+ URLEncodedUtils.format(_REQUEST, "utf-8")+"unused="+System.currentTimeMillis()/1000);
httpGet.setHeader("token",token);
httpGet.setHeader("Cache-Control","no-cache");
httpGet.setHeader("Cache-Control","no-store");
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
jsonObject = jsonParser.getJSONFromRESPONSE(httpEntity);
if(jsonObject == null){
Message message = Message.obtain();
message.obj = "get null.... internet like shit T_T";
handler.sendMessage(message);
}else {
Message message = Message.obtain();
message.obj = "download ok";
handler.sendMessage(message);
}
}else {
Log.e("SERVICE START", "false");
return;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
When I run stopService in Activity Class, service calls the onDestroy function, but Timer still lives on.
How can I destroy the timer task?