Search This Blog

Saturday 4 August 2012

Updating UI from background service in android

Its recommended that always perform long task using background Thread or Service. If you have not idea how to create basic service and Thread then please read these

Now back to some current one, we can perform any long task in background using service. Let you are downloading movies in your application and we run one service to start download. But if we did not notify about this to user then end user will think that application is not responsive. We can not  update User interface from service directly to show progress in android.

so if you are using service in your android application , two step will make sure update of user interface when ever new data loaded inside service

  •  Create one service from activity 
  • Then bind this service to activity using service connection 
Remember These some points about service 
  1. Service will not create new instance if it is already running
  2. When you bind service it will call onserviceConnected() method
  3. You can not unbind or bind service if it is already stopped (either explicitly or implicitly)
Service connection will be perform using Binder. Whenever you will bind service it will call connected method of service connection. in this method we will get Service class object, and our work done. Using object of service we can use any updated value from service class

   LocalService localservice
;
  
ServiceConnection serviceConnection = new ServiceConnection() {

      
@Override
      
PUBLIC void onServiceDisconnected(ComponentName name) {
           txt_view.setText
("DisConnected !!!!! bind it for updating UI...";
      
}

      
@Override
      
PUBLIC void onServiceConnected(ComponentName name, IBinder SERVICE) {
           localservice
= ((LocalService.LocalBinder) SERVICE).getBinder();
          
try {
               txt_view.setText
(String.valueOf(localservice.STR));
              
localservice.STR = "String changes from Activit"
           } catch
(Exception e) {
           }
       }
   }
;}


In service class we will create a Binder to return the object of current service.

   @Override
  
PUBLIC IBinder onBind(Intent intent) {
      
RETURN iBinder;
  
}

   private IBinder iBinder
= new LocalBinder();

  
PUBLIC class LocalBinder extends Binder {
       LocalService getBinder
() {
          
RETURN LocalService.this;
      
}
   }


Here onBind() will return service class object when service will connected . I have taken a string inside the service and set to TextView's background .

on calling bindservice() onserviceConnected() will call. But it onServiceDisconnected() will never call either you call unbind service or stop service. It will only call when service will stop stopped in memory low situation or by OS. once service disconnected, you will not get receive result any more

     
Service Main Screen
  This screen have only simple UI for starting , binding, unbinding and stopping service. I started the service     

   private Intent intent = NULL;
  
private OnClickListener startService = new OnClickListener() {

      
@Override
      
PUBLIC void onClick(VIEW v) {
           intent
= new Intent(MainActivity.this,      

                LocalService.class);
           startService(intent);
      
}
     }
;


It start the service. Now we will bind study how bind and unbind service

Binding Sevice....while binding service we will user ServiceConnection class object

   private OnClickListener boundService = new OnClickListener() {

      
@Override
      
PUBLIC void onClick(VIEW v) {
          
IF (intent != NULL) {
               bindService
(intent, serviceConnection, BIND_AUTO_CREATE);
          
} ELSE {
               Toast.makeText
(MainActivity.this,
                      
"First Satrt service to bind." Toast.LENGTH_LONG)
                      
.show();
          
}
       }
   }
;
  
private OnClickListener unboundService = new OnClickListener() {

      
@Override
      
PUBLIC void onClick(VIEW v) {
          
IF (intent != NULL) {
               unbindService
(serviceConnection);
              
txt_view.setText("DisConnected !!!!! bind it for updating UI...";
          
} ELSE {
               Toast.makeText
(MainActivity.this,
                      
"First Satrt bind to UnBind." Toast.LENGTH_LONG)
                      
.show();
          
}
       }
   }
;
  
private OnClickListener stopService = new OnClickListener() {

      
@Override
      
PUBLIC void onClick(VIEW v) {
          
IF (intent != NULL) {
               stopService
(intent);
          
} ELSE {
               Toast.makeText
(MainActivity.this, "First Satrt to stop it."
                       Toast.LENGTH_LONG
).show();
          
}
       }
   }
;


Now see some screen shot to get idea how this will work..

        Android trainner
        Service Disconnected After Unbind
                                     
                    Activity Showed value from Service   


Now i think you got some idea how we can update UI from background service
Download source cod to read complete piece of code

 Download All Service Binding Example                                                     

2 comments:

  1. Your blog makes some good points, thank you. However, it is not correct that a service must be stated via startService() before one can bind to it.

    Reviewing the android reference on services (http://developer.android.com/reference/android/app/Service.html#ServiceLifecycle) it states that a bind service "likewise creates the service if it is not already running".

    ReplyDelete
    Replies
    1. Thanx for make me correct. You are right bindservice will start service automatically

      Delete

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code