Android进阶之路Android技术知识Android开发

AIDL简单例子

2019-03-23  本文已影响8人  奔跑吧李博
AIDL (Android Interface Definition Language), Android接口定义语言,Android提供的IPC (Inter Process Communication,进程间通信)的一种独特实现。
实现AIDL调用示例:
1.AIDL公用接口端:

在main下建立aidl包,在项目路径下建立aidl接口,以aidl结尾

package com.example.apple.aidluse;
import com.example.apple.aidluse.UserBean;

interface IGetUser {
    UserBean getUserBean();
}
2.创建UserBean实体类,需要实现Parcelable。
import android.os.Parcel;
import android.os.Parcelable;

public class UserBean implements Parcelable{
    private String name;
    private int age;

    public UserBean(String name, int age) {
        this.name = name;
        this.age = age;
    }


    protected UserBean(Parcel in) {
        name = in.readString();
        age = in.readInt();
    }

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

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

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

3.创建UserBean.aidl
package com.example.apple.aidluse;
parcelable UserBean;
4.创建Service类
public class UserService extends Service{

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

    //使用IGetUser之前,需要编译或运行一下,不然找不到接口
    private Binder binder = new IGetUser.Stub(){

        @Override
        public UserBean getUserBean(){
            return new UserBean("小王",23);
        }
    };
}
5.注册UserService
        <service android:name=".UserService"
            android:exported="true"
            android:enabled="true" >
            <intent-filter>
                <action android:name="com.example.apple.aidluse.UserService" />
            </intent-filter>
        </service>
客户端
1.创建ServiceConnection对象,绑定服务连接上Service后,使用IBinder对象,IGetUser.Stub.asInterface(service)获取接口,调用接口方法远程调用服务端的方法进行处理,获取想要的结果。
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            IGetUser iGetUser = IGetUser.Stub.asInterface(service);
            try {
                UserBean userBean = iGetUser.getUserBean();
                Toast.makeText(getApplication(),userBean.getName() + "------" + userBean.getAge(),Toast.LENGTH_SHORT).show();

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

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
2.启动服务端:
    public void startService(View view) {
        Intent intent = new Intent(this, UserService.class);
        startService(intent);
    }
3.客户端绑定服务端:
    public void bindService(View view) {
        Intent intent1 = new Intent();
        intent1.setAction("com.example.apple.aidluse.UserService");
        Intent explicitIntent = createExplicitFromImplicitIntent(this,intent1);
        bindService(explicitIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) {
        // Retrieve all services that can match the given intent
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);

        // Make sure only one match was found
        if (resolveInfo == null || resolveInfo.size() != 1) {
            return null;
        }

        // Get component info and create ComponentName
        ResolveInfo serviceInfo = resolveInfo.get(0);
        String packageName = serviceInfo.serviceInfo.packageName;
        String className = serviceInfo.serviceInfo.name;
        ComponentName component = new ComponentName(packageName, className);

        // Create a new intent. Use the old one for extras and such reuse
        Intent explicitIntent = new Intent(implicitIntent);

        // Set the component to be explicit
        explicitIntent.setComponent(component);

        return explicitIntent;
    }

这里是github代码直通车

上一篇下一篇

猜你喜欢

热点阅读