android关于binder的简单通信过程

news2024/9/23 23:24:31

文章目录

  • 简述
  • aidl文件
  • 服务端的实现
  • 客户端的实现
  • 验证过程

简述

主要实现的是两个应用之间跨进程通信的过程,client端调用server端的具体实现,然后server端给client回调数据,详细如下所示

aidl文件

以下的文件需要在服务端与客户端都配置一份且保持一致

1.aidl 跨进程所需要的文件目录如下所示
在这里插入图片描述
以下文件是对应的TestDataBean.aidl文件的
在这里插入图片描述

2.IOnTestDataCallback.aidl文件,用于服务端给客户端回调接口,传递一个parcel类型的数据

// IOnTestDataCallback.aidl
package com.example.test;
import com.example.test.TestDataBean;

// Declare any non-default types here with import statements

interface IOnTestDataCallback {
    void onCallback(in TestDataBean dataBean);
}

3.IOnTestDataListener.aidl文件,用于客户端给服务端请求数据的调用过程,oneway表示异步方法,不用等待方法中的实现执行完成,直接返回就行了。

// IOnTestDataListener.aidl
package com.example.test;
import com.example.test.IOnTestDataCallback;
// Declare any non-default types here with import statements

interface IOnTestDataListener {
    oneway void sendData(String str, in byte[] bytes,in IOnTestDataCallback callback);
}

4.TestDataBean.aidl文件,用于跨进程传递parcel对象数据。

// TestDataBean.aidl
package com.example.test;

parcelable TestDataBean;

5.TestDataBean.java文件,TestDataBean.aidl中的具体实现方式。

package com.example.test;

import android.os.Parcel;
import android.os.Parcelable;

public class TestDataBean implements Parcelable {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    private String name;
    private int number;


    public TestDataBean() {

    }

    protected TestDataBean(Parcel in) {
        name = in.readString();
        number = in.readInt();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(number);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<TestDataBean> CREATOR = new Creator<TestDataBean>() {
        @Override
        public TestDataBean createFromParcel(Parcel in) {
            return new TestDataBean(in);
        }

        @Override
        public TestDataBean[] newArray(int size) {
            return new TestDataBean[size];
        }
    };
}

服务端的实现

1.TestBinderService.java文件

package com.tencent.wemeet.testwhitelist;

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

import androidx.annotation.Nullable;

import com.example.test.IOnTestDataCallback;
import com.example.test.IOnTestDataListener;
import com.example.test.TestDataBean;

import java.util.Arrays;

public class TestBinderService extends Service {

    private static final String TAG = "TestBinderService";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new IOnTestDataListener.Stub() {
            @Override
            public void sendData(String str, byte[] bytes, IOnTestDataCallback callback) throws RemoteException {
                Log.d(TAG, "str = " + str + ",bytes = " + Arrays.toString(bytes));
                TestDataBean bean = new TestDataBean();
                bean.setName("zhangsan");
                bean.setNumber(20);
                try {
                    Thread.sleep(5000);
                    callback.onCallback(bean);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
    }
}

2.AndroidManifest.xml文件配置

        <service
            android:name=".TestBinderService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.binder.test.service" />
            </intent-filter>
        </service>

客户端的实现

TestBinderActivity.java文件

package com.example.test;

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.os.RemoteException;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class TestBinderActivity extends AppCompatActivity {

    public static final String TAG = "TestBinderActivity";
    private boolean isBinder;
    private IOnTestDataListener binder;

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

        Intent intent = new Intent();
        intent.setAction("com.binder.test.service");
        intent.setPackage("com.tencent.wemeet.testwhitelist");
        isBinder = bindService(intent, connection, Context.BIND_AUTO_CREATE);

        findViewById(R.id.btn_test).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binder == null) {
                    Log.d(TAG, "binder is null");
                    return;
                }
                Log.d(TAG, "begin");
                try {
                    binder.sendData("123", new byte[]{1, 2, 3}, new IOnTestDataCallback.Stub() {
                        @Override
                        public void onCallback(TestDataBean dataBean) throws RemoteException {
                            Log.d(TAG, "name = " + dataBean.getName() + ",number = " + dataBean.getNumber());
                        }
                    });
                } catch (RemoteException e) {
                    Log.d(TAG, "sendData RemoteException");
                    throw new RuntimeException(e);
                }

                Log.d(TAG, "end");
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBinder) {
            isBinder = false;
            unbindService(connection);
            connection = null;
            binder = null;
        }
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected");
            binder = IOnTestDataListener.Stub.asInterface(service);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected");
        }
    };
}

