AIDL如何使用

配置android环境 如果出现jdk1.8无法使用

![在这里插入图片描述](https://img-blog.csdnimg.cn/6acfb230baec4b77875204b6b9e894a8.png
在这里插入图片描述

服务器端代码

创建aidl
在这里插入图片描述
创建aidl的代码

// ICat.aidl
package com.example.myapplication;

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

interface ICat {
    String getColor();
    double getWeight();
}
在这里插入代码片

build时,SDK会自动构建下面两个文件ICat
在这里插入图片描述
然后创建AidlService对象

package com.example.myapplication;

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

import androidx.annotation.Nullable;

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

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

    class CatBinder extends ICat.Stub {//关键的地方ICat.Stub继承了Binder可以实现跨进程通信

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

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

    @Override
    public void onCreate() {
        super.onCreate();
        catBinder = new CatBinder();
        timer.schedule(new TimerTask() {
            //启动一个线程每0.8秒钟执行一下这个方法
            @Override
            public void run() {
                int rand = (int) (Math.random() * 3);
                color = colors[rand];
                weight = weights[rand];
            }
        },0,800);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return catBinder;
    }
}

package com.example.service2;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.myapplication.ICat;

public class MainActivity extends AppCompatActivity {
    private ICat catService;
    private ServiceConnection conn = new ServiceConnection() {
         @Override
        public String getColor() throws RemoteException {
            return color;
        }

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button viewById = (Button) findViewById(R.id.button);
        TextView viewById1 = (TextView) findViewById(R.id.textView);
        TextView viewById2 = (TextView) findViewById(R.id.button);

        Intent intent = new Intent();
        intent.setAction("com.example.myapplication.AIDL_SERVICE");
        intent.setPackage("com.example.myapplication");
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
        viewById.setOnClickListener(view -> {
            viewById1.setText("颜色" + catService.getColor());
            viewById2.setText("体重" + catService.getWeight());
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
    }
}

客户端

aidl文件,需要把服务器端的整个文件夹复制过来,用project类型打开,不要用android项目打开,然后build一下就可以了
布局文件的xml,看一下最后的截图你就可以理解了

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.myapplication.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_editor_absoluteX="143dp"
        tools:layout_editor_absoluteY="185dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        tools:layout_editor_absoluteX="176dp"
        tools:layout_editor_absoluteY="277dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        tools:layout_editor_absoluteX="176dp"
        tools:layout_editor_absoluteY="277dp" />
</LinearLayout>

客户端代码,bindService老是不成功折磨了我好久

package com.example.myapplication;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.ICat;


public class MainActivity extends AppCompatActivity {
    private ICat catService;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            catService = ICat.Stub.asInterface(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            catService = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button viewById = (Button) findViewById(R.id.button);
        TextView viewById1 = (TextView) findViewById(R.id.textView);
        TextView viewById2 = (TextView) findViewById(R.id.button);

        Intent intent = new Intent();
        intent.setAction("com.example.myapplication.AIDL_SERVICE");
        intent.setPackage("com.example.myapplication");
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
        viewById.setOnClickListener(view -> {
            try {
                viewById1.setText("颜色" + catService.getColor());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                viewById2.setText("体重" + catService.getWeight());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
    }
}

总是拿不到service里提供的数据color,weight,也就是bindService不成功,因为没有在client端的AndroidManifest.xml配置queries标签去声明service与其交互的包名,配置后就可以拿到服务端app AidlService提供的数据color,weight了.

    <queries>
        <package android:name="com.example.myapplication" />
    </queries>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值