Android development documentation translation-Services

Source: Internet
Author: User

Android development documentation translation-Services

Service is an application component that can run in the background for a long time without interacting with users. Other components can enable the service. After the service is enabled, the user can switch to another application in time. In addition, components can be bound to the service for interaction, and cross-process interaction (Android IPC Mechanism) is implemented in a timely manner ). Network Operations, playing music, performing file I/O operations, or interacting with content providers can all be performed through services in the background.

Service:

Started
By calling startService (), you can start a service. Once started, the service can run independently in the background, even if the started component is destroyed. Generally, the started service is used to perform a single operation without returning a value. For example, download an object on the network. After the operation is completed, the service should end on its own.

Bound
By calling bindService (), you can bind a service. A Bound service generally provides an interface for interacting with components, sending requests, obtaining results, and even performing inter-process interactions (IPC ). The lifecycle of the bound service is the same as that of the bound component. Although multiple components can be bound to one service at the same time, after all these components are unbound, the service will be destroyed.

Although the two forms of service are generally described separately in this document, you can enable and bind the service at the same time. You only need to override two callbacks-onStartCommand and onBind at the same time.
No matter which method you use to start the service (or both), you can use Intent to operate the service, just like operating the Activity. However, if you do not want other applications to use your service, you can declare the service as private in the manifest file. For details, seeService Statement in the configuration file.

Basic Introduction
To use a service, you must inherit the Service class or its subclass. You need to override some callback methods and perform some key operations in these methods. Below are some important lifecycle callback:

OnStartCommand ()
The system will call this function after you call startService. Once this method is executed, the service is started and runs independently in the background. If you implement this method, you must call stopSelf () or stopService () at the right time to stop the service. (If you only provide binding interfaces, you do not need to implement this method)

OnBind ()
When other components bindService () is bound to a service, the system calls the onBind () function. You need to provide a class that implements the IBinder interface in this method for the client to use. This method must be overwritten. If you do not want your service to provide the binding function, you can directly return null.

The Android system forcibly stops the service when the memory is low. if the service is bound to an activity with a focus, the risk of being killed is reduced; if a service is declared as a front-end service, it will hardly be killed. Otherwise, if the service is enabled for a long time, the priority of the service in the system will be lower over time, and the risk of being killed will be higher. If your service is started, you should consider the situation where it is killed by the system. If the system kill a service, the system will restart it when the resources are loose (this policy is determined based on your onStartCommand () return value ).

Service Statement in the configuration file
Like activity, you need to declare service in the list file.


  
     ...        
   
          ...  
   
  

You can declare some other attributes in the service node. These attributes are optional. Only the android: name attribute is required. This attribute is used to describe a unique service class name. You should ensure that this class name is not modified.
To ensure the security of your application, you should use explicit intent to start or bind the service, and do not declare intent-filters in the service.
In addition, you can set the android: exported attribute to false to ensure that your service can only be used in your own applications. This effectively prevents other applications from using your service, even with explicit intent.

Create a service in Startup Mode
You can start the service through startService (). You can listen to the onStartCommand () callback.
After a service is started, it has an independent life cycle and runs independently in the background, even if its components are destroyed. In this case, you need to call stopSelf () at the right time to end it or call stopServie () to end it.
The Intent passed when startService () is called will be received during the onStartCommand () callback.

Note: by default, the service runs in the application process that declares the service and runs in the main thread. Therefore, if your service is executing intensive or congested operations, it may cause ANR. To avoid this situation, you need to start a new thread.

Generally, you can inherit the IntentService class to accelerate your development.

Inherit IntentService class
Because most services do not need to process concurrent requests, You can inherit the IntentService class to accelerate your development.

IntentService has the following features:

1. A working thread is created to execute the intent passed in onStartCommand (), which is separated from the main thread.
2. A work queue is created to execute intent in sequence, so you do not need to consider multithreading.
3. When all tasks are completed, stopSelf () is automatically called ().
4. Provides the onBind () default implementation (return null)
5. Provides the default Implementation of onStartCommand (), sends tasks to the task queue, and calls back onHandleIntent ()

These features allow you to complete client tasks by implementing onHandleIntent () (you also need to provide a simple constructor)
The following is an implementation of IntentService:

