前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Binder基本使用

Binder基本使用

作者头像
233333
发布2020-02-18 15:47:37
9370
发布2020-02-18 15:47:37
举报

Android开发中,Binder是一种跨进程通信方式,而使用AIDL可以实现Binder的工作。

如何使用它是了解它的第一步,本文章主要记录使用Binder的一些步骤。(代码思路参考《Android开发艺术探索》任玉刚 著)

1.创建两个activity

两个activity(OneActivity、TwoActivity),将OneActivity假设为服务端,TwoActivity假设为客户端,分别运行在不同进程中

在AndroidManifest.xml中,为TwoActivity设置进程,这样两个activity就分别运行在不同的进程中了

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

2. 创建AIDL文件

在AIDL文件中声明客户端想要调用服务端的方法

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

AIDL文件声明完,activity等文件并不能调用到IInfManager接口,需要在app的build.gradle文件中的android{}中添加

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

然后点击sync now按钮,activity文件就可以调用到IInfManager接口了,可以在app\build\generated\source\aidl\debug文件下找到自动生成的IInfManager.java文件。

3.创建Service

Service中创建Binder对象,在onBind方法中返回这个对象,Binder对象中具体实现了IInfManager接口中的方法。Service需要在AndroidManifest.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.服务端OneActivity

OneActivity中设置按钮跳转至TwoActivity,这里为了简单,使用startService可以为InfManageService中name变量初始化"zhangsan"的值。也可以与客户端TwoActivity中一样,绑定service,建立连接,来设置name的值(具体参考下一步客户端的用法)。

@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.客户端TwoActivity

首先绑定InfManageService服务,建立连接,连接成功后通过返回的IBinder对象可以获得IInfManager接口,可以通过这个接口去使用服务端的方法。

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);
}

上面代码onServiceConnected方法中,首先在TwoActivity界面中显示了服务端的name变量内容"zhangsan"

image
image
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-02-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.创建两个activity
  • 2. 创建AIDL文件
  • 3.创建Service
  • 4.服务端OneActivity
  • 5.客户端TwoActivity
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档