Android notes ---- Service Components

Source: Internet
Author: User

Android notes ---- Service Components

Service Overview

Cross-process Service calling (AIDL Service)

Phone Manager

SMS Manager

 

 

 

Service Overview

Services are the most similar components of Android and Activity. They all represent executable programs. The difference between a Service and an Activity is that a Service has been running in the background and has no user interface. Once a Service is started, it also has its own life cycle like an Activity.

The Service component is also an executable program and has its own lifecycle. The process of creating and configuring a Service is similar to that of creating and configuring an Activity. The following describes the Service development process.

1.1 Service Development

To develop a Service, follow these steps:

Defines a subclass that inherits services.

Configure the Service in the AndroidManifest. xml file.

Similar to Activity, Service also defines a series of lifecycle methods, as shown below:

OnStartCommand (): This method is called back every time the client calls the startService (Intent) method to start the Service.

IBinder onBind (Intent intent): This method is a required method of the Service subclass. It communicates with other services through the returned IBinder object.

OnCreate (): calls back this method when the Service is created for the first time.

OnDestroy (): This method will be called back before the Service is closed.

OnUnbind (): This method is called back when all clients bound to the Service are disconnected.

Configure Service Usage , Or Element configuration Child element, used to indicate which Intent can start the service.

In Android, a Service cannot run on its own. It needs to be called through an Activity or another Context object. There are two ways to start a Service:

StartService () method of Context: This method is used to start the Service. There is no association between the visitor and the Service. Even if the visitor exits, the Service is still running.

BindService () method of Context: This method is used to start the Service. The visitor and Service are bound together. Once the visitor exits, the Service is terminated.

 

Example: Service Usage:

MainActivity. java

