Android Studio下的一个AIDL实例

AIDL详细介绍传送门

在服务端定义AIDL接口

新建一个appservice项目

添加一个.aidl文件,右键 -> New -> AIDL -> AIDL File

在aidl文件中加入一个返回字符串的方法,完成之后build->make project

package com.example.appservice;

interface IMyAidlInterface {
    String getValue();
}

添加一个类MyService继承Service

public class MyService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return new MAIDLServiceImpl();
    }

    public class MAIDLServiceImpl extends com.example.appservice.IMyAidlInterface.Stub{
        @Override
        public String getValue() throws RemoteException {
            return "成功连上服务端";
        }
    }

}

在.xml文件中对service进行配置,添加代码

<service
    android:name=".MyService"
    android:process=":remote"
    android:exported="true">
<intent-filter>
    <category android:name="android.intent.category.DEFAULT" />
    <action android:name="com.example.appservice.IMyAidlInterface" />
</intent-filter>
</service>

在客户端调用接口

新建一个项目appclient

将服务端的aidl文件夹复制粘贴过来,build->make project

修改MainActivity代码

public class MainActivity extends AppCompatActivity {
    private Button btCallAIDL;
    private IMyAidlInterface aidlService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btCallAIDL = (Button) findViewById(R.id.bt_call_aidl);
        // 点击按钮绑定服务端的服务
        btCallAIDL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.appservice.IMyAidlInterface"); // 参数为服务端的Service的action的name参数的值
                intent.setPackage("com.example.appservice"); // 参数为服务端的包名
                bindService(intent, new MyConnection(), BIND_AUTO_CREATE);// 绑定Service
            }
        });
    }

    private class MyConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            aidlService = IMyAidlInterface.Stub.asInterface(service);// 获得服务端的RemoteInterface的对象。
            try {
                String str = aidlService.getValue();// 调用服务端的方法
                Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

}

效果展示图

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值