Android Learning Note (53): Services Service (next)-Remote service

Source: Internet
Author: User

Previously discussed service is a local service, that is, service and client within the same process (that is, within the same application), the service life cycle is subject to the life cycle of the process. In practical applications, it is sometimes desirable that service be used as a back-office service, not only by activity within the same process, but also by other processes, in which case the bindservice, or remote service, is required.

In Android, different apps belong to different processes (processes), which are the boundaries of the security policy, and one process cannot access the storage of other processes (for example, using ContentProvider). In remote service, interprocess communication, commonly referred to as IPC (interprocess commnication), requires a connection between process A and process B for mutual communication or data transfer.

Android offers the Aidl (Android Interface Definition Language) tool to help establish the interface between IPC, greatly simplifying the developer view. Right only to help understand the code. The following steps enable communication between the client and service:

"1" Defines the Aidl interface, and Eclipse will automatically establish an interface for the service IService
The "2" client connects to the service, connects to the stub that the IService exposes to the client, obtains the stub object, in other words, the service supplies the client with a stub in the interface, The concrete implementation of abstract iservice.stub in IService.
After the "3" client and service are connected, the client can simply invoke the method inside the iservice.stub using the local method.

The following example shows an example of a client receiving a service from a remote service that provides a timed count, called Testremoteservice.

Step 1: Define the interface provided by the service to the client through the Aidl file , the Itestremoteservice.aidl file is as follows

Package com.wei.android.learning.part5;
Interface Itestremoteservice {
int Getcounter ();
}

We add a i<serviceclassname>.aidl file in the SRC directory with the same syntax as Java. In this example, the service is very simple and provides only the value of the counter, so we define the int getcounter () in the interface.

The Aidl file is simple, and Eclipse automatically generates a related Java interface file based on the file, but it doesn't show up, and if you use the command-line tool directly, it will help generate Java files.

Step 2:remote The service is written, passing the stub object through Onbind (), when the client connects. the Testremoteservice.java file is as follows:

