Service component of the four components of the Android

What is Service

Service (service) is a way to perform a long-running operations in the background without a user interface application components. Service starts by other application components (such as Activity), service once started will always run in the background, even if the component to start the service (Activity) have been destroyed will not be affected. In addition, the components can be bound to the service to interact with, and even perform interprocess communication (IPC). For example, the service can process network transactions, play music, perform file I / O or interaction with content providers, all of which can be carried out in the background, Service state is basically divided into two forms:

    Start state

When application components (such as Activity) by calling startService () to start the service, the service that is in the "on" state. Once activated, the service can run in the background indefinitely, even if the component to start the service have been destroyed will not be affected, unless manually call to stop the service, the service is usually started to perform a single operation, and will not return the results to the calling square.

    Binding status

When an application component is bound to the service by calling bindService (), the service that is in a "binding" status. Binding service provides a client - server interface, allowing components to interact with the service, send a request to obtain the results, or even the use of inter-process communication (IPC) across processes to perform these operations. Only when bound to another application components, binding service will run. Multiple components can bind simultaneously to the service, but after all unbind, namely the service will be destroyed.

Comparison of Activity and Service

Similarity

  • Are separate components Android
  • We have an independent life cycle
  • Context is a derived class, it is possible to call the Context class as defined getResources (), getContentResolver () method and the like
  • It has its own life cycle callback methods

difference

  • Activity run in the foreground with a graphical user interface, is responsible for interaction with the user; Service is usually run in the background, and does not require user interaction or have a graphical user interface.

Scenarios
If a program needs to render the component interface, or program to run when the user needs to interact with the user, need to use Activity, otherwise you should consider using the Service.

Service to create a background service

Background services can be divided into non-interactive services and interactive services. The difference is the way to start the service StartService()and bindService(). The latter will return Bindan object for Servicea method and processing results, and the former will not

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

