What is Service?

A Service is often referred to as a “background Service.”

A Service is an application component that can run operations in the background for a long time without a user interface. A service can be started by another application component (such as an Activity), and once started, it runs in the background, even if the component that started the service is destroyed.

In addition, components can be bound to services to interact with or even perform interprocess communication (IPC).

The term “background” refers to the foreground, which specifically means that the operation of the Service itself does not depend on the user’s visible UI interface. Therefore, in terms of actual business requirements, the application scenarios of the Service should meet the following requirements:

  • 1. Does not rely on the user visible UI interface (of course, this is not absolute, for example, the foreground Service is used in conjunction with the Notification interface);

  • 2. It has long running characteristics.

2. Check whether services are executed in main threads and whether time-consuming operations can be performed in services.

  • By default, services and activities run in the main thread of the current app thread if the process is not specified.

  • 2. A service cannot perform time-consuming operations (network requests, database copy, large files) in a special case, you can configure the process of the service execution in the manifest file, so that the service execution in another process

    <service
    android:name="com.baidu.location.f"
    android:enabled="true"
    android:process=":remote" >
    </service>
    
    Copy the code

3. How to bind an Activity to a Service, and how to start its corresponding Service in an Activity?

  • An Activity is bound to a service by bindService(Intent Service, ServiceConnection Conn, int Flags). When the binding is successful, the Service passes the proxy object to Conn via a callback, and we get the Service proxy object provided by the Service.

  • You can start a Service in an Activity using the startService and bindService methods. In general, if you want to obtain Service objects, you must use bindService () method, such as music player, third-party payment, etc.

  • You can use the startService () method if you just want to start a background task.

5. The life cycle of a Service is also examined extensively

Services have bound and unbound modes, and a mixture of the two modes. The lifecycle approach is different for different uses.

Unbound die type

The first call to startService is onCreate(), onStartCommand(), and the onDestory method is called when the Service is closed.

Binding mode

The first bindService () executes onCreate() and onBind() executes onUnbind() and onDestory().

The above two life cycles are in relatively pure mode scenarios. We must also note that there is only one Service instance, which means that if the current Service to be started already exists, it will not be created again and the onCreate () method will not be called.

A Service can be bound by multiple clients. The Service will not be destroyed until all binding objects have performed onBind (), but if one client has performed onStart(), If all bind clients unBind(), the Service will not be destroyed.

All in one picture

InterService

As a veteran driver, if you haven’t heard of Interservice, you’re a bit of a screw-up

What is an IntentService? What are the advantages?

We usually just use Service, maybe IntentService

This is new to most of you. So read the following introduction I believe you are no longer strange. If you still don’t know then be honest in the interview that you haven’t used it or don’t know, etc. Not all the questions need to be answered.

What is an IntentService?

IntentService is a subclass of Service that adds additional functionality over regular Service.

Two questions:

A Service does not start a separate process. A Service is in the same process as its application.

A Service is not dedicated to a new thread, so time-consuming tasks should not be handled directly within the Service;

The characteristics of the IntentService

  • A separate worker thread is created to handle all Intent requests;

  • A separate worker thread is created to handle the code that implements the onHandleIntent() method without having to deal with multithreading;

  • IntentService stops automatically after all requests are processed, without calling stopSelf() to stop the Service;

  • Provide a default implementation for Service onBind(), which returns NULL;

  • Provide a default implementation for Service onStartCommand that adds the Intent to the queue.

public class MyIntentService extends IntentService {
    private String ex = "";
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(MyIntentService.this, "-e "+ ex, Toast.LENGTH_LONG).show(); }}; publicMyIntentService(){
        super("MyIntentService");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        ex = intent.getStringExtra("start");
        returnsuper.onStartCommand(intent, flags, startId); } @override protected void onHandleIntent(Intent Intent) {/** * */ try {thread.sleep (1000); } catch (InterruptedException e) { e.printStackTrace(); } mHandler.sendEmptyMessage(0); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code

5, Describe the relationship between an Activity and an Intent and a Service

  • They are among the most frequently used classes in Android development.

  • Activity and Service are one of the four components of Android. They’re both subclasses of ContextWrapper, so they’re kind of brothers.

  • However, the two brothers have their own skills. Activity handles the display and interaction of the user interface, while Service handles the processing of background tasks. An Activity and a Service can pass data through an Intent,

  • So you can think of intEnts as messengers.

6. Are the Service and Activity on the same thread

The default for the same app is to be in the same Thread, the main Thread.

Can you play toast in the Service

You can. One of the conditions for toasting is that there must be a Context, and Service itself is a subclass of Context, so toasting in a Service is perfectly acceptable. For example, when we complete the download task in Service, we can play a toast to notify the user.

Can the service lifecycle method onstartConmand() perform network operations? How do I perform network operations in a Service?

You can perform network operations directly in the Service and in the onStartCommand() method

What is the difference between starting a Service and stopping it?

During the life cycle of a Service, fewer methods are called back than activities, only onCreate, onStart, onDestroy, onBind, and onUnbind.

There are generally two ways to start a Service, and they have different effects on the Service life cycle.

  • 1. StartService the Service goes through onCreate to onStart and is running. OnDestroy is called while stopService is running.

    If the caller simply exits without calling stopService, the Service will always run in the background.

  • 2. With bindService the Service runs onCreate and then onBind, which binds the caller to the Service. Srevice calls onUnbind->onDestroyed when the caller exits.

    The so-called bound together to live or die together. The caller can also stop the service by calling the unbindService method, in which case Srevice calls onUnbind->onDestroyed.

What is important to note is what happens if these methods are interwoven together?

One principle is that the onCreate method of a Service is called only once, that is, no matter how many times you call startService and bindService, the Service is created only once.

If you bind first, run the onStart method of the Service directly when you start. If you bind first, run the onBind method directly when you bind.

If bindService is called and stopService is called, the service will not call onDestroy and will not stop. You can only call UnbindService and the service will be destroyed

If a service is started by startService and startService is called several times, the service calls onStart multiple times. If stopService is called multiple times, the Service will only call onDestroyed once.

If a service calls bindService multiple times after being started by bindService, the service will only call onBind once. Calling unbindService more than once throws an exception.

More articles

NDK project actual combat – high imitation 360 mobile phone assistant uninstall monitoring

Advanced UI special like live like effect – a beautiful cool like animation

Believe in yourself, there is nothing impossible, only unexpected.