-1

Hi I'm new to android and I need to know what exactly happens in the below-highlighted code regarding the IBinder and why do we use an inner class for this purpose.

public class MyRandomService extends Service {

    private class LocalBinder extends Binder {
        MyRandomService getService() {
            return MyRandomService.this;
        }
    }
    private LocalBinder localBinder = new LocalBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return localBinder;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }    

    @Override
    public void onDestroy() {
        stop_random_number_generator();
    } 

}
CodeMatrix
  • 2,124
  • 1
  • 18
  • 30
harinsamaranayake
  • 751
  • 2
  • 12
  • 32

2 Answers2

0

It is an inner class so you can return the outer Service instance easily. You could als make it an external class Referring from here: IBinder details

Qandil Tariq
  • 539
  • 1
  • 3
  • 15
0

IBinder:

To create a bound service, you must define the interface that specifies how a client can communicate with the service. This interface between the service and a client must be an implementation of IBinder and is what your service must return from the onBind() callback method. After the client receives the IBinder, it can begin interacting with the service through that interface.

onBind():

The system invokes this method by calling bindService() when another component wants to bind with the service (such as to perform RPC). In your implementation of this method, you must provide an interface that clients use to communicate with the service by returning an IBinder. You must always implement this method; however, if you don't want to allow binding, you should return null.

For more info https://developer.android.com/reference/android/os/IBinder

jettimadhuChowdary
  • 1,058
  • 1
  • 13
  • 23