Android-based test summary of Android Basics (iv)

Source: Internet
Author: User

Android top-up Test summary Android basic service (iv)

Android Basics in the previous Chapter broadcast receiver (iii) we talked about broadcast receiver basics. This section focuses on service-related basics, and service is often used in our development process.

If you have any questions during the reading process, please do not hesitate to contact us. Please specify Fuchenxuan de Blog if you need to reprint
This chapter is the "Android beauty from 0 to the best of the road" Android basic service summarizes the Android developer interview more common service-related interview questions. Hope for the vast number of Android developers, helpful.

    • Android face test summary Android basic service four
      • Service common face question
      • Intentservice Applicable Scenarios

Service common face question
    1. is the service executed in the main thread, and does the service have time-consuming operations?

      By default, if the process that Servic is running is not displayed, Service and activity are running in the main thread (UI main thread) of the process in which the current app resides.
      Service cannot perform time-consuming operations (network requests, copy databases, large files)
      In special cases, you can configure the process in which the service executes in the manifest file so that the service executes in another process

<service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote" ></service>
  1. How does the activity bind to the service, and how does it initiate its own service in the activity?
    Activity is bound to the service via Bindservice (Intent service, serviceconnection conn, int flags), and when the binding succeeds, the service passes the proxy object through a callback to Conn, so we get the service proxy object provided by the service.
    The Service can be started in Activity through the StartService and Bindservice methods. In general, if you want to get service objects then you will definitely need to pass the Bindservice () method, such as music player, third party payment, etc. You can use the StartService () method only to open a background task.

  2. life cycle of Service
    The Service has binding and unbound modes, as well as a mixed use of the two modes. Different ways of using life cycle methods are also different.
    Unbound mode: When the first call to StartService executes the method followed by OnCreate (), Onstartcommand (), and the Ondestory method is called when the Service is closed.
    Binding mode: The first time Bindservice (), the execution of the method for OnCreate (), Onbind () Unbind the time will be executed Onunbind (), Ondestory ().
    The two life cycles above are in relatively simple patterns. We must also note in the development process that the service instance will only have one, that is, if the service that is currently being started is already present, then the service will not be created again, and the OnCreate () method will not be called.
    A Service can be bound by multiple customers, and only all of the bound objects are executed
    The service is destroyed after the Onbind () method, but if a client executes the OnStart () method, then this time if all the BIND clients have executed the UnBind () the service will not be destroyed.

    The life cycle diagram of the Service is shown below to help you remember.

  3. What are the advantages of intentservice?

    We usually only use the service, perhaps Intentservice for most of the students is the first time to hear. Then look at the following introduction to believe that you are no longer unfamiliar. If you still don't understand, then you can honestly say that you haven't used or understood the interview. Not all the questions need to be answered.
    I. Introduction ofIntentservice
    Intentservice is a subclass of service that adds additional functionality to the normal service.
    First look at the Service itself with two questions:
    The service does not start a separate process specifically, the service is in the same
    Approached
    Service is not a new thread, so it should not be processed directly in the service with time-consuming
    Task
    Ii. characteristics ofIntentservice
    A separate worker thread is created to handle all Intent requests;
    A separate worker thread is created to handle the code implemented by the Onhandleintent () method, without
    Deal with multithreading problems;
    After all request processing is complete, Intentservice automatically stops without calling the Stopself () method
    Stop Service;
    Provides a default implementation for the Service's Onbind () and returns null;
    Provides a default implementation for the Service's onstartcommand, adding the request Intent to the queue
    In
    Using Intentservice
    I have written a Intentservice use example for reference. In this example, a
    Mainactivity a myintentservice, these two classes are the four components of course need to be registered in the manifest file. This gives only the core code:

    Mainactivity.java: Public void Click(View view) {Intent Intent =NewIntent ( This, Myintentservice.class); Intent.putextra ("Start","Myintentservice"); StartService (intent);} Myintentservice.java Public  class myintentservice extends intentservice { PrivateString ex ="";PrivateHandler Mhandler =NewHandler () { Public void Handlemessage(Android.os.Message msg) {Toast.maketext (Myintentservice). This,"-E"+ Ex,toast.length_long). Show (); }}; Public Myintentservice(){Super("Myintentservice");}@Override Public int Onstartcommand(Intent Intent,intFlagsintStartid) {ex = Intent.getstringextra ("Start");return Super. Onstartcommand (Intent, flags, Startid);}@Overrideprotected void onhandleintent(Intent Intent) {/*** Simulation Execution time-consuming task * This method is executed in a sub-thread, so the handler must be used to communicate with the main thread * /Try{Thread.Sleep ( +);}Catch(Interruptedexception e) {E.printstacktrace ();} Mhandler.sendemptymessage (0);Try{Thread.Sleep ( +);}Catch(Interruptedexception e)  {E.printstacktrace (); }} }
  4. What is the relationship between Activity, Intent, Service?

    They are all the most frequently used classes in Android development. Activity and Service are among the four components of Android. Both of them are subclasses of the subclass of the Context class, so they can be considered contextwrapper. But the two brothers each have their own skills, Activity is responsible for the user interface display and interaction, Service responsible for background task processing. Data can be passed through Intent between Activity and Service, so Intent can be thought of as a messenger of communication.

  5. Service and Activity on the same thread?
    For the same app, by default in the same thread, main thread (UI thread).

  6. can you play toast in the Service?
    OK. One of the conditions of the toast is that there is a context, and the service itself is a subclass of the context, so it is perfectly possible to play toast in the service. For example, we can play a toast notification user after completing the download task in the Service.

  7. what is the Service and describes its life cycle. What are the service startup methods, what is the difference, and how do I deactivate the service?
    In the Service life cycle, the callback method is less than the Activity, only OnCreate, OnStart, OnDestroy,
    Onbind and Onunbind.
    There are usually two ways to start a service, and their impact on the service life cycle is different.

    1. by StartService
      The Service goes through OnCreate to OnStart and then runs, StopService
      Call the OnDestroy method.
      If the caller exits directly without calling StopService, the Service will always
      Run in the background.
    2. The
    3. through Bindservice
      Service runs onCreate and then calls Onbind, at which point the caller and the service are bound together. When the caller exits, Srevice calls the Onunbind->ondestroyed method.
      The so-called binding together is a total survival. The caller can also stop the service by calling the Unbindservice method, when Srevice calls the Onunbind->ondestroyed method. It is important to note that if these methods are intertwined, what will happen? One principle is that the OnCreate method of Service will only be called once, that is, how many times you startservice and Bindservice,service are created only once.
      If bind is first, then start will run the Service's OnStart method directly, if first start, then bind will run the Onbind method directly.
      If Bindservice is called during service run time, the service will not call the OnDestroy method, and the service will stop StopService, only call Unbindservice , the service is destroyed
      if a service calls StartService multiple times after StartService is start, the service calls the OnStart method multiple times. If you call StopService multiple times, the service will only call the Ondestroyed method once.
      If a service calls Bindservice multiple times after Bindservice is start, the service will only call the Onbind method once.
      Calling Unbindservice multiple times throws an exception.
  8. is the service lifecycle Method Onstartconmand () possible to perform network operations? How do I perform network operations in the service?
    Network operations can be performed directly in the Service, and network operations can be performed in the Onstartcommand () method

  9. How do I increase service priority?
    The Android system has its own set of methods for memory management, in order to guarantee the orderly and stable operation of the system,
    The internal system is automatically assigned, and the program's memory is used. When the system feels that the current resources are very limited,
    To ensure that some high-priority programs can run, they kill some programs or services that they don't think are important to free up memory.
    This will ensure that programs that are really useful to the user are still running again. If your Service is in this situation, you will probably be killed first.
    But if you increase the priority of the Service, you can keep him for a little while,
    We can use Setforeground (true) to set the priority of the Service.
    Why the foreground? The Service that is started by default is the Activity that is marked as background and is currently running
    is generally marked as foreground, which means that you set the Service to foreground so that he and the running
    Activity-like priorities have been improved a certain amount. When this doesn't guarantee you the Service.
    Never be killed, just raise his priority.

  10. How does the
  11. service execute periodically?
    When starting a service for background tasks, it is common practice to start a thread and then use the Sleep method to control scheduled tasks, such as polling operations, message pushes. This is easily recovered by the system.
    Service Recycling is out of our control, but we can control the service restart activity. You can return a parameter in the service's Onstartcommand
    method to control the restart Activity
    using Alarmmanager, Alarmmanager will issue a broadcast periodically, depending on how Alarmmanager works. Then register this broadcast in your project, rewrite the OnReceive method, start a service in this method, and then perform the network access operation inside the service, push when you get the new message. At the same time set up a alarmmanager for the next polling, when the poll ends can stopself end change service. This will not affect the next polling even if this polling fails. This will ensure that the push task does not break the

  12. the Onstartcommand method of the Service has several return values? What do the delegates mean?
    There are four return values, with different values representing the following meanings:
    Start_sticky: If the service process is killed, the status of the reserved service is the start state, but the delivery intent object is not preserved. The system then tries to recreate the service, and since the service status is started, the Onstartcommand (Intent,int,int) method must be called after the services are created. If no startup commands are passed to the service during this time, then the parameter Intent will be null.
    start_not_sticky:"non-sticky". When this return value is used, the service is not automatically restarted if the service is killed by an exception after Onstartcommand is executed.
    start_redeliver_intent: retransmission INTENT. With this return value, if the service is killed by an exception after Onstartcommand is executed, the service is automatically restarted and the value of Intent is passed in.
    **start_sticky_compatibility:**start_sticky compatible version, but does not guarantee that the service will be restarted after kill.

  13. Under What circumstances will the Service's Onrebind (Intent) method be executed?
    If the Onunbind () method returns True, execution is not performed.

  14. What are the ways that Activity invokes the methods in the Service?
    Binder:
    Implemented in the form of binder interfaces, the activity will get the service's on in the Onserviceconnected () callback method of the Serviceconnection class when the activity binding service succeeds The Bind () method return comes over the Binder's subclass and then invokes the method through the object.
    Aidl:
    Aidl is more suitable for scenarios where the client and the server are not in the same application.

    Messenger:
    It refers to a handler object so that others can send a message to it (using the Mmessenger.send (Message msg) method). This class allows message-based communication across processes (that is, two processes can communicate via message), and a messenger is created using handler on the server side, and the client can communicate with the server by holding the messenger. A messeger cannot be sent in both directions, and two can be sent in two directions.

Here is a superficial picture to help you understand.

**BroadCastReceiver**
    1. How does the Service send a Message to Activity?
      Service and Activity must use the Messenger mechanism if they want to send a Message to each other.

      Intentservice Applicable Scenarios
      • Intentservice built-in is handlerthread as an asynchronous thread, each task assigned to Intentservice will be executed in a queue, one by one, once a task in the queue takes too long to execute, it will cause subsequent tasks to be deferred.
      • A running Intentservice program is less likely to be killed by the system than a purely daemon, and the priority of the program is between the foreground program and the pure daemon.

This chapter summarizes the basics of service-related points. We hope to help you.

The level is limited, if have errors and omissions, welcome to correct, criticize, if need reprint, please indicate source –http://blog.csdn.net/vfush, thank you!

Android-based test summary of Android Basics (iv)

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.