Public class MainActivity extends Activity {Button start, stop; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // obtain the start and stop buttons in the program interface. start = (Button) findViewById (R. id. start); stop = (Button) findViewById (R. id. stop); // create Intentfinal Intent intent = new Intent (); // set the Action attribute Intent for intent. setAction (com. boby. service. FIRST_SERVICE); start. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View arg0) {// start specified SerivcestartService (intent) ;}}); stop. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View arg0) {// stop specified SerivcestopService (intent );}});}}

 

Configure Service in the configuration file:

 

 

1.2 bind and communicate with the local Service

When a program starts or closes a Service through startService () and stopService (), there is basically no association between the Service and the visitor, so the Service and the visitor cannot communicate or exchange data.

If you want to exchange data between services and visitors, you need to call methods or exchange data. BindService () and unbindService () should be used to start and close the service.

The bindService (Intent service, ServiceConnection conn, int flags) of Context calls back the onSerciceConnected (ComponentName, IBinder Service) method of the ServiceConnection object when the connection between the visitor and the service is successful, when a visitor disconnects from the Service, the onSerciceDisconnected (ComponentName name) method of ServiceConnection is called back.

When developing a Service class, the Service class must provide an IBinder onBind (Intent intent) method. When binding a local Service, onBind (Intent intent) the IBinder object returned by the method will be passed to the service parameter in the onSerciceConnected (ComponentName, IBinder service) method, so that visitors can communicate with the Service through this IBinder object.

 

For example, binding an Activity to a local Service:

MainActivity. java

Public class MainActivity extends Activity {Button bind, unbind, getServiceStatus; // keep the IBinder object BindService of the started Service. myBinder binder; // defines a ServiceConnection object private ServiceConnection conn = new ServiceConnection () {// calls back this method when the Activity and Service are successfully connected @ Overridepublic void onServiceConnected (ComponentName name, IBinder service) {System. out. println (-- Service Connected --); // obtain the MyBinder object binder = (BindService. myBinder) service;} // call back this method when the Activity is disconnected from the Service @ Overridepublic void onServiceDisconnected (ComponentName name) {System. out. println (-- Service Disconnected --) ;};@ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // obtain the start, stop, and getServiceStatus buttons in the Program Interface bind = (Button) findViewById (R. id. bind); unbind = (Button) findViewById (R. id. unbind); getServiceStatus = (Button) findViewById (R. id. getServiceStatus); // create Intentfinal Intent intent = new Intent (); // set the Action attribute Intent for intent. setAction (com. boby. service. BIND_SERVICE); bind. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View source) {// bind specified SerivcebindService (intent, conn, Service. BIND_AUTO_CREATE) ;}}); unbind. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View source) {// unbind SerivceunbindService (conn) ;}}); getServiceStatus. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View source) {// obtain and display the count value of the Service Toast. makeText (MainActivity. this, Serivce's count value is: + binder. getCount (), 4000 ). show ();}});}}

 

Configure Service in the configuration file:

  
  

 

1.3 Service Lifecycle

The Service lifecycle varies slightly when the Service is started in an application.

 

Cross-process Service calling (AIDL Service)

2.1 AIDL service Introduction

Cross-process access (AIDL Service) does not share memory between processes in the Android system. Therefore, some mechanisms need to be provided for data communication between different processes.

To enable other applications to access the services provided by this application, Android uses an Interface Definition Language (IDL) to publish service interfaces. Therefore, this kind of service that can be accessed across processes is called the AIDL (Android Interface Definition Language) service.

For Android remote Service calls, you must first define a remote call interface and then provide the Implementation class of this interface.

When the client accesses the local Service, the Service only returns a callback object (IBinder object) to the client through the onBind () method. The onBind () method of the remote Service only transmits the proxy of the IBinder object to the second parameter of the onserviceconnection onServiceConnected method of the client. After the client obtains the proxy of the IBinder object of the remote Service, it can call back the attributes or methods of the remote Service through the IBinder object.

 

2.2 Procedure for creating an AIDL Service
Creating an AIDL service is more complex than creating a common service. The specific steps are as follows:
(1) Create an aidl file in the Java package directory of the Eclipse Android project. The syntax of this file is similar to Java code, but it will be slightly different.
(2) If the content of the aidl file is correct, ADT will automatically generate a Java interface file (*. java ).
(3) create a Service class ).
(4) Implement the Java interface generated by the aidl file.
(5) In AndroidManifest. configure the AIDL service in the xml file. In particular, the attribute value of android: name in the tag is the ID of the service to be referenced by the client, that is, the parameter value of the Intent class.

 

2.3 expose data to the client

After the AIDL interface is defined in the previous step, a Service implementation class is defined. The IBinder object returned by the onBind () method of the Service should be an instance of the ICat. Stub subclass generated by the ADT.

 

AndroidManifest. xml

 
 
  
  
   
  
 

 

For example, cross-process Service call:

AidlService. java

Public class AidlService extends Service {private CatBinder catBinder; Timer timer = new Timer (); String [] colors = new String [] {red, yellow, black }; double [] weights = new double [] {2.3, 3.1, 1.58}; private String color; private double weight; // inherits Stub, that is, implements the ICat interface, and implements the IBinder interface public class CatBinder extends Stub {@ Overridepublic String getColor () throws RemoteException {return color ;}@ Overridepublic double getWeigh T () throws RemoteException {return weight ;}@ Overridepublic void onCreate () {super. onCreate (); catBinder = new CatBinder (); timer. schedule (new TimerTask () {@ Overridepublic void run () {// randomly change the value of the color and weight attributes in the Service component. Int rand = (int) (Math. random () * 3); color = colors [rand]; weight = weights [rand]; System. out. println (-------- + rand) ;}}, 0,800) ;}@ Overridepublic IBinder onBind (Intent arg0) {/* return the catBinder object * When binding a local Service, this catBinder object will directly * pass to the second parameter of the onServiceConnected method of the ServiceConnection object * of the client; * When binding a remote Service, only pass the proxy * of the catBinder object to the second parameter of the onServiceConnected method of the ServiceConnection object * of the client; */return catBinder ;}@ Overridepublic void onDestroy () {timer. cancel ();}}

 

2.4 client access to AIDLService

The AIDL interface defines the communication interfaces between two processes. Therefore, the client also needs the AIDL interface just defined. Therefore, the first step of the Client development is to copy the AIDL interface file of the Service to the client application. After being copied to the client, the ADT tool generates an implementation for the AIDL interface.

To bind a remote Service to a client, follow these two steps:

Create a ServiceConnection object.

Call the bindService () method of Context to remotely call the Service using the ServiceConnection object as the parameter.

The ServiceConnection bound to a remote Service does not directly obtain the objects returned by the onBind () method of the Service. Only the proxy of the objects returned by the onBind () method can be returned. Therefore, the on ServiceConnected method of ServiceConnection must be processed using the following code:

 

AidlClient. java

Public class AidlClient extends Activity {private ICat catService; private Button get; EditText color, weight; private ServiceConnection conn = new ServiceConnection () {@ Overridepublic void onServiceConnected (ComponentName, IBinder service) {// obtain the proxy catService = ICat of the object returned by the onBind method of the remote Service. stub. asInterface (service) ;}@ Overridepublic void onServiceDisconnected (ComponentName name) {catService = null ;};@ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); get = (Button) findViewById (R. id. get); color = (EditText) findViewById (R. id. color); weight = (EditText) findViewById (R. id. weight); // create the IntentIntent intent = new Intent (); intent. setAction (com. boby. aidl. action. AIDL_SERVICE); // bindService (intent, conn, Service. BIND_AUTO_CREATE); get. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View arg0) {try {// obtain and display the status color of the remote Service. setText (catService. getColor (); weight. setText (catService. getWeight () +);} catch (RemoteException e) {e. printStackTrace () ;}}) ;}@ Overridepublic void onDestroy () {super. onDestroy (); // unbind this. unbindService (conn );}}

 

Phone Manager

TelephonyManager is a service class that manages the communication status and network information of a mobile phone. It provides a large number of getXxx () methods to obtain information about the telephone network.

To obtain TelephonyManager in a program, you only need to call the following code:

 

 

For example, listen for phone calls:

MonitorPhone. java

Public class MonitorPhone extends Activity {TelephonyManager tManager; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // get the TelephonyManager object tManager = (TelephonyManager) getSystemService (Context. TELEPHONY_SERVICE); // create a call status listener PhoneStateListener listener = new PhoneStateListener () {@ Overridepublic void onCallStateChanged (int state, String incomingNumber) {switch (state) {// No Status case TelephonyManager. CALL_STATE_IDLE: break; case TelephonyManager. CALL_STATE_OFFHOOK: break; // case TelephonyManager when the incoming call rings. CALL_STATE_RINGING: OutputStream OS = null; try {OS = openFileOutput (phoneList, MODE_APPEND);} catch (FileNotFoundException e) {e. printStackTrace ();} PrintStream ps = new PrintStream (OS); // records the number of future calls to the file. println (new Date () + Incoming call: + incomingNumber); ps. close (); break; default: break;} super. onCallStateChanged (state, incomingNumber) ;}}; // listens to tManager for changing the call status. listen (listener, PhoneStateListener. LISTEN_CALL_STATE );}}

Note: The data/com. under the boby/files directory, you can see a phoneList file, export the file, view its content, and record the incoming calls from another simulator.

 

 

SMS Manager

SmsManager is another very common service provided by Android. SmsManager provides the system sendXxxMessage () method for sending text messages. A text message is usually a common text content, that is, it can be sent by calling the sendTextMessage () method.

For example, two simulators send messages to each other:

The following program uses a PendingIntent object, which is a packaging of Intent. The PendingIntent object is usually obtained by calling the getActivity (), getService (), and getBroadcastReceiver () Static Methods of PendingIntent.

PendingIntent is usually passed to other application components, so that other applications can execute the "Intent" encapsulated by PendingIntent ".

 

Example:

SendSms. java

Public class SendSms extends Activity {EditText number, content; Button send; SmsManager sManager; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // get SmsManagersManager = SmsManager. getDefault (); // get two text boxes and buttons on the program interface number = (EditText) findViewById (R. id. number); content = (EditText) findViewById (R. id. content); send = (Button) findViewById (R. id. send); // bind the listener send to the Click Event of the send button. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View arg0) {// create a PendingIntent object PendingIntent pi = PendingIntent. getActivity (SendSms. this, 0, new Intent (), 0); // send SMS sManager. sendTextMessage (number. getText (). toString (), null, content. getText (). toString (), pi, null); // you are prompted to send the Toast message. makeText (SendSms. this, the text message is sent, 8000 ). show ();}});}}

 

 
 


 

 

 

 

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.