There are two types of service:
Local Service: for internal application
Remote Service (SERCIE): for Applications within the Android system
The former is used to implement some of the time-consuming tasks of the application itself, such as query upgrade information, does not occupy the application, such as the activity of the thread, but the background execution of a single thread, so the user experience is better.
The latter can be reused by other applications, such as weather forecasting services, and other applications do not need to write such a service and invoke what is already available.
Write a sample local service that does not need to interact with the activity
Local service writing is relatively straightforward. First, create a service class that inherits the Android service class. Here is a Count service class, each second for the counter plus one. Inside the service class, a thread is also created to implement the above business logic in the background.
Service Code:
Import Android.app.Service;
Import android.content.Intent;
Import Android.os.IBinder;
Import Android.util.Log; public class Countservice extends Service {private Boolean threaddisable; private int count; @Override public IBinder onb IND (Intent Intent) {return null;} @Override public void OnCreate () {super.oncreate (); New Thread (New Runnable () {Publi
c void Run () {while (!threaddisable) {try {thread.sleep (1000);} catch (Interruptedexception e) {} count++; System.out.println ("Countservice count is" + count);}}).
Start ();
@Override public void OnDestroy () {Super.ondestroy (); this.threaddisable = true;
LOG.V ("Countservice", "on Destroy");} Registers the service in the profile androidmanifest.xml <service android:name= "Countservice"/> to start and close the Local service import in the activity
android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle; public class Localservicedemoactivity extends activity {@Override public void onCreate (Bundle savedinstancestate) {Super . OnCreate (SavedinstancEstate);
Setcontentview (R.layout.main);
This.startservice (This, Countservice.class) (new Intent); @Override protected void OnDestroy () {Super.ondestroy (); This.stopservice (New Intent (this, countservice.class));}
Examples of writing local service and activity interactions
The example above is to start the shutdown service through StartService and StopService. Applies to situations where there is no invocation of interaction between the service and the activity. If you need to pass parameters or method calls between. You need to use the bind and Unbind methods.
The practice is that the service class needs to add interfaces, such as Icountservice, and the service class needs an internal class, which makes it easy to access the wrapper data for the external class, which needs to inherit the binder class and implement the Icountservice interface. Also, to realize the service
Onbind method, you cannot return only one null.
Newly established Interface code:
Public interface Icountservice {public abstract int getcount ();}
Countservice code: Import Android.app.Service;
Import android.content.Intent;
Import Android.os.Binder;
Import Android.os.IBinder;
Import Android.util.Log; public class Countservice extends Service implements Icountservice {private Boolean threaddisable; private int count; pri
vate Servicebinder servicebinder = new Servicebinder ();
public class Servicebinder extends Binder implements Icountservice {//@Override public int GetCount () {return count;}
@Override public IBinder onbind (Intent Intent) {return servicebinder;} @Override public void OnCreate () {super.oncreate (), New Thread (new Runnable () {//@Override public void Run () {while!
threaddisable) {try {thread.sleep (1000);} catch (Interruptedexception e) {} count++; System.out.println ("Countservice count is" + count);}}).
Start ();
@Override public void OnDestroy () {Super.ondestroy (); this.threaddisable = true; LOG.V ("Countservice", "on Destroy ");} @Override public int GetCount () {return count;}}
The registration of the service also changes, androidmanifest.xml file:
<service android:name= "Countservice" > <intent-filter> <action android:name= "Com.phone.jiao" Huservice. Countservice "/> </intent-filter> </service> acitity Code no longer starts the shutdown service through Startserivce and StopService, in addition, the need to pass Ser
Viceconnection internal class implementations to connect service and activity.
Import android.app.Activity;
Import Android.content.ComponentName;
Import android.content.Intent;
Import android.content.ServiceConnection;
Import Android.os.Bundle;
Import Android.os.IBinder; public class Localservicedemoactivity extends activity {private serviceconnection serviceconnection = new Serviceconnect Ion () {//@Override public void onserviceconnected (componentname name, IBinder service) {Countservice = (icountservice)
Service
System.out.println ("Countservice on serivce connected, Count is" + countservice.getcount ());}
@Override public void onservicedisconnected (componentname name) {countservice = null;}};
Private Icountservice Countservice; /** called when the ACTIVity is the created. * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.main);
This.bindservice (New Intent ("Com.phone.jiaohuservice.CountService"), This.serviceconnection, bind_auto_create); @Override protected void OnDestroy () {this.unbindservice (serviceconnection); Super.ondestroy ();//Note successively}}
Writing a remote service that delivers basic data
The above example can be extended to allow other applications to reuse the service. Such a service is called a remote service, which is actually interprocess communication (RPC).
It is necessary to use the Android Interface Description Language (AIDL) to define the interface of the remote service, rather than the simple Java interface described above. The extension is aidl rather than Java. The icountserivde.aidl,eclipse will automatically generate the relevant Java files by using the Icountservice changes above.
Remote code:
Icountservice.aidl
Package com.phone.remoteservice.aidl;
Interface Icountservice {
int getcount ();
Countservice.java
import com.phone.remoteservice.aidl.ICountService; import Android.app.Service;
Import android.content.Intent;
Import Android.os.IBinder;
Import android.os.RemoteException;
Import Android.util.Log; public class Countservice extends Service {private Boolean threaddisable; private int count; private icountservice.stub S
Ervicebinder = new Icountservice.stub () {//@Override public int GetCount () throws RemoteException {return count;}};
@Override public IBinder onbind (Intent Intent) {return servicebinder;} @Override public void OnCreate () {super.oncreate (), New Thread (new Runnable () {//@Override public void Run () {while!
threaddisable) {try {thread.sleep (1000);} catch (Interruptedexception e) {} count++;
LOG.I ("AA", "---" + count + "---");
}}). Start ();
}//@Override public void OnDestroy () {Super.ondestroy (); this.threaddisable = true; LOG.V ("Countservice", "on Destroy");}
configuration file Androidmanifest.xml
<service android:name= ". Countservice ">
<intent-filter>
<action android:name=" Com.phone.remoteservice.CountService " >
</intent-filter>
</service>
Local code:
Copy Remote code GEN:COM.PHONE.REMOTESERVICE.AIDL package name and internally generated Icountservice.java file to local, note that the package name does not change, the Java file name does not change.
Test code
Import Com.phone.remoteservice.aidl.ICountService;
Import Android.os.Bundle;
Import Android.os.IBinder;
Import android.os.RemoteException;
Import android.app.Activity;
Import Android.content.ComponentName;
Import android.content.Intent;
Import android.content.ServiceConnection;
Import Android.view.Menu; public class Remoteservicetest extends activity {private Icountservice Countservice; private Boolean srevicedisable;/** Called the activity is the created. * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.main);
Bindservice (New Intent ("Com.phone.remoteservice.CountService"), This.serviceconnection, bind_auto_create);
} @Override protected void OnDestroy () {this.unbindservice (serviceconnection);
Srevicedisable = true; Super.ondestroy (); Note successively} private serviceconnection serviceconnection = new Serviceconnection () {public void onserviceconnected (Compone Ntname name, IBinder service) {Countservice = ICountService.Stub.asInterface (service); New Thread (New Runnable () {//@Override public void Run () {while!
srevicedisable) {try {System.out. println ("Countservice on Serivce connected, the count is" + countservice.getcount ()); catch (RemoteException e) {e.printstacktrace ();} try {thread.sleep (1000);} catch (Interruptedexception e) {}}})
. Start ();
public void onservicedisconnected (componentname name) {countservice = null;
}
}; }
There is little difference in the use of services in an activity, which only requires the remoteexception exception to be caught when the method that calls the remote service in Serviceconnection.
This allows you to interact with your defined services in a way that uses remote services in the same application. If another application uses remote services, it is necessary to replicate the Aidl file above and the corresponding package to the application, as are other invocations.
Writing a remote service that delivers complex data types
Remote services often do not simply pass Java basic data types. There are some restrictions and regulations that need to be noted about Android:
1. Android supports string and charsequence
2. If you need to use other Aidl interface types in Aidl, import is required, even under the same package structure;
3. Android allows you to pass a class that implements the Parcelable interface, requiring import;
4. Android supports the collection interface type list and map, but there are some limitations, elements must be basic or above three situations, do not need to import the collection interface class, but need to import the type of elements involved;
5. Non-basic data types, also not string and charsequence types, require directional instructions, including in, out, and inout,in representations set by the client, out representation by the server side, and InOut both.
This changes the int data returned in the previous example to a complex data type:
Import Android.os.Parcel;
Import android.os.Parcelable;
public class Countbean implements parcelable {public
static final Parcelable.creator < Countbean > Creator = NE W Creator < Countbean > () {
@Override public
countbean createfromparcel (Parcel source) {
Countbean bea n = new Countbean ();
Bean.count = Source.readint ();
return bean;
@Override public
countbean[] NewArray (int size) {return
new countbean[size];
}
;
public int count;
@Override public
void Writetoparcel (Parcel dest, int flags) {
Dest.writeint (this. count);
}
@Override public
int describecontents () {return
0;
}
}
The above is a small series for you to bring the service activity three kinds of interactive way (detailed) of the whole content, hope to help you, a lot of support cloud Habitat Community ~