public class HelloIntentService extends IntentService {  /**   * A constructor is required, and must call the super IntentService(String)   * constructor with a name for the worker thread.   */  public HelloIntentService() {      super("HelloIntentService");  }  /**   * The IntentService calls this method from the default worker thread with   * the intent that started the service. When this method returns, IntentService   * stops the service, as appropriate.   */  @Override  protected void onHandleIntent(Intent intent) {      // Normally we would do some work here, like download a file.      // For our sample, we just sleep for 5 seconds.      try {          Thread.sleep(5000);      } catch (InterruptedException e) {          // Restore interrupt status.          Thread.currentThread().interrupt();      }  }}

In comparison, If you inherit from the service and want to implement the same function, you need to write the code:

public class HelloService extends Service {  private Looper mServiceLooper;  private ServiceHandler mServiceHandler;  // Handler that receives messages from the thread  private final class ServiceHandler extends Handler {      public ServiceHandler(Looper looper) {          super(looper);      }      @Override      public void handleMessage(Message msg) {          // Normally we would do some work here, like download a file.          // For our sample, we just sleep for 5 seconds.          try {              Thread.sleep(5000);          } catch (InterruptedException e) {              // Restore interrupt status.              Thread.currentThread().interrupt();          }          // Stop the service using the startId, so that we don't stop          // the service in the middle of handling another job          stopSelf(msg.arg1);      }  }  @Override  public void onCreate() {    // Start up the thread running the service.  Note that we create a    // separate thread because the service normally runs in the process's    // main thread, which we don't want to block.  We also make it    // background priority so CPU-intensive work will not disrupt our UI.    HandlerThread thread = new HandlerThread("ServiceStartArguments",            Process.THREAD_PRIORITY_BACKGROUND);    thread.start();    // Get the HandlerThread's Looper and use it for our Handler    mServiceLooper = thread.getLooper();    mServiceHandler = new ServiceHandler(mServiceLooper);  }  @Override  public int onStartCommand(Intent intent, int flags, int startId) {      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();      // For each start request, send a message to start a job and deliver the      // start ID so we know which request we're stopping when we finish the job      Message msg = mServiceHandler.obtainMessage();      msg.arg1 = startId;      mServiceHandler.sendMessage(msg);      // If we get killed, after returning from here, restart      return START_STICKY;  }  @Override  public IBinder onBind(Intent intent) {      // We don't provide binding, so return null      return null;  }  @Override  public void onDestroy() {    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();  }}

Is it true that you are tired and don't like it.
However, if you want to implement concurrent operations, that is, to perform the next request before the execution of the previous request is complete, it is necessary to directly inherit the service.

Note that the onStartCommand () method must return an integer variable. This integer variable is used to specify how the system returns results after killing the service. The return values are as follows:

START_NOT_STICKY
The system will not re-create the service after killing the service, unless pending intents needs to be passed. This method is applicable when your program can simply restart the service that has not completed the task.

START_STICKY
If the system kills the service, it will restart the service and call onStartCommand (). However, it will not resend the previous intent, but return a null intent (unless it is a pending intents .) This mode is suitable for music players that do not need to execute commands, but need to run independently and wait for tasks.

START_REDELIVER_INTENT
If the system kills the service, the service will be restarted and the onStartCommand () will be dropped, and the previous intent will be passed. This mode is suitable for services that need to be returned immediately, such as downloading files.

Start service by binding
For more information, see the Android development documentation-Bound Services.

Send notifications to users
Once the service is running, you can use Toast events or Status Bar events to notify users of certain events.
Toast configurications is a message that appears on the current window surface in a short time. Status Bar Notifications is a notification Bar that provides icons and messages. You can click to execute an action (for example, enable an activity)

Front-End Service
The front-end Service is usually used to execute some operations that need to be realized by the user. Therefore, the system will not kill the service when the system is in a low memory status. The front-end Service must provide a notification on the status bar, which will not disappear until the service is stopped or removed from the front-end.
For example, the music player Service should be set as a service running on the front-end, because the user should always be aware of this operation. The status bar should display the currently playing songs, and the activity that can interact with users should be displayed after the current click.
Call the startForeground () function to run your service on the frontend. Example:

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),        System.currentTimeMillis());Intent notificationIntent = new Intent(this, ExampleActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);notification.setLatestEventInfo(this, getText(R.string.notification_title),        getText(R.string.notification_message), pendingIntent);startForeground(ONGOING_NOTIFICATION_ID, notification);

Manage Service Lifecycle
Service lifecycle is much simpler than Activity. But you need to pay more attention, because the service is usually running in the background.

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.