关于AIDL的简单认识

什么是AIDL

AIDL是Android Interface Definition Language, 顾名思义,它主要就是用来定义接口的一种语言。Android提供AIDL主要用来进程

间通讯。


如何使用AIDL


1).创建aidl文件

    .  在main文件下新建aidl文件夹

    .  创建aidl类

    .  例如


2).编写aidl接口

package com.example.myapplication;

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

interface IMyService {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
    double doCalculate(double a,double b);



3).如果使用Eclipse,Eclipse会自动在gen目录下生成对应的.java文件,如果是studio,点击Build中make Module 'AIDL'添加到编译

文件中。


4).编写Activity类,点击按钮在服务中实现两个数相加。

package com.example.myapplication;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Created by lenovo on 2017/12/3.
 */

public class Person extends Activity {
    private static final String TAG = "CalculateClient";

    private Button btnCalculate;

    private EditText etNum1;

    private EditText etNum2;

    private TextView tvResult;

    private IMyService mService;

    private ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            //logE("disconnect service");
            mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            //logE("connect service");
            mService = IMyService.Stub.asInterface(service);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle args = new Bundle();
        Intent intent = new Intent(this, RemoteService.class);
        intent.putExtras(args);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

        etNum1 = (EditText) findViewById(R.id.et_num_one);
        etNum2 = (EditText) findViewById(R.id.et_num_two);

        tvResult = (TextView) findViewById(R.id.tv_result);

        btnCalculate = (Button) findViewById(R.id.btn_cal);

        btnCalculate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                //logE("开始远程运算");
                try {
                    double num1 = Double.parseDouble(etNum1.getText().toString());
                    double num2 = Double.parseDouble(etNum2.getText().toString());
                    String answer = "计算结果:" + mService.doCalculate(num1, num2);
                    tvResult.setTextColor(Color.BLUE);
                    tvResult.setText(answer);

                } catch (RemoteException e) {
                }
            }
        });
    }

//    private void logE(String str) {
//        Log.e(TAG, "--------" + str + "--------");
//    }

}


5).最后编写服务类

package com.example.myapplication;

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.LinkedList;
import java.util.List;

/**
 * Created by lenovo on 2017/12/3.
 */

public class RemoteService extends Service {

    private static final String                            TAG                        =    "CalculateService";

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        logE("onBind()");
        return mBinder;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        logE("onCreate()");
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        logE("onStart()");
        super.onStart(intent, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // TODO Auto-generated method stub
        logE("onUnbind()");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        logE("onDestroy()");
        super.onDestroy();
    }

    private static void logE(String str) {
        Log.e(TAG, "--------" + str + "--------");
    }

    private final IMyService.Stub mBinder = new IMyService.Stub() {

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public double doCalculate(double a, double b) throws RemoteException {
            return a+b;
        }

//        @Override
//        public double doCalculate(int a, int b) throws RemoteException {
//            return a+b;
//        }

//        @Override
//        public double doCalculate(double a, double b) throws RemoteException {
//            // TODO Auto-generated method stub
//            Log.e("Calculate", "远程计算中");
//            Calculate calculate = new Calculate();
//            double answer = calculate.calculateSum(a, b);
//            return answer;
//        }
    };

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值