android AIDL示例代码(mark下)

1.demo结构图

 

2.ipcclient

  Book类。

package com.mu.guoxw.ipcclient;

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

/**
 * Created by guoxw on 2018/3/21.
 */

public class Book implements Parcelable {
    public String getName() {
        return name;
    }

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

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    private String name;

    private int price;

    public Book(){}

    public Book(Parcel in) {
        name = in.readString();
        price = in.readInt();
    }

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

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

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

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

    /**
     * 参数是一个Parcel,用它来存储与传输数据
     * @param dest
     */
    public void readFromParcel(Parcel dest) {
        //注意,此处的读值顺序应当是和writeToParcel()方法中一致的
        name = dest.readString();
        price = dest.readInt();
    }

    //方便打印数据
    @Override
    public String toString() {
        return "name : " + name + " , price : " + price;
    }
}

 Book.aidl

// Book.aidl
package com.mu.guoxw.ipcclient;

// Declare any non-default types here with import statements
parcelable Book;

  BookManager.aidl

package com.mu.guoxw.ipcclient;
 import com.mu.guoxw.ipcclient.Book;
// Declare any non-default types here with import statements

interface BookManager {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    List<Book>getBooks();
    void addBook(inout Book book);
    Book getBook();
}

 

gradle

android {
    
    sourceSets {
        main {
            java.srcDirs = ['src/main/java', 'src/main/aidl']
        }
    }

}

  

 

MainActivity

package com.mu.guoxw.ipcclient;

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.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private BookManager mBookManager = null;

    private boolean mBound = false;

    //包含Book对象的list
    private List<Book> mBooks;

    Button btn_add;
    TextView text;


    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBookManager = BookManager.Stub.asInterface(service);
            mBound = true;
            if (mBookManager != null) {
                try {
                    mBooks = mBookManager.getBooks();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(getLocalClassName(), "service disconnected");
            mBound = false;
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_add=findViewById(R.id.btn_add);
        text=findViewById(R.id.text);

        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                addBook();
            }
        });

    }




    /**
     * 按钮的点击事件,点击之后调用服务端的addBookIn方法
     *
     */
    public void addBook() {
        if (!mBound) {
            attemptToBindService();
            Toast.makeText(this, "当前与服务端处于未连接状态,正在尝试重连,请稍后再试", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mBookManager == null) return;

        Book book = new Book();
        book.setName("测试app_A");
        book.setPrice(30);
        try {
            mBookManager.addBook(book);
            Log.e("aidl:","client端_添加数据"+ book.toString());

            List<Book> mbooks=mBookManager.getBooks();
            for (int i=0;i<mbooks.size();i++){
                if(mbooks.get(i)!=null){
                    Log.e("aidl:", "addBook: cleint端_打印:"+mbooks.get(i).toString() );
                }
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 尝试与服务端建立连接
     */
    private void attemptToBindService() {
        Intent intent = new Intent();
        intent.setAction("com.multak.guoxw.ipcservertest.service.aidl");
        intent.setPackage("com.multak.guoxw.ipcservertest");
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!mBound) {
            attemptToBindService();
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        super.onStop();
        if (mBound) {
            unbindService(mServiceConnection);
            mBound = false;
        }
    }
}

 3:ipcServerTest

    Book.aidl

package com.mu.guoxw.ipcclient;
import com.mu.guoxw.ipcclien.Book;
// Declare any non-default types here with import statements
parcelable Book;

  BookManager.aidl

// BookManager.aidl
package com.mu.guoxw.ipcclient;
import com.mu.guoxw.ipcclient.Book;

interface BookManager {

    List<Book> getBooks();
    void addBook(inout Book book);
    Book getBook();
}

  

  AIDLService

package com.mu.guoxw.ipcservertest.service;

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.mu.guoxw.ipcclient.Book;
import com.mu.guoxw.ipcclient.BookManager;

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

public class AIDLService extends Service {


    private List<Book> mBooks=new ArrayList<>();

    public AIDLService() {
    }


    private final BookManager.Stub bookManager=new BookManager.Stub() {
        @Override
        public List<Book> getBooks() throws RemoteException {
            synchronized (this){
                if (mBooks != null) {
                    return mBooks;
                }
                return new ArrayList<>();
            }
        }

        @Override
        public void addBook(Book book) throws RemoteException {
            synchronized (this){
                if (mBooks == null) {
                    mBooks = new ArrayList<>();
                }
                if (book == null) {
                    book = new Book();
                }
                book.setPrice(2333);
                Log.e("aidl:", " service端_修改数据 "+book.toString());
                if (!mBooks.contains(book)) {
                    mBooks.add(book);
                }
            }
        }

        @Override
        public Book getBook() throws RemoteException {
            return null;
        }


    };




    @Override
    public void onCreate() {
        Book book = new Book();
        book.setName("Android开发艺术探索");
        book.setPrice(28);
        mBooks.add(book);
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(getClass().getSimpleName(), String.format("on bind,intent = %s", intent.toString()));
        return bookManager;
    }
}

  

MessengerService[没用]
package com.mu.guoxw.ipcservertest.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.support.annotation.Nullable;

public class MessengerService extends Service {
    private static final int SAY_HOLLE = 0;

    static class ServiceHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SAY_HOLLE:
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    }

    final Messenger mMessenger = new Messenger(new ServiceHandler());

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("binding");
        return mMessenger.getBinder();
    }
}

  Book

package com.mu.guoxw.ipcclient;

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


/**
 * Created by guoxw on 2018/3/21.
 */

public class Book implements Parcelable {


    public String getName() {
        return name;
    }

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

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }



    private String name;
    private int price;

    public Book() {
    }
    protected Book(Parcel in) {
        name = in.readString();
        price = in.readInt();

    }


    public static Creator<Book> getCREATOR() {
        return CREATOR;
    }



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

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

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

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

    public void readFromParcel(Parcel dest) {
        name = dest.readString();
        price = dest.readInt();

    }

    //方便打印数据
    @Override
    public String toString() {
        return "name : " + name + " , price : " + price;
    }
}

  4.注册

  <service
            android:name=".service.AIDLService"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="com.multak.guoxw.ipcservertest.service.aidl"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </service>

        <service
            android:name=".service.MessengerService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.lypeer.messenger"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </service>

 

 5.code:AIDL_demo

链接: https://pan.baidu.com/s/1ExGhr3U9MAgqR_kpBeGqCQ 

  

  

链接:https://pan.baidu.com/s/1h6sKauYDr-Kbl4ay2DnRzQ 
  提取码:q37o

 

6:

 

1:client 和server 的aidl文件包名要保持一致
2:通常使用时,应该是双向通信,在使用时在client端也加入service,接受server端处理后的结果
3: targetSdkVersion >= 30 的时候,需要在配置文件加入需要进来交互的app的applicationId。如下:

 

<manifest> 
... <queries> <package android:name="com.example.binder_client"/> // 如果是client端,需要与server端交互,这里的package name要写server端demo的applicationid </queries>
... </manifest>

  

  

 

 

 

 

posted @ 2018-03-22 19:20  咖喱不见不散啊  阅读(275)  评论(0编辑  收藏  举报