前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Binder 机制】AIDL 分析 ( 创建 Service 服务 | 绑定 Service 远程服务 )

【Binder 机制】AIDL 分析 ( 创建 Service 服务 | 绑定 Service 远程服务 )

作者头像
韩曙亮
发布2023-03-29 17:21:30
8291
发布2023-03-29 17:21:30
举报
文章被收录于专栏:韩曙亮的移动开发专栏

文章目录

一、创建 Service 远程服务


1、创建 Service

代码语言:javascript
复制
package kim.hsl.aidl_demo;

import androidx.appcompat.app.AppCompatActivity;

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 android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MainActivity";

    private IMyAidlInterface aidl;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        /**
         * 传入需要的 Service , 让系统寻找指定的远程服务
         * @param name
         * @param service
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 通过 IBinder 对象 , 从系统中获取对应的远程服务或代理对象
            aidl = IMyAidlInterface.Stub.asInterface(service);
            Log.i(TAG, "AIDL 获取成功");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            aidl = null;
        }
    };

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

        // 通过 Action 和 包名 , 绑定远程服务
        Intent intent = new Intent("android.intent.action.MyService");
        intent.setPackage("kim.hsl.aidl_demo");
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

        findViewById(R.id.add).setOnClickListener((View view)->{
            try {
                aidl.addStudent(new Student("Tom"));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        });

        findViewById(R.id.get).setOnClickListener((View view)->{
            try {
                List<Student> students = aidl.getStudents();
                Log.i(TAG, "students = " + students);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        });
    }
}

2、AndroidManifest.xml 清单文件中配置 Service

代码语言:javascript
复制
        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MyService" />
            </intent-filter>
        </service>

二、绑定 Service 远程服务


1、核心代码

通过 Action 和 包名 , 绑定远程服务 , 其中 Action 是在 AndroidManifest.xml 清单文件中配置的 ;

代码语言:javascript
复制
        // 通过 Action 和 包名 , 绑定远程服务
        Intent intent = new Intent("android.intent.action.MyService");
        intent.setPackage("kim.hsl.aidl_demo");
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

2、完整代码

完整代码如下 :

代码语言:javascript
复制
package kim.hsl.aidl_demo;

import androidx.appcompat.app.AppCompatActivity;

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 android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MainActivity";

    private IMyAidlInterface aidl;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        /**
         * 传入需要的 Service , 让系统寻找指定的远程服务
         * @param name
         * @param service
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 通过 IBinder 对象 , 从系统中获取对应的远程服务或代理对象
            aidl = IMyAidlInterface.Stub.asInterface(service);
            Log.i(TAG, "AIDL 获取成功");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            aidl = null;
        }
    };

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

        // 通过 Action 和 包名 , 绑定远程服务
        Intent intent = new Intent("android.intent.action.MyService");
        intent.setPackage("kim.hsl.aidl_demo");
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

        findViewById(R.id.add).setOnClickListener((View view)->{
            try {
                aidl.addStudent(new Student("Tom"));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        });

        findViewById(R.id.get).setOnClickListener((View view)->{
            try {
                List<Student> students = aidl.getStudents();
                Log.i(TAG, "students = " + students);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        });
    }
}

3、运行结果

点击添加按钮 , 即可向远程服务中添加 Student 对象 , 点击获取按钮 , 即可在日志中打印之前添加的所有 Student 对象 ;

在这里插入图片描述
在这里插入图片描述
代码语言:javascript
复制
2021-09-16 15:11:14.492 27781-27781/kim.hsl.aidl_demo I/MainActivity: AIDL 获取成功
2021-09-16 15:11:14.499 27781-27866/kim.hsl.aidl_demo I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 1
2021-09-16 15:11:14.499 27781-27866/kim.hsl.aidl_demo I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2021-09-16 15:11:14.499 27781-27866/kim.hsl.aidl_demo I/OpenGLRenderer: Initialized EGL, version 1.4
2021-09-16 15:11:27.704 27781-27781/kim.hsl.aidl_demo I/MainActivity: students = [name=Tom, name=Tom]


2021-09-16 15:11:40.729 27781-27781/kim.hsl.aidl_demo I/MainActivity: students = [name=Tom, name=Tom, name=Tom, name=Tom, name=Tom, name=Tom, name=Tom, name=Tom]
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-09-16,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 一、创建 Service 远程服务
    • 1、创建 Service
      • 2、AndroidManifest.xml 清单文件中配置 Service
      • 二、绑定 Service 远程服务
        • 1、核心代码
          • 2、完整代码
            • 3、运行结果
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档