/* Service provides a timer counter, implemented in Runnable Way, review Android Learning notes (31): Threads: Message and Runnable in Example 3. To avoid distracting attention, gray out this part of the code. In addition, we provide showinfo () to track the operation of the service, which is also grayed out. */
public class Testremoteservice extends service{
Private Handler Servicehandler = null;
private int counter = 0;
Private Testcountertask MyTask = new Testcountertask ();

public voidonCreate() {
Super.oncreate ();
Showinfo ("Remote Service OnCreate ()");
}

public voidOnDestroy() {
Super.ondestroy ();
Servicehandler.removecallbacks (MyTask); Stop counter
Servicehandler = null;
Showinfo ("Remote Service OnDestroy ()");
}

public void OnStart (Intent Intent, int startid) {
Turn on the counter
Super.onstart (Intent, Startid);
Servicehandler=new Handler ();
Servicehandler.postdelayed (MyTask, 1000);
Showinfo ("Remote Service OnStart ()");
}

//Step 2.1: specifically implement the stub exposed to the client in the interface, providing a stub inner class to implement.
Privateitestremoteservice.stub stub= New Itestremoteservice.stub (){
Step 2.1: Implement the various methods of defining the interface in the Aidl file.
public int Getcounter () throws RemoteException {
Showinfo ("Getcounter ()");
return counter;
}
};

//Step 2.2: When the client is connected, Onbind () is triggered and the service returns a stub object to the client so that the client can access the service through the stub object, in this case through Stub.getcounter ( ) to get the current count of the timer. In this example, we pass the same stub object to all the client.
Public IBinder Onbind (Intent arg0) {
Showinfo ("Onbind ()" + stub); //we specifically tracked the address of the stub object ., you can see through serviceconnection delivery to the client in the Client connection service
return stub;
}

/* Use the timer counter with runnable, plus 1 for every 10 seconds counter. */
Private class Testcountertask implements runnable{
public void Run () {
+ + counter;
Servicehandler.postdelayed (mytask,10000);
Showinfo ("Running" + counter);
}
}
/* Showinfo () help us with information tracking to better understand the operation of the service * *
private voidShowinfo(String s) {
System.out.println ("[" +getclass (). Getsimplename () + "@" + thread.currentthread (). GetName () + "]" + s);
}
}

Step 3:client and service to establish a connection, get stub, Servicetest4.java code as follows

public class ServiceTest4 extends activity{
PrivateItestremoteserviceRemoteservice = null;//Step 3.1 define interface variables
Private Boolean isstarted = false;
Privatecounterserviceconnectionconn = null;//Step 3.1 Define the connection variables to implement the Serviceconnection interface

protected void OnCreate (Bundle savedinstancestate) {
...//5 buttons respectively trigger StartService (), StopService (), Bindservice (), Releaseservice () and Invokeservice (), the following two lines, A row shows the count value obtained from the service and a row displays the status.
}

private void StartService () {
Intent i = new Intent ();
I.setclassname ("com.wei.android.learning", "Com.wei.android.learning.part5.TestRemoteService"); There are layers in my bag, like *.part1 and *.part2,etc.
StartService (i);//As with the previous local service, the service is initiated via intent, triggering the oncreate () [If service is not turned on]->onstart ()
IsStarted = true;
Updateservicestatus ();
}
private void StopService () {
Intent i = new Intent ();
I.setclassname ("com.wei.android.learning", "Com.wei.android.learning.part5.TestRemoteService");
StopService (i);//OnDestroy () that triggers the service [if service exists]
IsStarted = false;
Updateservicestatus ();
}
//Step 3.3:bindservice () Establish a connection between the service through a class that implements the Serviceconnection interface, noting the parameters context.bind_auto_create inside, triggering the OnCreate () [If service does not exist]–> Onbind ().
private void Bindservice () {
if (conn = = null) {
conn = new counterserviceconnection ();
Intent i = new Intent ();
I.setclassname ("com.wei.android.learning", "Com.wei.android.learning.part5.TestRemoteService");
Bindservice (I,Conn,context.bind_auto_create);
Updateservicestatus ();
}
}

private void Releaseservice () {
if (conn!=null) {
Unbindservice(conn);//Disconnect, unbind
conn = null;
Updateservicestatus ();
}
}
private void Invokeservice () {
IF (conn! = null) {
try{
Integer counter =remoteservice.getcounter ();//Once the client is successfully bound to the service, the method in the stub can be used directly.
TextView t = (TextView) Findviewbyid (r.id.st4_notapplicable);
T.settext ("Counter value:" + integer.tostring (Counter));
}catch (RemoteException e) {
LOG.E (GetClass (). Getsimplename (), e.tostring ());
}
}
}
//Step 3.2 class Counterserviceconnection implement Serviceconnection interface, need to implement the inside two trigger onserviceconnected () and onservicedisconnected ()
Privateclass Counterserviceconnection implements Serviceconnection{
@Override
public voidonserviceconnected(componentname name, IBinder service) {
Get stub objects from the connection, according to our tracking, Remoteservice is the stub object in the service
Remoteservice = ITestRemoteService.Stub.asInterface (service);
Showinfo ("onserviceconnected ()" + Remoteservice);
}

@Override
public voidonservicedisconnected(componentname name) {
Remoteservice = null;
Updateservicestatus ();
Showinfo ("onservicedisconnected");
}
}
private void Updateservicestatus () {
TextView t = (TextView) Findviewbyid (r.id.st4_servicestatus);
T.settext ("Service Status:" + (conn = = null?) Unbound ":" Bound ") +", "+ (isstarted? "Started": "Not Started"; ));
}
private void Showinfo (String s) {
System.out.println ("[" +getclass (). Getsimplename () + "@" + thread.currentthread (). GetName () + "]" + s);
}
}

RELATED Links: My Android development related articles

Android Learning Note (53): Services Service (next)-Remote service

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.