The Service of the Four Components of Android

Keywords: Android xml network encoding

1. Concept:

(1).Service can be said to be an Activity running in the background. It's not a separate process, it just needs the application to tell it what to do in the background.

(2) If it is to interact with the user, it needs to receive the display through the notification bar or by sending broadcasting and UI.

(3) Its application is very extensive, especially in the framework layer, the application is more to call system services.

2. Role:

(1) It is used to handle background operations that do not interfere with the user's use. Download below, Network Access. Play music, which can be turned on through Intent, but also can be bound to host objects (callers such as Activity) for use.

(2) If Activity is to display the information of the front page, then Service is to operate in the background. If a service interacts with the front UI, it can send a broadcast or a notification bar.

2.Service life cycle

Pictures from the Internet:


Note: In local services, onStart has been replaced by onStartCommand method

Service has two startup modes:

1. Open the service through startService()

Life cycle:

First Open Service: onCreate () - > onStartCommand ()

Every time a service is opened after the first time: onStartCommand()

Services opened through startService() can only be terminated through the stopService() method


2.bindService Opens Services: Binding the Service Life Cycle with the Caller's Life Cycle
First Open Service: onCreate () - > onBind ()
Every time after the second time: nothing is done
Services opened through bindService must be unbound at the time of activity destruction or before it is destroyed, and the binding must be unbound once, not many times.
 
The difference between startService opening service and bindService opening service:
startService can only open a service by stopService()
bindService and activity life cycle are tied together
 
The bindService enables interaction with the caller (Activity and Broadcast can open the Service)
startService: Usually for background Downloads
BidService: Usually used for music players

The following is the implementation of the specific code:

    /**
     * Steps for interaction between service and activity
     * 1. Create an implementation class of Binder in service (write a class to inherit Binder)
     * 2. Write specific methods in the implementation class
     * 3. Return the object of the implementation class in the onBinder method
     * 4. Declare the object of the Binder implementation class in the caller
     * 5. Get the Binder object in onService Connected
     * 6. Call the method in Service
     */

MainActivity:

public class MainActivity extends AppCompatActivity {
    Button but_start, but_stop, but_bind, but_unbind, but_myExample,but_link;
    MyServiceConnection conn;
    MyService.MyBinder myBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**Open Services*/
        // startService(new Intent(MainActivity.this, MyService.class));
        conn = new MyServiceConnection();
        init();
    }

    private void init() {
        but_start = (Button) findViewById(R.id.but_start);
        but_stop = (Button) findViewById(R.id.but_stop);
        but_bind = (Button) findViewById(R.id.but_bind);
        but_unbind = (Button) findViewById(R.id.but_unbind);
        but_myExample = (Button) findViewById(R.id.but_myExample);
        but_link= (Button) findViewById(R.id.but_link);
        but_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**Open Services*/
                startService(new Intent(MainActivity.this, MyService.class));
            }
        });
        but_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**Out of Service*/
                stopService(new Intent(MainActivity.this, MyService.class));
            }
        });
        but_bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**Binding services
                 * Parametric 1: Intent service
                 * Parametric 2: Service Connection conn listens for service connection status
                 * ServiceConnection An interface needs to write a class to implement it
                 * Parametric 3: int flags: How to connect
                 *  Service.BIND_AUTO_CREATE Automatically create connections*/
                bindService(new Intent(MainActivity.this, MyService.class), conn, Service.BIND_AUTO_CREATE);
            }
        });
        but_unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**Unbundling service*/
                unbindService(conn);

            }
        });
        //Example
        but_myExample.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myBinder.myExample();
            }
        });
        //Continuous use
        but_link.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //open
                Intent intent=new Intent(MainActivity.this, MyService.class);
                startService(intent);
                //binding
                bindService(intent,conn,Service.BIND_AUTO_CREATE);
            }
        });
    }

    public class MyServiceConnection implements ServiceConnection {
        //Service Connection
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MyService.MyBinder) service;
        }

        //Service not connected
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    //Destruction
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
    }
}
MyService:

public class MyService extends Service {
    //Called the first time a service is opened
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MyService", "onCreate");

    }

    //binding
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("MyService", "onBind");
        return new MyBinder();
    }

    //Untying
    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    //start
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService", "onStartCommand");
        return super.onStartCommand(intent, flags, startId);

    }

    //Destruction
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("MyService", "onDestroy");
    }

    public void examples() {
        Toast.makeText(this, "I am an example. examples", Toast.LENGTH_SHORT).show();
    }

    public class MyBinder extends Binder{
        public void myExample(){
            examples();
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
 >
<Button

    android:id="@+id/but_start"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="open"/>
    <Button
        android:id="@+id/but_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop it"/>
    <Button
        android:id="@+id/but_bind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="binding"/>
    <Button
        android:id="@+id/but_unbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Untying"/>

    <Button
        android:id="@+id/but_myExample"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Example"/>
    <Button
        android:id="@+id/but_link"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Open and bind"/>
</LinearLayout>

Reference address: http://www.3lian.com/edu/2015/06-06/219880.html




Posted by thiscatis on Sat, 29 Jun 2019 13:29:37 -0700