Search code examples
androidandroid-asynctasklocationlistener

create limited instances of AsyncTask


I am fetching user's location in a service, that implements LocationListener. And in OnlocationChanged() method, I am creating an instance of asynctask class that will upload the values to an online database. The problem is that, as soon as the OnlocationChanged() method is called by Listener, a new instance of asynctask is created and it slows down the device. I want a method/mechanism to limit the instances of asynctask to at most 5.


Solution

  • It's quite similar to Thread Pools in java (here).

    public class MaxAsyncHandler {
    
     private static MaxAsyncHandler instance = new MaxAsyncHandler();
     ArrayList<Data> list;
     int count;
     int MAX = 5;
    
    
     private MaxAsyncHandler() {
      this.count = 0;
      list = new ArrayList<Data>();
     }
    
     public int getCount() { return count; }
    
     public int incCount() { count++; }
    
     public static MaxAsyncHandler getInstance()
     {  
       return instance;
     }
    
     public void createTask(Data data) {
      if(count < MAX) 
         new AsyncTask(data); // 
      else
         list.add(data);
     }
    
     // Call this method when an AsyncTask finishes
     public void checkPool() {
      if(list.size() > 0)
        new AsyncTask(list.get(0)); //
     }
    }
    

    PS : I used a singleton pattern.