Service学习笔记-as下配置aidl

来源:互联网 发布:少儿编程教育培训 编辑:程序博客网 时间:2024/05/29 13:53

,之前一直感觉aidl(Android Interface definition language)很神秘,它可以实现apk的跨进程通信,今天学习了下。

服务端

创建工程1

1、创建aidl接口文件

interface IMyAidlInterface {    int plus(int a,int b);    String toUpperCase(String str);}

同步一下,就会在as的gen目录下生成相应的java文件(如下图,这个文件描述了aidl机理,初学者不必关注)
这里写图片描述
2、在service中实现aidl接口

IMyAidlInterface.Stub m_stub=new IMyAidlInterface.Stub() {        @Override        public int plus(int a, int b) throws RemoteException {            return a+b;        }        @Override        public String toUpperCase(String str) throws RemoteException {            if(!TextUtils.isEmpty(str)) return str.toUpperCase();            return null;        }    };

注意在配置文件中添加service的调用action:

<intent-filter>                <action android:name="com.example.myapplication.MyService"/>            </intent-filter>

客户端

创建工程2

将工程1中的aidl文件拷贝到工程2(把整个aidl文件夹拷贝过来额,不要改包名,如下图),在工程2的activity中调用工程1的service
这里写图片描述

public void Bind(View v){        Log.d(TAG,"Bind");        Intent intent=new Intent();        if(Build.VERSION.SDK_INT<21) intent.setAction("com.example.myapplication.MyService");        else {            Log.d(TAG,"Bind xxxx");            intent.setAction("com.example.myapplication.MyService");            intent.setPackage("com.example.myapplication");            Log.d(TAG,"Bind xxxx2222222");        }        bindService(intent,m_connection,BIND_AUTO_CREATE);    }    private ServiceConnection m_connection=new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            Log.d(TAG,"onServiceConnected");            iMyAidlInterface= IMyAidlInterface.Stub.asInterface(service);            try {                int result=iMyAidlInterface.plus(3,5);                String upperStr=iMyAidlInterface.toUpperCase("hello world");                Log.d(TAG,"onServiceConnected,result="+result+"  ,upperStr="+upperStr);            } catch (RemoteException e) {                e.printStackTrace();            }        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    };

注意android5.0以后把Intent intent = new Intent(“com.example.servicetest.MyAIDLService”);替换为Intent mIntent = new Intent();mIntent.setAction(“XXX.XXX.XXX”);mIntent.setPackage(“XXX.XXX”);可以解决隐式Intent闪退的问题。

个人demo地址:http://download.csdn.net/detail/u013795543/9650419

0 0
原创粉丝点击