Android BindService use case explanation

  • 2021-12-13 17:13:10
  • OfStack

Recently, I learned the application of Service in Android, and I got a small card in BindService, mainly because I didn't completely understand why I want to achieve it at first.

BindService and Started and Service are both Service. What is different?

1. In Started Service, the method StartService () is used to invoke the method. There is no connection between the caller and the service. Even if the caller exits, the service is still making "onCreate ()- > onStartCommand()- > startService()- > onDestroy () ", note that there is no onStart (), which is mainly replaced by onStartCommand () method, and onStart method is not recommended. 2. In BindService, the bindService () method is used to bind the service. When the caller and the binder are bound to 1, the caller 1 exits the service and terminates "onCreate ()- > onBind()- > onUnbind()- > onDestroy () ".

Caller Activity:


package com.zys.service;

import com.zys.service.BindService.MyBinder;

import android.R.bool;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    private Button startBtn;
    private Button stopBtn;
    private boolean flag;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        flag = false;
        // Settings 
        startBtn = (Button)this.findViewById(R.id.startBtn);
        stopBtn = (Button)this.findViewById(R.id.stopBtn);
        startBtn.setOnClickListener(listener);
        stopBtn.setOnClickListener(listener);
    }
    
    private OnClickListener listener = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
            case R.id.startBtn:
                bindService();
                break;
            case R.id.stopBtn:
                unBind();
                break;
            default:
                break;
            }
        }
        
        
    };
    
    private void bindService(){
        Intent intent = new Intent(MainActivity.this,BindService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }
    
    private void unBind(){
        if(flag == true){
            unbindService(conn);
            flag = false;
        }
    }
    
    private ServiceConnection conn = new ServiceConnection() {
        
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            
        }
        
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            MyBinder binder = (MyBinder)service;
            BindService bindService = binder.getService();
            bindService.MyMethod();
            flag = true;
        }
    };
    
}

Service BindService


package com.zys.service;

import java.io.FileDescriptor;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;

public class BindService extends Service {

    private static final String TAG = "BindService";

    public void MyMethod(){
        Log.i(TAG, "BindService-->MyMethod()");
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return myBinder;
    }
    
    public class MyBinder extends Binder{
        
        public BindService getService(){
            return BindService.this;
        }
    }
    
    private MyBinder myBinder = new MyBinder();
}

Because Service in Android uses the method of onBind to bind services, Returns 1 Ibinder object for operation, When we want to get the content of the specific Service method, we need the Ibinder object to return the specific Service object to operate, so the specific Service object must first implement the Binder object, so we can use the bindService method to bind Service, get the specific Service object after getting the Binder object, and then get the methods in Service, and so on. Therefore, we need to pay attention to the fact that the bindService way to bind the service must obtain the object that implements Binder, so this is the way that we must use Binder way to obtain Service instead of directly using Service class, which is constrained by the internal implementation of Android.

The method process is as follows:

Intent intent = new Intent(MainActivity.this,BindService.class)- > Created a new BindService object- > Created a new MyBinder object

- > bindService(intent, conn, Context.BIND_AUTO_CREATE);- > onBind () function---------------------------------------- > onServiceConnected ()

 -- > Get the BindService object just corresponding to the Binder object through the passed Binder object-- > Call the method defined in Service.

This must be passed through the Binder object, because it is passed through the Binder object, and the Service object is obtained through the Binder object, and then the required service is obtained, so the Service must implement the Binder in order to be passed and used.


Related articles: