Android AIDL 代码

 

不啰嗦,直接code。

Server:

目录结构:

Person.aidl

// Person.aidl
package com.hades.xq.aidlserver.bean;

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

parcelable Person ;
PersonController.aidl
// PersonController.aidl
package com.hades.xq.aidlserver;
import com.hades.xq.aidlserver.bean.Person;

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

interface PersonController {

    List<Person> getPersonList();

    void addPersonInOut(inout Person person);
}

 

Person.java
package com.hades.xq.aidlserver.bean;

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

/**
 * @Package com.hades.xq.aidlserver.bean
 * @FileName Person
 * @Date 2018/9/7 14:58
 * @Author Ares
 * @Description //TODO
 * @Version V2.0.2
 * @UpdateVersion V2.0.2
 */
public class Person implements Parcelable {

    public Person() {
    }

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

    private String name;

    private int age;

    /**
     * 0 gril,1 boy
     */
    private int sex;

    /**
     * 此方法很重要
     * @param dest
     */
    public void readFromParcel(Parcel dest) {
        name = dest.readString();
        age = dest.readInt();
        sex = dest.readInt();
    }

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

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

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

    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;
    }

    public int getSex() {
        return sex;
    }

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

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

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

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                '}';
    }
}
package com.hades.xq.aidlserver.server;

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 com.hades.xq.aidlserver.PersonController;
import com.hades.xq.aidlserver.bean.Person;

import java.util.ArrayList;
import java.util.List;

/**
 * @Package com.hades.xq.aidlserver.server
 * @FileName AidlServer
 * @Date 2018/9/7 18:32
 * @Author Ares
 * @Description //TODO
 * @Version V2.0.2
 * @UpdateVersion V2.0.2
 */
public class AidlServer extends Service {

    private final String  TAG = "TAG";

    private List<Person> personList = null;

    public AidlServer() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        personList = new ArrayList<>();
        initData();
    }

    private void initData() {
        Log.i(TAG, "AidlServer.initData");
        Person person =new  Person();
        person.setAge(12);
        person.setName("tom");
        person.setSex(1);
        personList.add(person);
    }

    private PersonController.Stub stub = new PersonController.Stub(){
        @Override
        public List<Person> getPersonList() throws RemoteException {
            return personList;
        }

        @Override
        public void addPersonInOut(Person person) throws RemoteException {
            if (person != null) {
                personList.add(person);
            } else {
                Log.e(TAG, "接收到了一个空对象 InOut");
            }
        }
    };


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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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=".server.AidlServer"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.hades.xq.aidlserver.action" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </service>
    </application>

</manifest>

Client:

package com.hades.xq.clinet

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.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import com.hades.xq.aidlserver.PersonController
import com.hades.xq.aidlserver.bean.Person
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), View.OnClickListener {

    private val TAG = "TAG"

    private var connected: Boolean = false

    private lateinit var personController: PersonController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn_getList.setOnClickListener(this)
        btn_add_inOut.setOnClickListener(this)
        bindService()
    }


    private fun getList() {
        Log.i(TAG, "getList start")
        if (connected) {
            val list = personController.personList
            Log.i(TAG, "list.size -->${list.size} ")
            list.forEach {
                Log.i(TAG, it.toString())
            }
        } else {
            Log.i(TAG, "客户端获取列表失败! ")
        }
    }

    private fun addPerson() {
        Log.i(TAG, "addPerson start")
        if (connected) {
            val person = Person()
            person.sex = 0
            person.age = 22
            person.name = "lily"
            personController.addPersonInOut(person)
            Log.i(TAG, "客户端添加成功!$person")
        } else {
            Log.i(TAG, "客户端添加失败! ")
        }
    }

    private fun bindService() {
        val intent = Intent()
        intent.setPackage("com.hades.xq.aidlserver")
        intent.setAction("com.hades.xq.aidlserver.action")
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (connected) {
            unbindService(serviceConnection)
        }
    }

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            connected = false
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            service?.let {
                personController = PersonController.Stub.asInterface(service)
                connected = true
            }
        }
    }

    override fun onClick(v: View?) {
        v?.let {
            when (v?.id) {
                R.id.btn_getList -> {
                    getList()
                }
                R.id.btn_add_inOut -> {
                    addPerson()
                }
            }
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_getList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="获取列表" />

    <Button
        android:id="@+id/btn_add_inOut"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="InOut 添加书" />

</LinearLayout>

PS: 原本Server用kotlin写,发现一个莫名其妙的问题,后来改Java没问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值