What is a Service?
Service is an application component in the android system. It is similar to the Activity level, but it does not have a graphical interface and cannot run on its own. It can only run on the background, it can also interact with other components, such as updating ContentProvider, Intent, and system notifications. There are two startup Methods: context. startService () and context. bindService (). Services are usually used to process some time-consuming operations.
Service Compilation
Create a class (FirstService here) that inherits android. app. Service and overwrites the following methods:
OnBind (Intent intent) Return the communication channel to the service.
OnCreate () Called by the system when the service is first created.
OnStartCommand (Intent intent, int flags, int startId) Called by the system every time a client explicitly starts the service by calling startService (Intent ), providing the arguments it supplied and a unique integer token representing the start request.
OnDestroy () Called by the system to operate y a Service that it is no longer used and is being removed.
Add service configuration in AndroidManifest. xml file Copy codeThe Code is as follows: <service android: name = ". FirstService"> </service>
Writing click events for enabling and stopping services in an ActivityCopy codeThe Code is as follows: class StartServiceListener implements OnClickListener {
@ Override
Public void onClick (View v ){
Intent intent = new Intent ();
Intent. setClass (TestActivity. this, FirstService. class );
StartService (intent );
}
}
Class StopServiceListener implements OnClickListener {
@ Override
Public void onClick (View v ){
Intent intent = new Intent ();
Intent. setClass (TestActivity. this, FirstService. class );
StopService (intent );
}
}