Thursday, May 24, 2012

Parcelable over AIDL


Steps to Implement the Parcelable over AIDL: Here I am giving some steps to implement the Parcelable.

Step1 : Create a different  .aidl file that will be used for define the Student class (Parcelable class).
(Student.aidl)
           package com.aidl; 
           parcelable Student;

we write this because aidl can detect Student class.

Step 2: Define the class as Parcelable by Implement the Parcelable.
(Student.java)

package com.aidl;
import android.os.Parcel;
import android.os.Parcelable;
public class Student implements Parcelable {
                public String name;
                public String father_name;
                public Student(Parcel source)
                {
                                name = source.readString();
                                father_name = source.readString();
                }
                public Student()
                {}
                public void setName(String name)
                {
                                this.name = name;
                }
                public void setFatherName(String father_name)
                {
                                this.father_name = father_name;
                }
                @Override
                public int describeContents() {
                                // TODO Auto-generated method stub
                                return 0;
                }
                @Override
                public void writeToParcel(Parcel dest, int flags) {
                                // TODO Auto-generated method stub
                                dest.writeString(name);
                                dest.writeString(father_name);
                               
                }
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
                                @Override
                                public Student createFromParcel(Parcel source) {
                                                // TODO Auto-generated method stub
                                                return new Student(source);
                                }
                                @Override
                                public Student[] newArray(int size) {
                                                // TODO Auto-generated method stub
                                                return new Student[size];
                                }
                };
               
}

Explanation:
Yellow Color code : Parcelable interface has two abstract methods that we need to implement in class Student
  1.   describeContent()  : It is used for provide additional hint , on how the Parcelable will be received.
  2.  writeToParcel(Parcel dest, int flag) : This is the main method where we add data member to parcel using writeInt(), writeStirng () etc methods.
 "Green color code":  In any class which is implementing Parcelable have to provide CREATOR field. The type of CREATOR must be Parcelable.Creator<T>. Here in place of T we write the name of our class eg. Student. CREATOR is used during UnMarshalling of the object.

It has two methods –
1-      T createFromParcel(Parcel parcel) :This method is called when UnMarshalling happen during receiving the data. Keep care that  we receive the data member in same sequence as we write in writeToPacel(). Here we create a  constructor in which we demarshalling the data.
2-      NewArray(int size) : Here we just create an array of given size and return.
               
 For set the data in class I write setter methods setName() and setFatherName(). Its optional.

(Folder Structure)

Note : Better to keep this Student.java and Student.aidl in same package. And both should be copied in service side as well as client side.

Step 3: In the IRemoteInterface.aidl we change the argument type of methods

Student getName();
            void setName(in Student st);

When we are passing any User defined object in AIDL then we need to specify in/out with argument
        in – when the object is an IN Parameter
        out – when the object is an OUT Parameter
Change should be in both side client as well as service.

Step 4: client side, we create the T (Student) type object , set  the name and father name. And send using setName(Student ) method.

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
                  // TODO Auto-generated method stub
      Log.i("RemoteClient","In onServicen binded...");
      try {
            serviceInterface = IRemoteInterface.Stub.asInterface(service);
            Student st1 = new Student();
            st1.setName("Rahul");
            st1.setFatherName("Nand Kishor Kushwaha");
            serviceInterface.setName(st1);
      Log.i("RemoteClient","User Name = "+serviceInterface.getName().name);
      Toast.makeText(localContext, ""+serviceInterface.getName().name, Toast.LENGTH_SHORT).show();
            } catch (RemoteException e) {
            // TODO Auto-generated catch block
                  e.printStackTrace();
            }
      }
};

Step 5: Client side, In the next line I am getting the class Student from service using getName().

Log.i("RemoteClient","User Name = "+serviceInterface.getName().name);


Step 6: : Service Side, Here simply we receive the Student object in setName(). In getName() I alter the name field of object and return it.

private IRemoteInterface.Stub mBinder = new IRemoteInterface.Stub() {
            @Override
            public  Student getName() throws RemoteException {
                  // TODO Auto-generated method stub
                  stuInfo.name = stuInfo.name.toUpperCase();
                  return stuInfo;
            }
            @Override
            public void setName(Student st) throws RemoteException {
                  // TODO Auto-generated method stub
                  stuInfo = st;
                 
            }
      };




Thus we pass the user defined Object (Student object) from client to server and vice versa. 

NOTE : AIDL also not able to send Date type object. In the next Post I will show How to send Date Type object.


It simply copied from another site , wanted to have stuff in my blog :) 


Wednesday, May 23, 2012

How to have SystemService

There are some defined steps that leads to convert your service as systemService .
By doing this , you can call your service , the way we are calling LocationService , PowerManager and WindowManager etc . (ie  Context.getSystemservice(Context.String)   )


