Binder basic use

In Android development, Binder is a way of cross process communication, and using AIDL can realize Binder's work.

How to use it is the first step to understand it. This article mainly records some steps of using Binder. (refer to "Android development art exploration" by Ren Yugang for code ideas)

1. Create two activities

Two activities (OneActivity and TwoActivity) assume OneActivity as the server and TwoActivity as the client, running in different processes respectively

In Android manifest.xml, set the process for two activity, so that the two activities run in different processes respectively

<activity android:name=".TwoActivity" android:process=":test"/>

2. Create AIDL file

Declare in the AIDL file that the client wants to call the method of the server

interface IInfManager {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void setName(String name);
 
    String getName();
}

After the AIDL file is declared, activities and other files cannot be called to the IInfManager interface. You need to add them to android {} in the build.gradle file of the app

sourceSets{
    main{
        java.srcDirs = ['src/main/java', 'src/main/aidl']
    }
}

Then click the sync now button, and the activity file can be called to the IInfManager interface. You can find the automatically generated IInfManager.java file under the app\build\generated\source\aidl\debug file.

3. Create Service

The Binder object is created in the service and returned in the onBind method. The Binder object implements the methods in the IInfManager interface. Service needs to be registered in Android manifest.xml.

public class InfManageService extends Service{
 
    private String name;
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        name = intent.getStringExtra("name");
        return super.onStartCommand(intent, flags, startId);
    }
 
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
 
    private Binder binder = new IInfManager.Stub() {
        @Override
        public void setName(String mName) throws RemoteException {
            name = mName;
        }
 
        @Override
        public String getName() throws RemoteException {
            return name;
        }
    };
}

4. Server OneActivity

Set the button in OneActivity to jump to TwoActivity. For simplicity, use startService to initialize the value of "zhangsan" for the name variable in InfManageService. You can also bind the service and establish a connection to set the value of name as in the client TwoActivity (refer to the usage of the client in the next step for details).

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_one);
 
    Intent intent = new Intent(OneActivity.this, InfManageService.class);
    intent.putExtra("name", "zhangsan");
    startService(intent);
 
    btn_one_gototwo = (Button) findViewById(R.id.btn_one_gototwo);
 
    btn_one_gototwo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(OneActivity.this, TwoActivity.class);
            startActivity(intent);
        }
    });
}

5. Client TwoActivity

First, bind the InfManageService service and establish a connection. After the connection is successful, the IInfManager interface can be obtained through the returned IBinder object, through which you can use the methods of the server.

private TextView tv_two_name;
private Button btn_two_change;
 
private IInfManager iInfManager;
 
private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        iInfManager = IInfManager.Stub.asInterface(service);
        try {
            tv_two_name.setText(iInfManager.getName());
            Log.i("TwoActivity","first:" + iInfManager.getName());
            iInfManager.setName("lisi");
            Log.i("TwoActivity","next:" + iInfManager.getName());
        }catch (RemoteException e){
 
        }
    }
 
    @Override
    public void onServiceDisconnected(ComponentName name) {
 
    }
};
 
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_two);
 
    tv_two_name = (TextView) findViewById(R.id.tv_two_name);
    btn_two_change = (Button) findViewById(R.id.btn_two_change);
 
    Intent intent = new Intent(TwoActivity.this, InfManageService.class);
    bindService(intent, connection, Context.BIND_AUTO_CREATE);
 
    btn_two_change.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                iInfManager.setName("wangmazi");
                tv_two_name.setText(iInfManager.getName());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    });
}
 
@Override
protected void onDestroy() {
    super.onDestroy();
    unbindService(connection);
}

In the above code onServiceConnected method, first, the name variable content "zhangsan" of the server is displayed in the TwoActivity interface

Keywords: Android Java xml Gradle

Added by steveryan on Wed, 05 Feb 2020 11:00:15 +0200