一个app需要调用第三方app提供的服务,除了提供jar,aar,contentprovider,activity跳转,scheme跳转,广播发送,还可以通过aidl (Android Interface Definition Language,即Android接口定义语言),通过service对外提供服务,底层原理是使用android系统的Binder,进行进程间的通信。

        本次试验,通过一个叫learn的app提供两个接口服务,1.判断用户名密码是否正确  2.返回用户信息,使用了简单对象和自定义对象两种实现方式,然后另外一个叫test的app来调用learn提供的服务,试验发现如果learn进程没有在运行,那么test是无法调起learn提供的服务的。所以aidl有这个局限性。提供sdk一般通过aar提供接口服务比较好。

       注意事项:在learn服务提供方,定义的aidl和类,在test项目中,包名必须和learn中一致,否则无法调起。

       一、服务端

关于aidl的创建,项目右键-->new-->AIDL-->AIDL file

 

       1.定义aidl

       

服务接口定义IUserAidlInterface.aidl
// IUserAidlInterface.aidl
package com.figo.learn;

// Declare any non-default types here with import statements
import com.figo.learn.User;
interface IUserAidlInterface {
    /**
     * 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);
    boolean isUserPwdRight(String name,String pwd);

     User getUserInfo(String name);
}

        自定义对象User.aidl

// User.aidl
package com.figo.learn;
parcelable User;

        注意自定义类User.java的包名和aidl所在的包名必须一致

package com.figo.learn;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * 可序列化用户类
 */
public class User implements Parcelable {
    private String userName;
    private String sex;
    private  int age;
    private  String mobile;
    private  String address;
    public User()
    {

    }
    protected User(Parcel in) {
        userName = in.readString();
        sex = in.readString();
        age = in.readInt();
        mobile = in.readString();
        address = in.readString();
    }

    public static final Creator<User> CREATOR = new Creator<User>() {
        @Override
        public User createFromParcel(Parcel in) {
            return new User(in);
        }

        @Override
        public User[] newArray(int size) {
            return new User[size];
        }
    };

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(userName);
        dest.writeString(sex);
        dest.writeInt(age);
        dest.writeString(mobile);
        dest.writeString(address);
    }
    public void readFromParcel(Parcel dest) {
        //注意,此处的读值顺序应当是和writeToParcel()方法中一致的
        userName = dest.readString();
        sex = dest.readString();
        age = dest.readInt();
        mobile = dest.readString();
        address = dest.readString();
    }

    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", mobile='" + mobile + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

          这时候,再Build-->ReBuild Project,就会自动生成相关的stub了。

      2.创建service,且注册到androidmanifest.xml

 

UserService.java
package com.figo.learn.service;


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

import com.figo.learn.IUserAidlInterface;
import com.figo.learn.User;

public class UserService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return new UserBinder();
    }
    public class UserBinder extends IUserAidlInterface.Stub
    {

        @Override
        public boolean isUserPwdRight(String name, String pwd) throws RemoteException {
            //这里可以写查询后台逻辑,演示就直接判断了
            if("admin".equals(name)&&"123456".equals(pwd))
            {
                return true;
            }else {
                return false;
            }
        }

        @Override
        public User getUserInfo(String name) throws RemoteException {
            User user=new User();
            if("admin".equals(name))
            {
                user.setUserName("张三");
                user.setAge(18);
                user.setAddress("上海");
                user.setMobile("15812345678");
                user.setSex("男");
            }
            return user;
        }
    }
}

注册服务

    <service
            android:name=".service.UserService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.figo.learn.user"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </service>

         二.在test项目的客户端

1.将aidl和自定义类,learn中一样的包名,copy过来

同样的rebuild一下项目 

2.测试远程调用

AidlTestActivity.java
package com.figo.test.activity;

import androidx.appcompat.app.AppCompatActivity;

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.view.View;
import android.widget.Toast;

import com.figo.learn.IUserAidlInterface;
import com.figo.learn.User;
import com.figo.test.R;

public class AidlTestActivity extends AppCompatActivity {
    private IUserAidlInterface iUserAidlInterface;
    private ServiceConnection conn=new ServiceConnection()
    {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            Toast.makeText(AidlTestActivity.this, "远程服务已经连接,iUserAidlInterface创建成功", Toast.LENGTH_LONG).show();
            iUserAidlInterface = IUserAidlInterface.Stub.asInterface(service);
            if(iUserAidlInterface!=null)
            {
                String userName = "admin";
                String pwd = "123abc";
                boolean isPwdRight = false;
                User user=null;
                try {
                    isPwdRight = iUserAidlInterface.isUserPwdRight(userName, pwd);
                    user=iUserAidlInterface.getUserInfo("admin");
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                if (isPwdRight) {
                    Toast.makeText(AidlTestActivity.this, "用户名密码匹配", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(AidlTestActivity.this, "用户名密码不匹配", Toast.LENGTH_LONG).show();
                }

                if (user!=null) {
                    Toast.makeText(AidlTestActivity.this, "获取到用户信息"+user.toString(), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(AidlTestActivity.this, "未获取到用户信息", Toast.LENGTH_LONG).show();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name)
        {
            iUserAidlInterface=null;
            Toast.makeText(AidlTestActivity.this, "远程服务已经断开", Toast.LENGTH_LONG).show();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aidl_test);
        //this.bindService();

    }

    private void bindService()
    {
        Intent intent=new Intent();
        intent.setAction("com.figo.learn.user");
        intent.setPackage("com.figo.learn");
        bindService(intent, conn , BIND_AUTO_CREATE);
    }

    public void aidlServiceTest(View view)
    {

        try {
            //如果onCreate未连接成功,再次连接一下看看
//            if(iUserAidlInterface==null)
//             {
//                 this.bindService();
//             }else {
//                if (iUserAidlInterface != null) {
//
//                } else {
//                    Toast.makeText(AidlTestActivity.this, "iUserAidlInterface未创建成功", Toast.LENGTH_LONG).show();
//                }
//            }
            bindService();
         }catch (Exception e)
         {
             e.printStackTrace();
         }

    }

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

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