a .We need to Create 3 New files

   1.  Create a Service
   2 . Create wrapper class (Kind of )
   3.  Create aidl file

Refer http://processors.wiki.ti.com/index.php/Android-Adding_SystemService

b. Changes in four files

   1. Changes in Context.java and contextImpl.java
           have to change in getSystemService() API
   2. Changes in Android.mk file
   3.Changes in SystemServer.java file
 

Below table tells that , where to add/modify what .









Monday, May 21, 2012

Interface and Abstract

Well, Every one has different way of style to explain the interface and abstract  . 

here am going to explain when to use what .
straight forward explanation is , where you need to implement some function in the derived (child) class , then you need to use Interface whereas you want to use parent class implementation then you could have use Abstract .

There are some other reason of having Interface .

have a look at the below example

   class parent {
 
    void  business() =0 ;
   };


class child : public parent {

void business() {
// doing some business for survival .
}

};
 

Conclusion : Parent wants all the children to do their own business , In this case we could have use Interface



 class parent {
 
   virtual  void  business(){
     // family business
     } ;
   };


class child : public parent {

void business() {
// doing some business  .
}

};



here child  is implementing some business , But it is not necessary since parent is doing family business .

we are giving freedom to child , if you want implement it else will consider his business is family business

Conclusion : There are some situation where child may or may not implement business , If child is doing some business ,then we are taking that else taking from parent .

















Saturday, May 12, 2012

Inheritance

Points to remember in Inheritance

1.  Base class destructor should be virtual
        -> If it is not , we will end up in memory leak

Base * ptr = new Derived();
 delete ptr ;  // this will call base class's destructor   , not both class's destructor
   
2. Base class's Constructor and destructor should be public
    -> Otherwise will gets compile time issue



Compilation Stage



Friday, May 11, 2012

Understanding of virtual function




It is a function or method can be overridden within an inheriting class by a function with the same signature ,In other words , the purpose of virtual function is , to allow customization of derived class implementation


   “Where there is a casting there is a virtual”

Base * ptr = new Base() ; //  No need of virtual
Derived * ptr = new Derived();  // No need of virtual
Base * ptr = new Derived(); // need virtual to call correct function

Key benefits of Virtual function :

     It is allowed us to do function over riding
       
    Class Base { virtual void fn1() ; };
    Class derived: public base {void fn1() ;}

   Base* ptr = new derived() ;
    Ptr->fn1() ; this calls the derived class function fn1()

Above class become ptr->_vptr->fn1() ;

Now , consider if fn1() is not declared as virtual , then   the above call would call the Base class function .

Best part of this concepts is , you can have an array ,type of  Base* . and you can append derived classes object without worrying about function call .

 It is avoiding memory leak
  
   lets look at the below code
  
    Class Base { void ~Base() ; };
    Class derived: public base {void ~derived() ;}
   
    Base* ptr = new derived() ;
    delete ptr ;
   oops , there is a memory leak , above call only call base class destructor  .
  
wanna avoid memory leak
  Class Base { virtual void ~Base() ; };

Now , it will use vptr , and it will call the derived class destructor and subsequently it will call base class destructor

Disadvantages or Cost of virtual function

1.      If a class contains virtual function , then vtable is created , which means additional memory space required for that
2.      virtual function are mapped at runtime through vtable . hence calling virtual function is slow compared to normal function
3. vptr (virtual pointer which points to vtable) is created for every object .Additional 4 byte required to store vptr


pictorial representation of virtual function  


 





At last ,  If a function declared as virtual in base class , then the function in all derived class are virtual only . No need to mention it explicitly using “virtual” keyword


Some FAQ:

  1. What is the size of an empty class
Ans : 1 byte , because compiler provides minimum 1 byte to the object

  1. what is the size of the class  class A { virtual void fn1();};
      Ans : 4 byte ,  now vptr (virtual pointer comes in to the picture)
      
  1. What is pure virtual function
 Ans : A virtual function doesn’t have body
         Virtual void fn1() = 0;

  1. Can we create object of the class which has pure virtual function
Ans : No , Compiler will check the body of the function while creating object of the class , since it doesn’t have the body we can’t create the object and compiler will throw an error at the time of compilation







Factory Reset in Android phones

Below dial code used to do factory reset in android phones
*2767*3855#

Tested in Samsung phones 

Thursday, May 10, 2012

Creating transparent Activity in Android

Creating Transparent is quite simple in android .
  you have to add  transparent theme for which activity you wants to made Transparent

  <activity
            android:name=".AlarmUIActivity"
            android:label="@string/app_name"
             android:theme="@android:style/Theme.Translucent.NoTitleBar">