Android binding type service-inherit the binder class

Source: Internet
Author: User

If you only use services locally in an application and do not need to work across processes, You can implement your own binder class, use it to directly provide your client with the ability to access public methods in the service.

Note:Generally, the client and server only work in the same application and process. For example, for an application that needs to play music well, you need to bind the music playing service working in the background to an activity of the app.

Follow these steps to create a binding service:

1. Create a binder instance in the service using one of the following methods:

A. Public methods that can be called by the client;

B. Return the instance of the current service, which has public methods that can be called by the client;

C. Return another class held by the Service with a public method that the client can call.

2. Return the instance of this binder object from the onbind () callback method;

3. on the client side, receive the binder object in the onserviceconnected () callback method, and use the method provided by this object to call the bound service.

Note:The reason why the server and client must be in the same application is that such a client can convert the returned object and correctly call its own APIs. The server and client must also be in the same process, because this technology does not execute any cross-process processing.

For example, the following server code provides the ability to access the server through the binder:

Public class LocalService extends Service {
// Binder given to clients
Private Final ibinder mbinder = new localbinder ();
// Random number generator
Private final random mgenerator = new random ();

/**
* Class used for the client binder. Because we know this service always
* Runs in the same process as its clients, we don't need to deal with IPC.
*/
Public class localbinder extends binder {
LocalService getservice (){
// Return this instance of LocalService so clients can call public methods
Return LocalService. This;
}
}

@ Override
Public ibinder onbind (intent ){
Return mbinder;
}

/** Method for clients */
Public int getrandomnumber (){
Return mgenerator. nextint (100 );
}
}

The localbinder object in the above Code provides the getservice () method to the client, which can be used to obtain the current instance of the LocalService. This allows the client to call public methods in the service. For example, a client can call the getrandomnumber () method of the server.

The following activity code binds the LocalService and calls the getrandomnumber () method of the service when you click a button:

Public class bindingactivity extends activity {
LocalService mservice;
Boolean mbound = false;

@ Override
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
}

@ Override
Protected void onstart (){
Super. onstart ();
// Bind to LocalService
Intent intent = new intent (this, LocalService. Class );
Bindservice (intent, mconnection, context. bind_auto_create );
}

@ Override
Protected void onstop (){
Super. onstop ();
// Unbind from the service
If (mbound ){
Unbindservice (mconnection );
Mbound = false;
}
}

/** Called when a button is clicked (the button in the layout file attaches
* This method with the Android: onclick attribute )*/
Public void onbuttonclick (view v ){
If (mbound ){
// Call a method from the LocalService.
// However, if this call were something that might hang, then this request shoshould
// Occur in a separate thread to avoid slowing down the activity performance.
Int num = mservice. getrandomnumber ();
Toast. maketext (this, "Number:" + num, Toast. length_short). Show ();
}
}

/** Defines callbacks for Service binding, passed to bindservice ()*/
Private serviceconnection mconnection = new serviceconnection (){

@ Override
Public void onserviceconnected (componentname classname,
Ibinder Service ){
// We 've bound to LocalService, cast the ibinder and get LocalService instance
Localbinder binder = (localbinder) service;
Mservice = binder. getservice ();
Mbound = true;
}

@ Override
Public void onservicedisconnected (componentname arg0 ){
Mbound = false;
}
};
}

The preceding example shows how to bind a service using the serviceconnection interface and the onserviceconnected callback method on the client. The following sections will provide more information about binding service processes.

Note:In the preceding example, the server is not explicitly unbound. However, all clients should be unbound at the right time (for example, when the activity is paused ).

 

Sample Code: LocalService. Java

/*
* Copyright (c) 2007 the android open source project
*
* Licensed under the Apache license, version 2.0 (the "License ");
* You may not use this file before t in compliance with the license.
* You may obtain a copy of the license
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* Distributed under the license is distributed on an "as is" basis,
* Without warranties or conditions of any kind, either express or implied.
* See the license for the specific language governing permissions and
* Limitations under the license.
*/

Package com. example. Android. APIs. app;

Import Android. App. notification;
Import Android. App. icationicationmanager;
Import Android. App. pendingintent;
Import Android. App. Service;
Import Android. content. intent;
Import Android. OS. Binder;
Import Android. OS. ibinder;
Import Android. util. log;
Import Android. widget. Toast;

// Need the following import to get access to the app resources, since this
// Class is in a sub-package.
Import com. example. Android. APIs. R;

