Skip to content Skip to sidebar Skip to footer

Android Local Service Sample, Bindservice(), And Serviceconnection()

I have a question which is related to this question that was asked by @mnish about a year ago. Please have a look at his question and code. He implements a ServiceConnection() and

Solution 1:

He is probably using Android Interface Definition Language (AIDL) http://developer.android.com/guide/components/aidl.html

Therefore he has to use a stub of the server side implementation like documented:

// This is called when the connection with the service has been// established, giving us the service object we can use to// interact with the service.  We are communicating with our// service through an IDL interface, so get a client-side// representation of that from the raw service object.
 mService = IRemoteService.Stub.asInterface(service);

The iservice reference is coming from the onServiceConnected method which is called after binding the service to your activity. The call bindService gets passed the ServiceConnection which implements the onServiceConnected method.

You don't need the "IRemoteService.Stub.asInterface(service)" when your implementation of the service is local, then you can just cast the service to you local service.

The local service sample does this in the service:

publicclassLocalServiceextendsService {
    private NotificationManager mNM;

    // Unique Identification Number for the Notification.// We use it on Notification start, and to cancel it.privateint NOTIFICATION = R.string.local_service_started;

    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */publicclassLocalBinderextendsBinder {
        LocalService getService() {
        return LocalService.this;
        }
    }

    ...

}

And this in the Activity in the ServiceConnection class:

private ServiceConnection mConnection = new ServiceConnection() {
publicvoidonServiceConnected(ComponentName className, IBinder service) {
        // This is called when the connection with the service has been// established, giving us the service object we can use to// interact with the service.  Because we have bound to a explicit// service that we know is running in our own process, we can// cast its IBinder to a concrete class and directly access it.
        mBoundService = ((LocalService.LocalBinder)service).getService();

        // Tell the user about this for our demo.
        Toast.makeText(Binding.this, R.string.local_service_connected,
                Toast.LENGTH_SHORT).show();
    }

    publicvoidonServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been// unexpectedly disconnected -- that is, its process crashed.// Because it is running in our same process, we should never// see this happen.
        mBoundService = null;
        Toast.makeText(Binding.this, R.string.local_service_disconnected,
            Toast.LENGTH_SHORT).show();
    }
};

Solution 2:

Here you are, my example .. will make you clear about that LOL

// My MyServiceInterface.aidlpackage com.mad.exam;

interfaceMyServiceInterface {
     intgetNumber();
}

//MyService publicclassMyServiceextendsService {

    @Overridepublic IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Service OnBind()", Toast.LENGTH_LONG).show();
        return mBinder;
    }

    @OverridepublicvoidonCreate() {
        // TODO Auto-generated method stubsuper.onCreate();
        Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();
    }

    @OverridepublicvoidonDestroy() {
        // TODO Auto-generated method stubsuper.onDestroy();
        Toast.makeText(this, "Service Destroyed ", Toast.LENGTH_SHORT).show();
    }

    @OverridepublicvoidonStart(Intent intent, int startId) {
        // TODO Auto-generated method stubsuper.onStart(intent, startId);
        Toast.makeText(this, "Service Started ", Toast.LENGTH_SHORT).show();
    }

    @OverridepublicbooleanonUnbind(Intent intent) {
        // TODO Auto-generated method stubreturnsuper.onUnbind(intent);
    }

    privatefinal MyServiceInterface.StubmBinder=newMyServiceInterface.Stub() {
        publicintgetNumber() {
            returnnewRandom().nextInt(100);
        }
    };
}

//My Activity publicclassServiceDemoextendsActivityimplementsOnClickListener {
    MyServiceInterface mService;
    ServiceConnection mConnection;
    Button retreive;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stubsuper.onCreate(savedInstanceState);
        setContentView(R.layout.service);
        retreive = (Button) findViewById(R.id.retreive);
        retreive.setOnClickListener(this);

        mConnection = newServiceConnection() {

            publicvoidonServiceDisconnected(ComponentName name) {
                // TODO Auto-generated method stub
            }

            publicvoidonServiceConnected(ComponentName name, IBinder service) {
                // TODO Auto-generated method stub
                mService = MyServiceInterface.Stub.asInterface(service);

                try {
                    int i;
                    i = mService.getNumber();
                    Toast.makeText(ServiceDemo.this, "The service value is: " + String.valueOf(i), Toast.LENGTH_SHORT).show();
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
    }

    publicvoidonClick(View v) {
        // TODO Auto-generated method stub
        Log.i("My Tag", "Clicked");
        Buttonbtn= (Button) v;
        IntentcallService=newIntent(this, MyService.class);
        bindService(callService, mConnection, Context.BIND_AUTO_CREATE);
    }

    @OverrideprotectedvoidonStart() {
        // TODO Auto-generated method stubsuper.onStart();
        IntentcallService=newIntent(this, MyService.class);
        bindService(callService, mConnection, Context.BIND_AUTO_CREATE);
    }
}

Post a Comment for "Android Local Service Sample, Bindservice(), And Serviceconnection()"