验证过程

先打开server端相关的应用进程,之后再打开client端相关的应用进程,然后通过binder的方式连接server端并进行通信,记录大致的通信过程。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2078348.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

使用极狐GitLab进行K3S集群的维护与控制

极狐GitLab 是 GitLab 在中国的发行版&#xff0c;专门面向中国程序员和企业提供企业级一体化 DevOps 平台&#xff0c;用来帮助用户实现需求管理、源代码托管、CI/CD、安全合规&#xff0c;而且所有的操作都是在一个平台上进行&#xff0c;省事省心省钱。可以一键安装极狐GitL…

企业图纸防泄密怎么做?10款好用的图纸加密软件推荐

在当今竞争激烈的市场环境中&#xff0c;企业图纸作为核心技术和商业机密的重要组成部分&#xff0c;其安全性直接关系到企业的竞争力和市场地位。因此&#xff0c;采取有效措施防止图纸泄密至关重要。本文将探讨企业图纸防泄密的综合策略&#xff0c;并推荐10款优质的图纸加密…

工业企业能源管理系统

进入新世纪以来&#xff0c;我国的社会主义市场经济持续繁荣&#xff0c;在经济发展的同时&#xff0c;能源耗费量与日俱增&#xff0c;在很大程度上阻碍了我国经济的可持续发展。为了实现节能减排的目标&#xff0c;大量企业进行了产业结构调整和优化升级&#xff0c;促进了资…

OpenAI Embeddings API: How to change the embedding output dimension?

题意&#xff1a;OpenAI Embeddings API&#xff1a;如何更改嵌入输出维度&#xff1f; 问题背景&#xff1a; In the official OpenAI node library Create embeddings if for example using the model text-embedding-ada-002 the embeddings returned is an array of aroun…

PHP宿舍外面点单系统---附源码97171

目 录 摘 要 Abstract 1 绪论 1.1 研究背景 1.2国内外研究现状 1.3论文结构与章节安排 2 宿舍外卖点单系统分析 2.1可行性分析 2.1.1 技术可行性分析 2.1.2经济可行性分析 2.1.3操作可行性分析 2.2 功能需求分析 2.2.1普通用户功能 2.2.2商家用户功能 2.2.3管理…

Qt:玩转QPainter序列六

前言 继续看源码。 正文 剩下的大部分都是画各种图形的函数&#xff0c;它们一般都有多个重载版本&#xff0c;我就不一 一介绍使用了&#xff0c;只挑其中的一部分使用一下。 在 QPainter 类中&#xff0c;这些方法涉及到绘图的各种功能&#xff0c;主要用于设置视图变换、…

chapter08-面向对象编程——(Object类详解)——day09

目录 319-运算符 320-查看Jdk源码 321-子类重写equals 322-equals课堂练习1 323-equals重写练习2 324-equals重写练习3 325-hashCode 326-toString 327-finalize 319-运算符 引用的都是同一个地址&#xff0c;所以返回true 320-查看Jdk源码 equals只能判断引用类型是…

线程同步学习

1、线程同步的定义 线程同步不是一起、相同&#xff0c;而是协调、协同的意思。 1)按预定的先后次序进行运行&#xff0c;如:您说完&#xff0c;我再说;线程A生成数据后交给线程B处理; 2)公共资源同一时刻只能被一个线程使用;共享数据在同一时刻只能被一个线程修改&#xff0c…

uniapp 小程序支持打开手机相册和摄像头

开发uniapp 时&#xff0c;有时需要让用户上传手机相册或者拍摄图片&#xff0c;对图片进行处理&#xff0c;下面提供了一个method&#xff0c;支持打开摄像头拍照和相册功能&#xff0c;完成后&#xff0c;对图片做base64处理。 // 打开相册的方法openCamera() {let _thisthi…

给自己复盘的tjxt笔记day9

