The two methods of service of the four components of Android Comments

Service brief overview

Service (Service): is not a user interface, it can run in the background and can perform long-term application components operation. Start service by other application components (such as: Activity, another service). In addition, the components can be bound to the service to interact with, and even perform interprocess communication (IPC). For example: service can process network transactions, play music, perform file I / O or interact with the content provider, and all this can be carried out in the background.


Priority of the process

Understand the priority of a process can help you understand the service -

  • 1. Foreground process (foreground process)
    • Sentence summary: There are currently foreground process is the process of interaction with the user.
  • 2. Visible process (visible processes)
    • Activity onPause method is equivalent to execution. Such as: Activity pops up when Dialog.
  • 3. Service process (service process)
    • Equivalent to using startService open a service, though users do not see, but it is a matter of concern to the user. Such as: background playing music, downloading data.
  • 4. Background process (daemon)
    • Activity onStop equivalent method is performed. Such as: Press the Home key to exit the application.
  • 5. Empty process (process empty)
    • The application does not have any active components in the application is an empty process. The only reason is to improve the survival time of the next turn.

Open services in two ways

Services: The default run in the main thread.

Service creation process

  1. Customize a service class that inherits android.app.Service;
  2. Configuration service (AndroidManifest.xml) in the manifest file;
  3. Overriding methods in the service class.
<service android:name=".service.MyCustomService"></service>

Both services open the way

A: start way

First on the code

    private Intent startIntent;
    //start方式:开启服务
    public void startOpenService(View v) {
        //创建一个开启服务的Intent对象
        startIntent = new Intent(this, MyCustomService.class);
        this.startService(startIntent); //开启一个服务
    }

    //start方式:关闭服务
    public void startCloseService(View v) {
        if (startIntent != null) {
            this.stopService(startIntent);
            startIntent = null;
        }
    }

1. Open the service by startService (Intent service)

  • onCreate (), onStartCommand () method will be executed in turn two when the service first opened.
  • When the service is turned on, and then click Turn On services, it will only execute onStartCommand () method.

2. Turn off the service by stopService (Intent service)

  • onDestroy () method will be in the implementation stopService method (closed service), and is executed!
  • Note parameters: Intent object can not be null, first sentence be empty (null is not the case, you can repeatedly call).

Special Note
1. stopService passed the Intent object must be passed and startService Intent object is the same object, in order to ensure open service is turned off.
2. Application quit (application works behind the scenes, not killed), the service will still be running.
3. When manually kill the application process, the service will be terminated! And does not perform the way services onDestroy () method.

Two: bind mode

First on the code

    private Intent bindIntent;
    private MyServiceConnection connection;
    private boolean isSuccess;
    //bind方式:开启服务
    public void bindOpenService(View v) {
        if (!isSuccess) {
            bindIntent = new Intent(this, MyCustomService.class);
            //boolean bindService(Intent service,  //开启服务的意图对象
            //                    ServiceConnection conn, //服务连接对象
            //                    int flags)  //绑定服务操作选项()
            connection = new MyServiceConnection();
            isSuccess = this.bindService(bindIntent, connection, Context.BIND_AUTO_CREATE);
        }
    }
    
    //bind方式:解绑服务
    public void bindCloseService(View v) {
        //void unbindService(ServiceConnection conn)
        if (connection != null) {
            this.unbindService(connection);
            connection = null;
            isSuccess = false;
        }
    }

1. () open service by bindService

  • onCreate (), onBind () method when the two first open service, are subsequently performed.
  • BindService operation again, it will not have any way to be executed. To use this method to open the service, it is recommended to obtain state after binding, if successful operation is no longer binding.

2. unbindService () unbundling services

  • onUnbind (), onDestroy () method will be two services in the implementation of unbundling unbindService methods, it is subsequently performed. So unbundling can only do this once.

Special Note
ServiceConnection objects 1. binding settlement tied passed to ensure that the same object!
2. isSuccess storage service binding status of success (true), and when the binding is successful, to avoid duplication of bindings. It is inconsistent with the object ServiceConnection new object each time the object is new bindService pass, passing when ServiceConnection unbindService objects may be bound to deliver the service, it will throw an exception!
3. After the unbundling, isSuccess assignment false, it can once again operate bound.
4. bind service is the way to open an invisible service, in the settings can not be found (in fact, some phones now customize the system, start the way open service has become an invisible served).
5. bind services and open manner opener (Activity), there is dependency, before the opener is destroyed, it must open the way to bind unbundling of services, or will throw an exception! (Not to do with the students, but for the same die.)


Service template code

Demand: In the Activity using bind a way to start the service, and the service method call (simulate some business processing).
Analysis: Process Steps

  1. Create a service class that inherits Service. Such as: MyCustomService;
  2. Customize a service interface object class, implement ServiceConnection interface. Such as: MyServiceConnection;
  3. Custom help a middle class, class inheritance Binder (IBinder implementation class). When the service onBind method to be executed, as a return value. Such as: MyBinderImpl;
  4. A custom interface to encapsulate some intermediate class object shared help function. Such as: MyBinderInterface.

Entire process code is as follows

MyCustomService.class

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
 * 创建一个服务类
 */
