Local Service Development
Service Development:
1. Define a service. Note that the onbind function does not need to be rewritten and null is directly returned;
2. Rewrite the onstartcommand function to perform operations in the background. Generally, another thread is started to execute user work separately, and the code executed after the service is started is added here;
3. Rewrite the ondestroy function and add the code executed after the service is stopped;
4. Define a Thread class, such as serviceworker, and perform time-consuming processing in the run function;
Class serviceworker implements runnable
Client development:
1. Execute startservice where you want to connect to the service
5. Execute stopservice where the service needs to be disconnected
6. Rewrite the ondestroy function and add the code to be executed after exit. Generally, stop the service here;
Remote Service Development
Service Development:
1. Define the aidl file. You can add an interface in New-> interface and change the suffix to aidl;
Package com. Demo. Service;
Interface igradeservice {
String getgrade (INT result );
}
7. Compile the build project and generate the Java file of the corresponding interface under the gen directory;
8. Write a service class and add the service implementation class.
Public class gradeserviceimpl extends gradeservice. Stub
9. Rewrite the onbind function and return the service implementation class gradeserviceimpl;
Return new gradeserviceimpl ();
10. Add the following items to androidmanifest. XML in service:
<Service android: Name = "gradeservice">
<Intent-filter>
<Action Android: Name = "com. Demo. Service. igradeservice"/>
</Intent-filter>
</Service>
Client development:
1. Define an Interface Class in the class
Private igradeservice gradeservice = NULL;
11. Define a serviceconnection variable;
Private serviceconnection servconn = new serviceconnection (){
@ Override
Public void onservicedisconnected (componentname name ){
// Todo auto-generated method stub
Gradeservice = NULL;
}
@ Override
Public void onserviceconnected (componentname name, ibinder Service ){
// Todo auto-generated method stub
Gradeservice = igradeservice. stub. asinterface (service );
}
};
12. Add
Bindservice (new intent (igradeservice. Class. getname (), servconn, bind_auto_create );
13. Add
Unbindservice (servconn );
14. In the specific operation process, directly call the service function
Gradeservice. getgrade (integer. valueof (edtresult. gettext (). tostring (). intvalue ());