/**
* This is an example of implementing an application service that runs locally
* In the same process as the application. The {@ link localserviceactivities. Controller}
* And {@ link localserviceactivities. Binding} classes show how to interact with
* Service.
*
* <P> notice the use of the {@ link notificationmanager} When interesting things
* Happen In the service. This is generally how background services shocould
* Interact with the user, rather than doing something more disruptive such
* Calling startactivity ().
*/
Public class LocalService extends Service {
Private icationicationmanager mnm;

// Unique identification number for the notification.
// We use it on notification start, and to cancel it.
Private int 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
* IPC.
*/
Public class localbinder extends binder {
LocalService getservice (){
Return LocalService. This;
}
}

@ Override
Public void oncreate (){
Mnm = (icationicationmanager) getsystemservice (notification_service );

// Display a notification about us starting. We put an icon in the status bar.
Shownotification ();
}

@ Override
Public int onstartcommand (intent, int flags, int startid ){
Log. I ("LocalService", "received start ID" + startid + ":" + intent );
// We want this service to continue running until it is explicitly
// Stopped, so return sticky.
Return start_sticky;
}

@ Override
Public void ondestroy (){
// Cancel the persistent notification.
Mnm. Cancel (notification );

// Tell the user we stopped.
Toast. maketext (this, R. String. local_service_stopped, Toast. length_short). Show ();
}

@ Override
Public ibinder onbind (intent ){
Return mbinder;
}

// This is the object that calls es interactions from clients. See
// Remoteservice for a more complete example.
Private Final ibinder mbinder = new localbinder ();

/**
* Show a notification while this service is running.
*/
Private void shownotification (){
// In this sample, we'll use the same text for the ticker and the expanded notification
Charsequence text = gettext (R. String. local_service_started );

// Set the icon, scrolling text and timestamp
Notification = new notification (R. drawable. stat_sample, text,
System. currenttimemillis ());

// The pendingintent to launch our activity if the user selects this notification
Pendingintent contentintent = pendingintent. getactivity (this, 0,
New intent (this, localserviceactivities. Controller. Class), 0 );

// Set the info for the views that show in the notification panel.
Notification. setlatesteventinfo (this, gettext (R. String. local_service_label ),
Text, contentintent );

// Send the notification.
Mnm. Y (notification, notification );
}
}

 

Localserviceactivities. Java

/*
* Copyright (c) 2007 the android open source project
*
* Licensed under the Apache license, version 2.0 (the "License ");
* You may not use this file before t in compliance with the license.
* You may obtain a copy of the license
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* Distributed under the license is distributed on an "as is" basis,
* Without warranties or conditions of any kind, either express or implied.
* See the license for the specific language governing permissions and
* Limitations under the license.
*/

Package com. example. Android. APIs. app;

Import com. example. Android. APIs. R;

Import Android. App. activity;
Import Android. content. componentname;
Import Android. content. context;
Import Android. content. intent;
Import Android. content. serviceconnection;
Import Android. OS. Bundle;
Import Android. OS. ibinder;
Import Android. View. view;
Import Android. View. View. onclicklistener;
Import Android. widget. Button;
Import Android. widget. Toast;

Public class localserviceactivities {
/**
* <P> example of explicitly starting and stopping the local service.
* This demonstrates the implementation of a service that runs in the same
* Process as the rest of the application, which is explicitly started and stopped
* As desired. </P>
*
* <P> note that this is implemented as an inner class only keep the sample
* All together; typically this code wowould appear in some separate class.
*/
Public static class controller extends activity {
@ Override
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );

Setcontentview (R. layout. local_service_controller );

// Watch for button clicks.
Button button = (button) findviewbyid (R. Id. Start );
Button. setonclicklistener (mstartlistener );
Button = (button) findviewbyid (R. Id. Stop );
Button. setonclicklistener (mstoplistener );
}

Private onclicklistener mstartlistener = new onclicklistener (){
Public void onclick (view v ){
// Make sure the service is started. It will continue running
// Until someone CILS stopservice (). The intent we use to find
// The service explicitly specifies our service component, because
// We want it running in our own process and don't want other
// Applications to replace it.
Startservice (new intent (controller. This,
LocalService. Class ));
}
};

Private onclicklistener mstoplistener = new onclicklistener (){
Public void onclick (view v ){
// Cancel a previous call to startservice (). Note that
// Service will not actually stop at this point if there are
// Still bound clients.
Stopservice (new intent (controller. This,
LocalService. Class ));
}
};
}

//----------------------------------------------------------------------

/**
* Example of binding and unbinding to the local service.
* This demonstrates the implementation of a service which the client will
* Bind to, specify an object through which it can communicate with the Service. </P>
*
* <P> note that this is implemented as an inner class only keep the sample
* All together; typically this code wowould appear in some separate class.
*/
Public static class binding extends activity {
Private Boolean misbound;

Private LocalService mboundservice;

Private serviceconnection mconnection = new serviceconnection (){
Public void onserviceconnected (componentname classname, ibinder Service ){
// This is called when the connection with the service has been
// Established, giving us the service object we can use
// 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 ();
}

Public void onservicedisconnected (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 shoshould never
// See this happen.
Mboundservice = NULL;
Toast. maketext (binding. This, R. String. local_service_disconnected,
Toast. length_short). Show ();
}
};

Void dobindservice (){
// Establish a connection with the service. We use an explicit
// Class name because we want a specific service implementation that
// We know will be running in our own process (and thus won't be
// Supporting component replacement by other applications ).
Bindservice (new intent (binding. This,
LocalService. Class), mconnection, context. bind_auto_create );
Misbound = true;
}

Void dounbindservice (){
If (misbound ){
// Detach our existing connection.
Unbindservice (mconnection );
Misbound = false;
}
}

@ Override
Protected void ondestroy (){
Super. ondestroy ();
Dounbindservice ();
}

Private onclicklistener mbindlistener = new onclicklistener (){
Public void onclick (view v ){
Dobindservice ();
}
};

Private onclicklistener munbindlistener = new onclicklistener (){
Public void onclick (view v ){
Dounbindservice ();
}
};

@ Override
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );

Setcontentview (R. layout. local_service_binding );

// Watch for button clicks.
Button button = (button) findviewbyid (R. Id. Bind );
Button. setonclicklistener (mbindlistener );
Button = (button) findviewbyid (R. Id. Unbind );
Button. setonclicklistener (munbindlistener );
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.