/**
定义一个类继承Service即可
*/
public class FirstService extends Service {
    /**
     * Service子类必须实现的方法。该方法返回一个IBinder对象,应用程序可通过IBinder对象与Service组件通信
     * @param intent
     * @return
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("===================onBind FirstService=================");
        return null;
    }

    /**
     * 当Service上绑定的所有客户端都断开连接时会回调该方法
     * @param intent
     * @return
     */
    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("===================onUnbind FirstService=================");
        return super.onUnbind(intent);
    }

    /**
     * Service第一次被创建后回调该方法
     */
    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("===================onCreate FirstService=================");
    }

    /**
     * Service被关闭之前回调该方法
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("===================onDestroy FirstService=================");
    }

    /**
     * 该方法的早期版本是onStart(Intent intent, int startId),
     * 当客户端调用startService(Intent)方法启动Service时都会回调该方法
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("===================onStartCommand FirstService=================");
        return super.onStartCommand(intent, flags, startId);

    }
}


The above services registered into Manifest.xml

<service android:name="com.javayihao.demo.TestService">
            <!-- 配置intent-filter元素说明该Service可被哪些Intent启动,可选 -->
            <intent-filter>
                <!-- 为intent-filter配置action -->
                <action android:name="com.javayihao.demo.TEST_SERVICE" />
            </intent-filter>
        </service>

Starting and stopping Service 

The first

() Method starts by no correlation between startService Context Service, Service and visitors, can not communicate, exchange data between the Service and the visitors. Even if the visitor exits, Service is still running:

Features: Whenever Service will be created callback onCreate method, every time the callback method when activated onStartCommand Service. Repeatedly to start an existing Service component will no longer callback method onCreate, but each time you start the callback will onStartCommand method.

        Intent intentService = new Intent(this, FirstService.class);
        intentService.setAction("com.javayihao.demo.TEST_SERVICE");
        //启动Service
        startService(intentService);
        //停止Service
        //stopService(intentService);

The second

test service

public class TestService extends Service {
    //定义onBinder方法要返回的Binder对象
    private MyBinder binder = new MyBinder();
    // 通过继承Binder来实现IBinder类
    public class MyBinder extends Binder {
        public int getCount() {
            return 111;
        }
    }
    /**
     * service子类必须实现的方法。该方法返回一个IBinder对象,应用程序可通过IBinder对象与Service组件通信
     * @param intent
     * @return
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("===================onBind TestService=================");
        return binder;//返回一个对象
    }
    /**
     * 当Service上绑定的所有客户端都断开连接时会回调该方法
     * @param intent
     * @return
     */
    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("===================onUnbind TestService=================");
        return super.onUnbind(intent);
    }

    /**
     * Service第一次被创建后回调该方法.用于初始化服务,只会被调用一次
     */
    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("===================onCreate TestService=================");
    }

    /**
     * Service被关闭之前回调该方法
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("===================onDestroy TestService=================");
    }

    /**
     * 该方法的早期版本是onStart(Intent intent, int startId),
     * 当客户端调用startService(Intent)方法启动Service时都会回调该方法
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("===================onStartCommand TestService=================");
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 耗时操作
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }
}

 

 start up

public class MainActivity extends AppCompatActivity {
    private  ServiceConnection connection;
    //启动Service时返回的IBinder对象
    TestService.MyBinder binder;
    //绑定服务
    public void  bindTestService(){
        Intent intent = new Intent(this, TestService.class);
        if(connection==null){
            ServiceConnection connection =new ServiceConnection() {
                //当与服务连接调用
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    binder =  (TestService.MyBinder)service;
                    System.out.println("=============与TestService服务连接===========");
                }

                //当与服务断开调用
                @Override
                public void onServiceDisconnected(ComponentName name) {
                    System.out.println("============与TestService服务断开===============");
                }
            };
            //进行绑定
            bindService(intent,connection, Context.BIND_AUTO_CREATE);
        }else{
            System.out.println("============已经绑定");
        }
    }
    //解除绑定
    public void unbindTestService(){
        if(connection!=null){
            unbindService(connection);
            connection=null;
            System.out.println("============解除绑定==============");
        }else{
            System.out.println("============还没有绑定==============");
        }
    }
    //Activity
    @Override
    public void  onDestroy() {

        super.onDestroy();
        if(connection!=null) {
            unbindService(connection);//死亡之前调用
            connection = null;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindTestService();
       // unbindTestService();
    }

The method onServiceConnected ServiceConnection object has a IBinder object can be achieved with a bound communication between Service. In the development of Service class, the class must provide a Service IBinder onBind (Intent intent) method, bindings local Service in the case of, IBinder objects onBind (Intent intent) method returns an object that will be passed ServiceConnection in onServiceConnected (ComponentName name service parameters, service IBinder) method, can communicate with the visitor through the Service IBinder object. In the actual development often use inherited Binder (IBinder implementation class) IBinder way to achieve their target.

For onBind of Service () method returns the object IBinder, it can be treated as the Service component callback object returned, Service allows the client to access the data through the interior of Service IBinder object can be realized so that the client communication between the Service.

Implementation process

Service life cycle

Two examples of start Service above, we have a life-cycle approach Service's observations. We found that the life-cycle approach different callback Service startup mode is also different.

Service life cycle

To sum up the life cycle callback method Service:

the startService () and bindService () are two independent operations, we can not only start binding; third parameter may be the method, when bound by bindService start (); can also be started after the first bound;
① the start of the life cycle of services: If a service is called an Activity Context.startService way to start (service can also start the service), then regardless of whether there Activity bindService use binding or unbinding unbindService the service, the service in Background process. If a Service is startService start method multiple times, then the onCreate method is only called once, but each time onStartCommand will be called back, and the system will only create an instance of Service (so you only need to call one stopService to stop). The Service will always run in the background, regardless of the corresponding program Activity is running, until called stopService, or their stopSelf method. Of course, if enough system resources, Android system is also likely to end service.

② bound lifecycle services: If a Service Context.bindService method is called an Activity binding start, no matter bindService call several times to call, onCreate method will only be called once, but always onStartCommand method is not called. When the link is established, Service will always run, unless you call Context.unbindService disconnected or before the call bindService of Context does not exist (such as when the Activity of the finish), the system will automatically stop Service, onDestroy correspondence will be called.

③ is started again bind the life cycle of services: If a Service is started first, and then is bound, the Service will be running in the background. And regardless of the call, onCreate always only called once, the corresponding startService call many times, Service of onStartCommand will call many times. UnbindService calls will not stop Service, and must call itself stopSelf stopService or Service to stop the service (using stopService under the premise of no unbundling is not out of service).

④ When the cleanup when the service is stopped: When a Service is terminated (1, call stopService; 2, call stopSelf; 3, there is no longer connected to the binding (by bindService start)) when, onDestroy method will be called back, here you should do some cleanup (such as creating and running threads of stop Service, the registered listeners, receivers, etc.).

Considerations when using the Service

① when calling bindService bound to the Service, you should ensure that somewhere unbindService call unbind (although Activity is finish automatically when unbound, and will automatically stop Service);

After ② startService start using the service, be sure to use stopService stop the service, regardless of whether you use bindService;

③ should pay attention to while using startService and bindService: Service termination, with needs unbindService stopService calls at the same time, in order to terminate the Service. About calling sequence, if the first call unbindService at this time does not automatically terminate the service, then call stopService service will stop; if the first call stopService service at this time will not be terminated, unbindService need to call (or call bindService of Context does not exist, Activity was as finish time) service will stop automatically.

④ When the rotary phone screen, if the reconstruction Activity takes place, using the previous rotation bindService established connection will be disconnected (Context does not exist).

⑤ in versions prior to 2.0 sdk, onStart method used was replaced onStartCommand method, but onStart method is still valid.

 

Reception

Due to the background service priorities is relatively low, when the system out of memory, it is likely to be recycled out, so is the front desk to make up for this shortcoming, it can be left running without being recovery system. For example: ink weather Weather in the status bar

 

Reception

 

IntentService

The default service code is running in the main thread. If you want to execute the code inside the time-consuming operations in the service, you need to open a main thread to handle these codes. For example, in the example start and stop of the Service, IntentService Service is designed to solve time-consuming operation can not be performed in this issue, create a IntentService is also very simple, as long as inheritance and override onHandlerIntent IntentService function, the function can be a time-consuming operation.

IntentService using steps
1, inherited IntentService create a custom class IntentService

import android.app.IntentService;
import android.content.Intent;


public class BindIntentService extends IntentService {
    private boolean quit = false;
    private int count = 0;

    public BindIntentService() {
        super("BindIntentService");
    }

    /**
     * 必须实现的抽象方法,我们的业务逻辑就是在这个方法里面去实现的
     * 方法在子线程运行,我们不用去关心ANR的问题
     * 在OnCreate方法里面创建并启动子线程,
     * 在OnStartCommand方法里面,将Intent封装成Message并传递到子线程的handler,然后回调onHandleIntentonStart
     *
     * @param intent
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        while (!quit) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count++;
            System.out.println("==================Current count:" + count + "====================");
            if (count == 10)
                quit = true;
        }
    }

    /**
     * 为了验证onHandleIntent执行后,服务会不会自动销毁,我们在这里重写onDestroy方法
     * 如果会自动销毁,那么在"IntetnService Running"出现后,应该会出现"IntetnService Stop"
     */
    @Override
    public void onDestroy() {
        System.out.println("==================BindIntentService onDestroy:" + count + "====================");
        //经测试,如果onHandleIntent里面的代码逻辑没有走完,在服务外部调用stopService来停止服务,并不会立即结束子线程
        quit = true;
        super.onDestroy();
    }
}