public class MyCustomService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        //该方法:在使用【bind绑定】的方式:开启服务的时候,才会被调用
        Log.e("Service生命周期", "【onBind】");
        //返回值需要一个IBinder接口实现类对象(可以返回自定义实现类对象)
        return new MyBinderInter();
    }
    @Override
    public boolean onUnbind(Intent intent) {
        Log.e("Service生命周期", "【onUnbind】");
        return super.onUnbind(intent);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        //服务第一次创建时调用
        Log.e("Service生命周期", "【onCreate】");
        //获取服务运行线程
        String name = Thread.currentThread().getName();
        long id = Thread.currentThread().getId();
        Log.e("线程", "【Service】" + name + "-" + id);
    }
    
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //每次开启服务(Activity内调用startService()方法)时调用
        Log.e("Service生命周期", "【onStartCommand】");
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        //服务被销毁时调用
        Log.e("Service生命周期", "【onDestroy】");
    }
    
    

    //模拟:定义一些函数,作为业务处理
    public void playPoker() {
        Toast.makeText(this, "玩扑克", Toast.LENGTH_SHORT).show();
    }

    public void playBall() {
        Toast.makeText(this, "打球", Toast.LENGTH_SHORT).show();
    }


    /**
     * 中间帮助类:自定义类继承 Binder(IBinder 接口实现类)
     */
    public class MyBinderInter extends Binder implements MyBinderInterface {

        @Override
        public void callPlayPoker() {
            playPoker();
        }

        @Override
        public void callPlayBall() {
            playBall();
        }
    }
}

MyServiceConnection.class

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
/**
 * 创建一个服务接口对象类:当服务绑定成功时,可以接收一个中间帮助类对象
 * 当 MyCustomService 中的 onBind 方法返回值不为null时,该服务连接对象类中的方法才会被执行
 */
public class MyServiceConnection implements ServiceConnection {

    private MyCustomService.MyBinderInter myBinderInter;

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        //服务绑定成功后执行(onBind执行后执行该方法)  IBinder:中间帮助类对象
        this.myBinderInter = (MyCustomService.MyBinderInter) iBinder;
        Log.e("Service生命周期", "【onServiceConnected】");
    }
    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        //该方法在连接正常关闭的情况下不会被执行,只有在Service被破坏或杀死的情况下执行。
        //如:系统资源不足,需要杀掉该服务,则会执行该方法。
    }

    public void callPlayPoker(){
        if(myBinderInter!=null){
            myBinderInter.callPlayPoker();
        }
    }

    public void callPlayBall(){
        if(myBinderInter!=null){
            myBinderInter.callPlayBall();
        }
    }
}

Interface: MyBinderInterface

//自定义接口:封装中间帮助类所共有的一些方法
public interface MyBinderInterface {
    //随意定义两个抽象方法,由实现类重写
    void callPlayPoker();
    void callPlayBall();
}

ServiceActivity calls within the service in the method

  • Remember: When executed onDestroy in activity () method, the unbundling service, otherwise it will throw an exception.
public class ServiceActivity extends BaseActivity {

    private Intent bindIntent;
    private MyServiceConnection connection;
    private boolean isSuccess;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
    }

    //bind方式:开启服务
    public void bindOpenService(View v) {
        if (!isSuccess) {
            bindIntent = new Intent(this, MyCustomService.class);
            connection = new MyServiceConnection();
            isSuccess = this.bindService(bindIntent, connection, Context.BIND_AUTO_CREATE);
        }
    }

    public void playPoker(View v) {
        if (connection != null) {
            connection.callPlayPoker();
        }
    }

    public void playBall(View v) {
        if (connection != null) {
            connection.callPlayBall();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (connection != null) {
            this.unbindService(connection);
            connection = null;
            isSuccess = false;
        }
    }
}


About: bindService and unbindService source description (English good junior partner can learn together)
boolean bindService (the Intent Service, ServiceConnection conn, int flags)

  • 方法说明
    Connect to an application service, creating it if needed. This defines a dependency between your application and the service. The given conn will receive the service object when it is created and be told if it dies and restarts. The service will be considered required by the system only for as long as the calling context exists. For example, if this Context is an Activity that is stopped, the service will not be required to continue running until the Activity is resumed.
    This function will throw SecurityException if you do not have permission to bind to the given service.
    Note: this method can not be called from a BroadcastReceiver component. A pattern you can use to communicate from a BroadcastReceiver to a Service is to call startService(Intent) with the arguments containing the command to be sent, with the service calling its stopSelf(int) method when done executing that command. See the API demo App/Service/Service Start Arguments Controller for an illustration of this. It is okay, however, to use this method from a BroadcastReceiver that has been registered with registerReceiver(BroadcastReceiver, IntentFilter), since the lifetime of this BroadcastReceiver is tied to another object (the one that registered it).
  • Parameters(参数说明)
    service:Identifies the service to connect to. The Intent may specify either an explicit component name, or a logical description (action, category, etc) to match an IntentFilter published by a service.
    conn:Receives information as the service is started and stopped. This must be a valid ServiceConnection object; it must not be null.
    flags:Operation options for the binding. May be 0, BIND_AUTO_CREATE, BIND_DEBUG_UNBIND, BIND_NOT_FOREGROUND, BIND_ABOVE_CLIENT, BIND_ALLOW_OOM_MANAGEMENT, or BIND_WAIVE_PRIORITY.
  • Returns(返回值说明)
    If you have successfully bound to the service, true is returned; false is returned if the connection is not made so you will not receive the service object.

void unbindService (ServiceConnection conn)

  • 方法说明
    Disconnect from an application service. You will no longer receive calls as the service is restarted, and the service is now allowed to stop at any time.
  • Parameters(参数说明)
    conn:The connection interface previously supplied to bindService(). This parameter must not be null.

Reference Links: Google official document: Service

PS: looking forward to have more exchanges with you, thank you ~

Guess you like

Origin www.cnblogs.com/io1024/p/11566803.html