0
private void save_logs_to_server(Double lat, Double lon) {
        String vehicle_no = getSharedData("vehicle_no");
        if(timer()-my_timer>update_interval){
            DownloadWebPageTask task = new DownloadWebPageTask();
            task.execute(new String[] { server+"/save_logs.php?vehicleno="+vehicle_no+"&lat="+lat+"&lon="+lon+"&speed="+speed});
        my_timer=timer();
        }
        else if(timer()-my_timer<0){
        my_timer=0; 
        }

    }

This is the piece of code that im using to repeatedly execute asynctask after according to the value of the variable update_interval

The timer () method i had written returns the clock in seconds

My doubt is : Do I need to use Timer class for the above purpose? Which one has less CPU overhead; the Timer or above strategy?

Any suggestions will be appreciated

Shan
  • 1,081
  • 1
  • 12
  • 35
  • my comment here about another aspect you create each time an object of asyncTask and use it , try to make some singleton pattern or using Handler that post delay with your timer mins – mohammed momn Jan 18 '14 at 03:07
  • Can you please elaborate. ..yes im calling this save_logs_to_server () method on each location change instances.which will create new asynctask obj each time!! Oh thats a big flaw!! – Shan Jan 18 '14 at 03:23
  • yeah you get my idea , i add answer for you with two way of implementation the two approach , will help your code performance – mohammed momn Jan 18 '14 at 04:09
  • So .... I should change my strategy for repeating this task – Shan Jan 18 '14 at 04:36
  • yeah , try to using the handler and message class as mention in source code of it support the singleton so will save your code from memory problem – mohammed momn Jan 18 '14 at 04:48

2 Answers2

1

if you repeatedly execute background tasks the best performance instead of using AsncTask class using handler because you will create each repeat new object of asyncTask class and execute doInBackground method and it will be very memory cost and in handler you create one Object and post message from it each repeat process , or in some cases you try to implements singleton design pattern on Asynctask
so you can create one object using it in your repeats also , asynctask will be very useful in one process not repeated process

here example on how to scheduled periodic tasks in best way hope it help you

http://binarybuffer.com/2012/07/executing-scheduled-periodic-tasks-in-android

and here example on singleton asynctasl

Is AsyncTask really conceptually flawed or am I just missing something?

Community
  • 1
  • 1
mohammed momn
  • 3,230
  • 1
  • 20
  • 16
-1

Your method is fine, except if you are calling it in a loop you need some idle time, like Thread.sleep(1000) otherwise you are going to take 100% of CPU.

serge
  • 1,590
  • 2
  • 26
  • 49