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

举报
韩曙亮 发表于 2022/01/13 00:07:48 2022/01/13
【摘要】 文章目录 一、创建 Service 远程服务1、创建 Service2、AndroidManifest.xml 清单文件中配置 Service 二、绑定 Service 远程服务1、核心代码2...





一、创建 Service 远程服务




1、创建 Service


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


        <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 清单文件中配置的 ;

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

  
 

2、完整代码


完整代码如下 :

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 对象 ;

在这里插入图片描述

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]

  
 

文章来源: hanshuliang.blog.csdn.net,作者:韩曙亮,版权归原作者所有,如需转载,请联系作者。

原文链接:hanshuliang.blog.csdn.net/article/details/120325452

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。