上次我给大家介绍了Service的基本用法,其中有提到过如何访问自身app的Service,现在我来为大家介绍如何访问其他app的Service


1:创建一个安卓项目app1并且新建一个service,在Service清单文件中配置访问此服务所需要的过滤条件

清单代码如下

<service android:name="com.example.aidl.MyService" android:enabled="true" android:exported="true" > <intent-filter > <action android:name="org.yi.Action"/> </intent-filter> </service>

2:创建一个接口IMybinder,然后随便写个方法,写完后把修饰接口的public删掉,

interface IMyBinder { void start();}

然后找到接口文件所在的文件目录,将文件后缀名改为aidl然后回到想到项目刷新,这时候gen目录会自动生成一个IMyBind的java文件,如下图(万恶的水印。。。)

3:在创建一个app2项目(用来启动app1中Service的方法),将aidl后缀的文件拷贝到app2项目里面来(记住拷贝的aidl所放在的包名要跟原来的一样)

4: 回到app1的service中写一个内部类继承IMybinder.stub,重写start()方法里面调用Service的方法,然后在Service的onBind方法返回一个Mybinder对象

(如下图中play()方法是在Service里面的,然后在play方法里面打个日志已便检查是否调用成功)

class MyBinder extends IMyBinder.Stub{ public void start() { play(); }}@Overridepublic IBinder onBind(Intent intent) { return new MyBinder();}public void play(){ Log.e("MyService", "这是app1中Service的play方法");}

5:在app2中放入一个按钮并在监听事件中调用app1中服务的方法

//利用intent的隐式意图启动另外一个app的服务findViewById(R.id.button1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent service = new Intent(); service.setAction("org.yi.Action"); bindService(service , conn , Context.BIND_AUTO_CREATE); }});

6:conn接口对象中的onServiceConnected方法中取得IMyBnder对象并调用start方法,代码如下

private ServiceConnection conn = new ServiceConnection() { private IMyBinder mBinder; @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { //取得IMyBinder对象 mBinder = IMyBinder.Stub.asInterface(service); try { mBinder.start(); } catch(RemoteException e) { e.printStackTrace(); } }};

大功告成,先运行app1来启动服务,然后在app2中点击按钮调用app1中service的方法,结果如下

这里的调用比较复杂需要在2个app中来回写方法,我会把这次的源代码上传到我的上传(名字为博客标题),有需要的可以去下载。Service基本就说到这,下次我为大家介绍安卓第三大组件BroadCastReceiver(广播机制)