Services Learning (1)

Source: Internet
Author: User

If you need to run for a long time, such as playing music, connecting to the server for a long time, even if the current activity on the screen still needs to run, use the service mode. The service will be triggered through API or through an IPC (interprocess communication) connection request. The Service will run until it is disabled, or the system will shut down when the memory is insufficient. In general, in order to save power, the service should be optimized to reduce CPU consumption and a large amount of network communication. Services can be used in the following scenarios:

1. After you leave the activity, you still need to continue working, such as downloading files from the network and playing music.
2. Continuous work is required no matter whether the activity appears (reproduced) or leaves, such as online chat applications.
3. connect to the network service and use the service provided by a Remote API
4. Regularly triggered services, such as cron in Linux.

There are two main forms of services:

(1) started: startedservice () is called to start. It must be closed explicitly. Generally, the service is only responsible for one operation and does not return results to the caller. For example, download files from the network. After the operation is complete, the service should be automatically exited.

(2) bound: bindservice () is called by other components and bound to this service.

Service basics:

Generally, you can create a service by inheriting the service class and override some important methods to manage the service lifecycle or bind the service to other components. The following methods are used:

Onstartcommand (): when other components (such as an activity) Call startservice (), the system calls onstartcommand (). After this method is called, the service is enabled in the background. to end the service, you must call stopself () or other components to call stopservice ().

Onbind (): when other components call bindservice () to bind this service, the system calls onbind (). This method must contain an interface that returns ibinder for communication between the service and the client.

Oncreate (): called when the service is created for the first time before onstartcommand () and onbind.

Ondestory (): called when service () is disabled, resources are released, and related threads are ended.

Declare service in the manifest file:

The <service> element is a subitem of the <Application> element.

 

<manifest ... >  ...  <application ... >      <service android:name=".ExampleService" />      ...  </application></manifest>

 

Create a started service

When other components call startservice () to start the service, the system then calls onstartcommand () of the service (). Once the service is started, you must call stopself () or other components call stopservice () to end it.

Other components can pass an intent carrying data to the service through startservice (), and the service side receives the passed intent in onstartcommand.

Generally, you can create a service by inheriting the following two classes:

Service: by default, this Service uses the main thread of the program. It is best to create a new thread to handle service work.

Intentservice: it is a subclass of a Service. It uses a working thread to process requests, but can only process one request at a time. It cannot process multiple requests at a time. It needs to implement the onhandleintent () method to receive intent and process client requests.

Create by inheriting intentservice:

The workflow of intentservice is as follows:

    • Create a worker thread independent of the main thread and execute the intent passed to onstartcommand.
    • Create a work queue and pass an intent to onhandleintent () each time ().
    • After all requests are processed, the service automatically exits and does not need to explicitly call stopself ().
    • The onbind () provided by default returns NULL.
    • Onstartcommand () sends intent to a work queue and then to onhandleintent () for processing.

Note: The onhandleintent () method and service constructor must be implemented.

Example of inheriting intentservice:

 

public class HelloIntentService extends IntentService {  /**   * 需要一个构造器, 必须调用父类构造器 IntentService(String)   * 并传入要创建的工作线程的名字   */  public HelloIntentService() {      super("HelloIntentService");  }  /**   *  IntentService在工作线程中调用这个方法   *  此方法返回后, IntentService关闭Service   */  @Override  protected void onHandleIntent(Intent intent) {      //一般情况下,我们在此做一些操作,比如下载一个文件。      //对于这个例子,我们只是让线程睡眠5s      long endTime = System.currentTimeMillis() + 5*1000;      while (System.currentTimeMillis() < endTime) {          synchronized (this) {              try {                  wait(endTime - System.currentTimeMillis());              } catch (Exception e) {              }          }      }  }}

 

If you need to override other methods, such as oncreate (), onstartcommand (), or ondestroy (), you must first call the parent class implementation so that intentservice can correctly process the life cycle of the worker thread.

For example, onstartcommand () must return the default implementation (it indicates how to pass intent to onhandleintent ()).

@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();    return super.onStartCommand(intent,flags,startId);}

Except onhandleintent (), the only method that does not need to call the parent class is onbind (), but the service must implement it only when it is allowed to be bound.

***

 

Services Learning (1)

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.