Android IPC进程间通信

IPC是Inter-Process Communication的缩写,含义为进程间通信或者跨进程通信,是指两个进程之间进行数据交换的过程。
进程间通信方式:Bundle、文件共享、AIDL、Messenger、ContentProvider、Socket
一.AIDL:Android Interface Definition Language
1.1创建一个aidl文件

interface XsyAidlInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
    String getName(String name);
}

1.2创建一个Service用来监听客户端连接请求,实现里面方法

public class AidlService extends Service {

    XsyAidlInterface.Stub mStub = new XsyAidlInterface.Stub() {
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public String getName(String name) throws RemoteException {
            return "-----aidl-----" + name;
        }
    };

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

1.3绑定服务端的Service,绑定成功后,将服务端返回的Binder对象转成AIDL接口所属的类型,接着就可以调用AIDL中的方法了

public class MainActivity extends AppCompatActivity {
    private XsyAidlInterface xsyAidlInterface;

    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            xsyAidlInterface = XsyAidlInterface.Stub.asInterface(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
    private TextView tvAIDL;


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

        initAIDL();
    }

    private void initAIDL() {

        bindService(new Intent(this, AidlService.class), serviceConnection, BIND_AUTO_CREATE);


        tvAIDL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String name = xsyAidlInterface.getName("success,hahahhaha");
                    Toast.makeText(MainActivity.this, "test = " + name, Toast.LENGTH_SHORT).show();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }
}
发布了40 篇原创文章 · 获赞 37 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/sanyang730/article/details/89081091