Saturday, November 14, 2015

Android Services

There are actually two ways to implement a service 
  1. When your class MyService extends from Service 
  2. When your class MyService extends from IntentService

Rule of thumb:

No matter which service you implement , lifecycle methods of the service will be called on main thread aka UI Thread and this is where i have seen too much of confusion where newbies tend to think that all the methods in the service are called on background thread .
Because of this you should not be calling any methods that would essentially be calling any methods which would block your UI thread in lifecycle methods of service 

Things are not that BAD as you think as you might start to wonder about whats the point then...
  • If you implement #1 you have to start a worker thread in onStartCommand()
    • Once started always run in the background
    • We have to manage the life of service ie call Stopself() once the job is done
  @Override  
   public int onStartCommand(Intent intent, int flags, int startId) {  
     Log.i(TAG, "Service onStartCommand " + startId);  
     final int currentId = startId;  
     Runnable r = new Runnable() {  
       public void run() {  
       }  
     };  
     Thread t = new Thread(r);  
     t.start();  
     return Service.START_STICKY;  
   }  

  • If you implement #2 then you are saved from this and the onHandleIntent() method will be actually called on the background thread and you can actually call long running background task on this thread
    • Once the onHandleIntent() is finished the service is automatically stopped
    • Requests are queued if multiple requests are sent at the same time
 
 @Override  
 protected void onHandleIntent(Intent intent) {  
   Log.d(TAG, "#### " + Thread.currentThread().getName());  
   if (intent != null) {  
     final String action = intent.getAction();  
     }  
  }  
 

No comments:

Post a Comment