Android中AIDL的使用的案例

来源:互联网 发布:华为网络安全工程师 编辑:程序博客网 时间:2024/04/28 14:33

本案例需要两个应用 , 一个远程提供服务 , 一个本地调用
这里写图片描述

//aidl_remoteservice远程

package jacky.aidl_remoteservice;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.support.annotation.Nullable;/** * 作者:Jacky * 邮箱:550997728@qq.com * 时间:2016/2/15 15:56 *///设置服务public class RemoteService extends Service {          @Nullable          @Override          public IBinder onBind(Intent intent) {                    return new MyBinder();          }          public void methodService(){                    System.out.println("我是远程服务里面的方法!");          }          private class MyBinder extends IService.Stub {                    public void callMethodService(){                              methodService();                    }          }}

//aidl_localservice本地

package jacky.aidl_localservice;import android.content.ComponentName;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.view.View;import jacky.aidl_remoteservice.IService;public class MainActivity extends AppCompatActivity {          private IService iservice;          private MyConn conn=new MyConn();          @Override          protected void onCreate(Bundle savedInstanceState) {                    super.onCreate(savedInstanceState);                    setContentView(R.layout.activity_main);                    Intent intent = new Intent();                    //配置意图,与jacky.aidl_remoteservice中定义的意图要相同                    intent.setAction("jacky.aidl_remoteservice");                    bindService(intent,conn,BIND_AUTO_CREATE);          }          public void click(View v){                    try {                              iservice.callMethodService();                    } catch (RemoteException e) {                              e.printStackTrace();                    }          }          //拿到iservice中间人对象(Binder)          public class MyConn implements ServiceConnection {                    @Override                    public void onServiceConnected(ComponentName name, IBinder service) {                              //需要使用IService.Stub                              iservice=IService.Stub.asInterface(service);                    }                    @Override                    public void onServiceDisconnected(ComponentName name) {                    }          }}

运行效果:
点击button , 调用远程服务 , 打印log
这里写图片描述


在AS中使用AIDL的办法:

[1]右键添加AIDL
这里写图片描述

[2]在添加的AIDL中实现
这里写图片描述

0 0