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                                                     

Wednesday 1 August 2012

Android sliding drawer example

Consider a case of complex UI where you do not have space on your android application screen but you have to show some extra data on same screen?
There are two way in such a condition --

1) Switching view using LayoutInflater or fragments - but its very costly if as it will need space from visible portion

2) Using menu and action bar - unfortunately we can only show button there to perform action.

Then what should we so ? android provide Sliding drawer for such a requirement. It does not take main screen space. and it open when ever a user want to open. Most importantly , you can show any complex user interface inside a sliding drawer.

Creating sliding drawer is simple. It just need two component--

  •  A button, will visible all the time to open and close sliding drawer. but we do not need to set listener for this.
  • And Layout that will show when you open sliding drawer. I have taken a ListView inside sliding drawer
Sliding Drawer Closed
                             


Sliding drawer
Sliding Drawer Opened

Sliding Drawer
Action On Sliding Drawer Element
                                               

Now you just need to download the sample application and start playing with it. 

Sliding Drawer Source Code


I have browse about sliding drawer and i found a very useful link to create sliding drawer from Left to right or Right to left See Going into depth of Custom Sliding drawer


Date Time Picker in android

We know how simple is to create Date Picker Dialog and  Time Picker Dialog ! but so what about a situation where we  need to pick Time and Date both at once with all attributes e.g AM_PM, second, minute, Hour, Month, Year etc. We got stuck  right?

I have search a lot about this on Google but i did not find efficient and easy solution. So decide to write about this important concept. While you are developing any android application then you just copy one class from my sample project. and your work has done.

There are two simple step to understand what's going on in my project

1) Create object of CustomDateTimePicker with two argument Your Current activity context and one Call back listener so that when you select time and date, it will return result

2) CustomDateTimePicker has number of method to fulfill your custom requirement like---


/**
* Pass Directly current time format it will return AM and PM if you set
* false
*/
custom.set24HourFormat(false);

                 /**
* Pass Directly current data and time to show when it pop up
*/
custom.setDate(Calendar.getInstance());

Custom is instance of my CustomDateTimePicker .Except this , CustomDateTimePicker  has number of method. 


                       The Output of my sample project will be like these screen shot.

Date time Picker
Date And Time Picker

Selected Value
          
                                                       

                                                              Download Source Code


Time Picker in android

In my previous post Date Picker in android, I discuss about how to create Date Picker now we will cover another important aspect Timepickerdialog in android. While developing android application we meet so many situation where we need to pick time. In time picker also, we have two important  steps to remember

1) Call back listener that will return Time in hour and minute 

2) And Time picker dialog object


Note - Always use overridden method onCreateDialog(int id) of activity to avoid window leak exception while changing orientation of activity

Date picker in android

In android application development, picker and dialog has an important place. Today i am going to discuss how to create a simple date picker dialog and time picker dialog. All though i know i am very late to write about this basic concept, but i realize that even-though a lots of matter and article available on this but they lack in term of explanation. So here i go with my attempt.

We need two things here

1) Dialog picker (either date or time) Object

2) And call back so that we can capture date or time when user set date


We will set current date or time when picker will open first time using calender object. Creating Datepickerdialog object inside overridden method of activity ,oncreatedialog() is best way. It will handle the orientation change effectively and you will avoid window leak exception quite easily

Android News and source code