优惠券管理 开发流程 需求分析&#xff0c;接口统计&#xff0c;数据库设计&#xff0c;创建分支&#xff0c;创建新模块&#xff08;依赖&#xff0c;配置&#xff0c;启动类&#xff09;&#xff0c;生成代码&#xff0c;引入枚举状态 优惠券管理 增删改查的业务代码&#…

vagrant 创建虚拟机

创建一个名为 “Vagrantfile” 的文件&#xff0c;修改如下内容&#xff1a; Vagrant.configure("2") do |config|(1..3).each do |i|config.vm.define "k8s-node#{i}" do |node|# 设置虚拟机的Boxnode.vm.box "centos/7"# 设置虚拟机的主机名…

Behave使用体验

behaveuiautomator2jenkins 同理&#xff0c;Behave也可以和Appium/AirTest框架结合 运行环境 pip install uiautomator2 behave behave2cucumber 意事项&#xff1a;behave版本号建议1.2.5&#xff0c;因为1.2.6和Jenkins Cucumber Report插件不兼容 生成报告 html报告 …

各位,请入局AI大模型,现在!立刻!马上!!

AI 大模型人才供不应求 2024年&#xff0c;AI 在国内市场全面大爆发&#xff0c;不断涌现出新的算法、模型和应用场景&#xff0c;各行各业的垂类大模型应用也迎来井喷期。 无论是华为、 百度、阿里、字节等互联网巨头&#xff0c; 还是中小型的科技公司都在高薪挖 AI 大模型人…

易盾空间推理 分析

声明: 本文章中所有内容仅供学习交流使用&#xff0c;不用于其他任何目的&#xff0c;抓包内容、敏感网址、数据接口等均已做脱敏处理&#xff0c;严禁用于商业用途和非法用途&#xff0c;否则由此产生的一切后果均与作者无关&#xff01; 有相关问题请第一时间头像私信联系我…

Codeforces Round 968 (Div. 2) ABC题详细题解(C++,Python)

前言&#xff1a; 本文为Codeforces Round 968 (Div. 2)的ABC详细题解&#xff0c;包含C,Python语言描述&#xff0c;觉得有帮助或者写的不错可以点个赞 感觉D题说的好抽象&#xff0c;看不懂&#xff0c;之后实力够了更新 目录 题A: 题目大意和解题思路: 代码实现(C): 代…

全国大学生数学建模大赛——黄花鱼的最优捕捞策略

渔业管理部门规定&#xff0c;每年只允许在产卵孵化期前的8个 月进行捕捞作业。如果每年投入的捕捞能力(如渔船数、下网 次数等)固定不变&#xff0c;这时单位时间捕捞量将与各年龄组鱼群条 数成正比&#xff0c;比例系数不妨设为捕捞强度系数。通常使用 13mm 网眼的拉网&…

中国高校发表科技论文及著作数量数据集(2009-2022年)

中国各地区的高校科技产出数据&#xff0c;包括27个指标&#xff0c;科技论文发表、著作出版、专利申请、专利转让、国家标准项等。这些指标综合反映了各地区高校在科学研究和技术开发方面的活跃程度及创新能力 一、数据介绍 数据名称&#xff1a;中国地区高校发表科技论文、…

Android App启动流程

1.通过 Launcher 启动应用时&#xff0c;点击应用图标后&#xff0c;Launcher 调用 startActivity 启动应用。 2.Launcher Activity 最终调用 Instrumentation 的 execStartActivity 来启动应用。 3.Instrumentation 调用 ActivityManagerProxy (ActivityManagerService 在应…

计算机类-本科毕业设计快速通关攻略-(选题-创新点-论文框架-论文绘图)

一、推荐选题 大多数人都没有什么基础&#xff0c;不推荐做系统类的&#xff0c;建议走深度学习方向&#xff0c;简单易上手&#xff0c;下面将给出几个我认为不错的方向。 1、目标检测类 目标检测是每年深度学习毕业设计的主流&#xff0c;如Faster R-CNN、YOLO、SSD等算法…

程序员心理健康测试问卷

当然&#xff0c;以下是一份针对程序员设计的心理健康测试问卷。这份问卷旨在帮助程序员评估自己的心理健康状态&#xff0c;并识别可能存在的心理问题。请注意&#xff0c;此问卷仅供参考&#xff0c;不能替代专业心理咨询或诊断。 程序员心理健康测试问卷 基本信息 姓名&am…