2, in which Manifest registration IntentService, registered the same way as with the Service

3, start IntentService
we recommend startService (intent) way to start the service.

Note! You can also use bindService way to start the service. However, when using bindService start, even if the logic execution onHandleIntent inside is completed, the service will not be automatically destroyed. The reason should be the Service or the bound state, calling stopSelf not be stopped. So if bindService start using the service will lose IntentService a major feature, please use caution.

4, destroy IntentService
IntentService a major feature of which is, after onHandleIntent code logic executed, the automatic destruction of Service. So we can not stop IntentService specialize in the operation.

Note! We can also call stopService client service manual to destroy, but in this way will not stop child thread IntentService inside started. If you want to destroy this way service, you must pay attention to the child thread can not be stopped, leading to memory leak.

system service

System Services provides many convenient services, you can query Wifi, network status, battery query, the query volume, query the package name, query and other related information, etc. Application and more services, we can confidently query specific documents, for example two common service here .

wifi

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
boolean enabled = wm.isWifiEnabled();

Maximum volume

AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
int max = am.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);

Reference connection:

https://blog.csdn.net/javazejian/article/details/52709857

https://www.jianshu.com/p/d48b386225fc

https://www.jianshu.com/p/d4d147fd8549

https://blog.csdn.net/geyunfei_/article/details/78851024

Published 260 original articles · won praise 112 · views 260 000 +

Guess you like

Origin blog.csdn.net/qq_34491508/article/details/103961678