我嘗試使用TimerTask從服務器api下載數據,任務在後臺應用程序中循環。StopService onDestroy被調用,但服務沒有結束
我有一個服務類:
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();
}
}
}
當我在活動課運行stopService,服務調用的onDestroy功能,但仍定時器生活在。
如何銷燬計時器任務?
在無效運行任務Runnable中,我使用httpclient.excute ..和我得到錯誤.. :(,,謝謝你的幫助 – HoangQBH
什麼是錯誤詳細信息? –
我得到'android.os.NetworkOnMainThreadException' – HoangQBH