android AIDL示例代碼(mark下)

1.demo結構圖java

 

2.ipcclientandroid

  Book類。app

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.aidlide

// 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();
}

  MainActivitythis

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:ipcServerTestspa

    Book.aidlcode

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

  BookManager.aidlorm

// 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();
}

  

  AIDLServiceserver

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 
相關文章
相關標籤/搜索