Android Studio AIDL进行IPC通信的使用步骤

1.新建IMyAidlInterface.aidl、Person.aidl文件


// IMyAidlInterface.aidl
package demo.com.aidldemo;
import demo.com.aidldemo.Person;
interface IMyAidlInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    String getString(String string);
    List<Person> getPersonList();
}




// Person.aidl
package demo.com.aidldemo;
parcelable Person;






2.服务端 MyService.java


package demo.com.aidldemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.SystemClock;


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




public class MyService extends Service {
    public MyService() {
    }




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


    IMyAidlInterface.Stub mBinder;




    {
        mBinder = new IMyAidlInterface.Stub() {
            @Override
            public String getString(String string) throws RemoteException {
                return string;
            }




            @Override
            public List<Person> getPersonList() throws RemoteException {
                Person p = new Person("p1",10,1l,90);
                Person p2 = new Person("p2",12,2l,92);




                List<Person> list = new ArrayList<>();
                list.add(p);
                list.add(p2);




                return list;
            }
        };
    }
}


3.IPC传输的对象类Person.java
package demo.com.aidldemo;


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


public class Person implements Parcelable {


    private String name;
    private int age;
    private long workingDay;
    private double money;


    public Person(String name, int age, long workingDay, double money) {
        this.name = name;
        this.age = age;
        this.workingDay = workingDay;
        this.money = money;
    }


    protected Person(Parcel in) {
        name = in.readString();
        age = in.readInt();
        workingDay = in.readLong();
        money = in.readDouble();
    }


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


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


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


    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", workingDay=" + workingDay +
                ", money=" + money +
                '}';
    }
}
4.清单文件配置,让服务端启动在其他进程


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


    <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:process=":remote"
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="demo.com.aidldemo.MyService" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>


        </service>
    </application>


</manifest>






5.客户端调用


package demo.com.aidldemo;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    private IMyAidlInterface myAidlInterface;


    TextView textView,textView2;
    Button button, button2;


    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {




            myAidlInterface = IMyAidlInterface.Stub.asInterface(service);




        }


        @Override
        public void onServiceDisconnected(ComponentName name) {


        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




        //使用意图对象绑定开启服务
        Intent intent = new Intent();
       //在5.0及以上版本必须要加上这个
        intent.setPackage("demo.com.aidldemo");
        intent.setAction("demo.com.aidldemo.MyService");//这个是上面service的action
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);






        textView = findViewById(R.id.textView);
        textView2 = findViewById(R.id.textView2);
        button= findViewById(R.id.button);


        button2= findViewById(R.id.button2);


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(myAidlInterface != null) {


                        textView.setText(myAidlInterface.getString("Hello AIDL"));
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });




        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(myAidlInterface != null) {


                        textView2.setText(myAidlInterface.getPersonList().toString());
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();


        if (mServiceConnection != null){
            unbindService(mServiceConnection);
        }
    }
}
6.布局文件


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Hello World!"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:text="调用服务端方法"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />


    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />


    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:text="调用服务端获取对象集合方法"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />


</android.support.constraint.ConstraintLayout>


猜你喜欢

转载自blog.csdn.net/wangwangli6/article/details/80095174