进程间通信AIDL

前言:之前进程间通信messenger写过了,今天再温习下AIDL,AIDL(Android Interface Definition Language,Android接口定义语言),不推荐使用AIDL创建一个绑定服务,因为实现复杂

1.创建AIDL,as对AIDL的支持非常好

进程间通信AIDL_第1张图片


进程间通信AIDL_第2张图片


getName方法是我自己加上去的,basicTypes是自动生成的

进程间通信AIDL_第3张图片


然后Rebuild Project


进程间通信AIDL_第4张图片


然后可以使用了,自定义一个AIDLSerivce继承自Service,代码如下

/**
 * Created by chen on 2018
 */

public class AIDLService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyIBinder();
    }

    class MyIBinder extends IMyAidlInterface.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 name;
        }
    }
}


记得在清单文件中声明这个服务在新进程中

    

如果需要在当前应用包名后加新的主观的名字可以这样,加了一个冒号,意思是项目包名为cn.chen,新进程名为cn.chen.com.aidl.chenad.service

  

再创建一个AIDLActivity来绑定这个远程服务

public class AIDLActivity extends AppCompatActivity {
    private static final String TAG = "duo_shine";
    private IMyAidlInterface mIMyAidlInterface;

    ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mIMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

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

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, AIDLService.class);
        bindService(intent, mConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(mConnection);
    }

    public void chenad(View view) {
        try {
            String chenad = mIMyAidlInterface.getName("chenad");
            Toast.makeText(this, chenad, Toast.LENGTH_SHORT).show();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(进程通信)