Basic Programming Method for Android Service application components

Source: Internet
Author: User

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 );
}
}

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.