Android AIDL进程间通信介绍

  1. 前言

通过给四大组件指定android:process属性,我们则可以轻易的开启多进程模式,但是Android系统中的进程之间不能共享内存,但是很多时候,不同进程之间是要通信的,这个时候就要用到AIDL进程间通信。

2.使用步骤

(1) 创建.aidl文件,在这里面定义远程接口。在项目名称上右键>New>AIDL>AIDL File,这样就创建了一个ADIL文件,命名为CalculateInterface

这里写图片描述

package com.test.aidl;

interface CalculateInterface{
    double doCalculate(double a, double b);
}

(2)生成Java接口文件。
在菜单中选择Build>Rebulid Project,这样就生成了java接口文件,地址在项目文件夹/app/build/generated/source/aidl里面。如图所示:

这里写图片描述
(3) 建立一个Service的子类

package com.test.aidl;

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

public class CalculateService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }


    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private final CalculateInterface.Stub mBinder = new CalculateInterface.Stub() {
        @Override
        public double doCalculate(double a, double b) throws RemoteException {
            double answer = a+b;
            return answer;
        }
    };
}

(4) 用BindService来调用Service

package com.test.aidl;

import android.app.Activity;
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.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends Activity {

    /**
     * 计算
     */
    private Button calculate;

    /**
     * 输入值
     */
    private EditText input_a, input_b;

    /**
     * 计算结果
     */
    private TextView result;

    private CalculateInterface mService;

    private ServiceConnection mServiceConnection = new ServiceConnection() {

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

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = CalculateInterface.Stub.asInterface(service);
        }
    };

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

        bindService();
        init();
    }


    /**
     * 初始化布局组件
     */
    private void init() {
        input_a = (EditText) findViewById(R.id.input_a);
        input_b = (EditText) findViewById(R.id.input_b);
        calculate = (Button) findViewById(R.id.calculate);
        result = (TextView) findViewById(R.id.result);

        calculate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    double num1 = Double.parseDouble(input_a.getText().toString());
                    double num2 = Double.parseDouble(input_b.getText().toString());
                    String answer = "计算结果为:" + mService.doCalculate(num1, num2);
                    result.setText(answer);
                } catch (RemoteException e) {
                }
            }
        });
    }

    /**
     * 绑定service
     */
    private void bindService() {
        Bundle args = new Bundle();
        Intent intent = new Intent("com.example.calculate.CalculateService");
        intent.setPackage("com.test.aidl");
        intent.putExtras(args);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }
}

(5) 在AndroidManifest.xml文件中配置相关信息

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.test.aidl">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <service
            android:name=".CalculateService"
            android:enabled="true"
            android:exported="true"
            android:process=":core">
            <intent-filter>
                <action android:name="com.example.calculate.CalculateService"/>
            </intent-filter>
        </service>
    </application>

</manifest>

3.细节讲解

从AndroidManifest.xml文件中可以看到,CalculateService跟MainActivity不在同一个进程中,CalculateService通过设置android:process=":core",而运行在core进程。下面我们运行程序,通过adb shell来查看当前的进程情况:

这里写图片描述
(查看进程的方法不了解的,可以看这篇文章:http://blog.csdn.net/dfskhgalshgkajghljgh/article/details/51373694)
很明显,当前程序有两个进程。
上面的代码实现的就是,模拟出两个数字相加,但是相加的算法过程在另外一个进程,及core进程中,但是在主进程中调用该算法,并返回数值。这种场景很常见,一个应用多个进程,其中某个进程专门处理一些算法操作,其他进程与他交互。
界面如下所示:

这里写图片描述这里写图片描述

4.项目地址

http://download.csdn.net/detail/dfskhgalshgkajghljgh/9564713


如有错误欢迎指出来,一起学习。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值