跨进程调用Service(AIDL Service的使用)

一、概述

AIDL 意思即 Android Interface Definition Language,翻译过来就是Android接口定义语言,是用于定义服务器和客户端通信接口的一种描述语言,可以拿来生成用于IPC的代码。从某种意义上说AIDL其实是一个模板,因为在使用过程中,实际起作用的并不是AIDL文件,而是据此而生成的一个IInterface的实例代码,AIDL其实是为了避免我们重复编写代码而出现的一个模板

设计AIDL这门语言的目的就是为了实现进程间通信。在Android系统中,每个进程都运行在一块独立的内存中,在其中完成自己的各项活动,与其他进程都分隔开来。可是有时候我们又有应用间进行互动的需求,比较传递数据或者任务委托等,AIDL就是为了满足这种需求而诞生的。通过AIDL,可以在一个进程中获取另一个进程的数据和调用其暴露出来的方法,从而满足进程间通信的需求

通常,暴露方法给其他应用进行调用的应用称为服务端,调用其他应用的方法的应用称为客户端,客户端通过绑定服务端的Service来进行交互

二、语法

AIDL的语法十分简单,与Java语言基本保持一致,需要记住的规则有以下几点:

  1. AIDL文件以 .aidl 为后缀名
  2. AIDL支持的数据类型分为如下几种:
    • 八种基本数据类型:byte、char、short、int、long、float、double、boolean
    • String,CharSequence
    • 实现了Parcelable接口的数据类型
    • List 类型。List承载的数据必须是AIDL支持的类型,或者是其它声明的AIDL对象
    • Map类型。Map承载的数据必须是AIDL支持的类型,或者是其它声明的AIDL对象
  3. AIDL文件可以分为两类。一类用来声明实现了Parcelable接口的数据类型,以供其他AIDL文件使用那些非默认支持的数据类型。还有一类是用来定义接口方法,声明要暴露哪些接口给客户端调用,定向Tag就是用来标注这些方法的参数值
  4. 定向Tag。定向Tag表示在跨进程通信中数据的流向,用于标注方法的参数值,分为 in、out、inout 三种。其中 in 表示数据只能由客户端流向服务端, out 表示数据只能由服务端流向客户端,而 inout 则表示数据可在服务端与客户端之间双向流通。此外,如果AIDL方法接口的参数值类型是:基本数据类型、String、CharSequence或者其他AIDL文件定义的方法接口,那么这些参数值的定向 Tag 默认是且只能是 in,所以除了这些类型外,其他参数值都需要明确标注使用哪种定向Tag。定向Tag具体的使用差别后边会有介绍
  5. 明确导包。在AIDL文件中需要明确标明引用到的数据类型所在的包名,即使两个文件处在同个包名下

三、服务端文件

1、传递简单信息

1.1.1首先创建aidl文件

点击main文件夹--->右击选中new----->选择AIDL----->AIDL File创建

在该文件中定义共享的参数

package com.example.broadcastreceiverdemo;

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

interface ICat {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
     //定义共享的参数
        String getColor();
        double getWeight();
}

创建完成之后,同步一下或者rebuild一下

1.1.2、创建传递信息的service类

package com.example.broadcastreceiverdemo;

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

import java.util.Timer;
import java.util.TimerTask;

import static android.content.ContentValues.TAG;

/**
 * Created by zhaoliang on 2018/7/27 0027
 */

public class AidlService extends Service {
    private String color;
    private double weight;
    Timer timer = new Timer();
    String[] colors = new String[]{
            "红色", "黄色", "黑色"
    };
    double[] weights = new double[]{
            2.3, 3.1, 1.58
    };
    private CatBinder catBinder;

    @Override
    public void onCreate() {
        super.onCreate();
        catBinder = new CatBinder();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
           //随机地改变service组件内color、weight属性值
                int rand = (int) (Math.random() * 3);
                color = colors[rand];
                weight = weights[rand];
                Log.i(TAG, "AIDL_onCreate");
            }
        }, 0, 800);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
/*
*1、在绑定本地service的情况下,该catbinder
对象会直接传给客户端的serviceConnection对象
的onserviceConnection方法的第二个参数
/2、在绑定远程service的情况下,该catbinder
对象会直接传给客户端的serviceConnection对象
的onserviceConnection方法的第二个参数
*
*
*/
        return new CatBinder();
    }
//继承stub也就是吸纳了ICat接口,并实现了IBinder接口
    public class CatBinder extends ICat.Stub {

        @Override
        public String getColor() throws RemoteException {
            return color;
        }

        @Override
        public double getWeight() throws RemoteException {
            return weight;
        }
    }

    @Override
    public void onDestroy() {
        timer.cancel();
    }
}

//别忘记注册
<service android:name=".AidlService">
       <intent-filter>
            <action android:name="com.example.broadcastreceiverdemo.AIDL_SERVICE" />
       </intent-filter>
        </service>

四、客户端文件

客户端需要在创建一个新的工程,包名可以随便起(也可以创建在统一个项目中new 一个module)

1.1.1、需要把服务端的AIDL文件复制过来,将 aidl 文件夹整个复制到和Java文件夹同个层级下,不需要改动任何代码

1.1.2、在Activity类中接收AIDL传递过来的信息

package com.example.broadcastreceiverdemo;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Toast;

import com.example.broadcastreceiverdemo.databinding.ActivityMainBinding;

/**
 * 接收AIDL传过来的值
 */
public class MainActivity extends Activity {
    ActivityMainBinding binding;
    private ICat catService;
    private ServiceConnection conn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        initAIDL();
    }

    private void initAIDL() {
        Intent intent = new Intent();
        intent.setAction("com.example.broadcastreceiverdemo.AIDL_SERVICE");//android5.0后无
//发使用隐式意图启动服务
intent.setPackage("com.example.broadcastreceiverdemo");//一定是AIDLService包的包名
        //获取远程service的onBind方法返回的对象的代理
        conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                //获取远程service的onBind方法返回的对象的代理
                catService = ICat.Stub.asInterface(service);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                catService = null;
            }
        };
        //绑定远程服务
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
        binding.btGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (catService != null) {
                        binding.tvColor.setText(catService.getColor());
                        binding.tvCount.setText(catService.getWeight() + "");
                    } else {
                        Toast.makeText(MainActivity.this, "AIDL传入的数据为空哦!!", Toast.LENGTH_SHORT).show();
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (conn != null) {
            unbindService(conn);
        }
    }
}

1.1.3运行的结果

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值