android远程服务

来源:互联网 发布:java调用外部http接口 编辑:程序博客网 时间:2024/05/22 06:41

1 什么是远程服务呢?远程服务就是多个进程进行通讯。而其中主要用到的是Android Interface Definition Language(安卓定义接口语言)来公开服务的语言。因此我们将这种跨进程的访问服务称为AIDL。

2 AIDL (Android Interface Definition Language) 是一种IDL 语言,用于生成可以在Android设备上两个进程之间进行进程间通信(interprocess communication, IPC)的代码。就是我这个App应用的activity,需要调用其他App应用的Service.当然同一App应用的activity 与service也可以在不同进程间,这可以设置Service配置中,android:process=”:remote”。
如何创建AIDL?
(1)在工程的src下,新建立一个文本文件,将要实现的函数放在这个文件中,后缀为.aidl。
(2)刷新工程后,就会发现在gen包下,有一个同名的java文件,这是aidl工具自动生成的,里面,就有我们要实现的函数。
如图:

这里写图片描述
AIDL代码:
注意aidl代码中是不需要加修饰符的。

package com.android.internal.telephony;import android.os.Bundle;import java.util.List;import android.telephony.NeighboringCellInfo;interface ITelephony {   void dial(String number);    void call(String number);}    boolean isSimPinEnabled();    void cancelMissedCallsNotification();}

3 清单文件中配置服务
android:enabled=”true”//是否支持其它应用调用当前组件
android:process=”:remote”//会在另外一个进程中运行。

<service            android:name=".QQLoginService"            android:enabled="true"//是否支持其它应用调用当前组件            android:process=":remote" >    </service>

4 绑定服务:绑定服务通过bindservices()里面传三个参为intent(服务),connection(连接者), Service.BIND_AUTO_CREATE(自动创建)其中connection需要自己实例化new出一个接口。

 ServiceConnection connection=new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {            Log.i("test","绑定成功了");            //myIBinder = (QQLoginService.MyIBinder) iBinder;            //qqLoginInterface = (QQLoginInterface) iBinder;            qqLoginInterfaceOut = QQLoginInterfaceOut.Stub.asInterface(iBinder);        }        @Override        public void onServiceDisconnected(ComponentName componentName) {        }    };    @Override    protected void onResume() {        super.onResume();        //绑定服务        bindService(intent,connection, Service.BIND_AUTO_CREATE);    }

5 如何启动两个进程之间的服务?
在安卓5.0以后就不允许使用隐式intent来启动服务,所以我们只能用显式,显式intent又分为两种。用的为CopmentName。
第一个参是要启动的应用的包名称,这个包是指清单文件中列出的应用的包名称。
第二个参是你要启动的activity或者service的全称,就是包名加类名。
代码如下:

       ComponentName componentName=new ComponentName("com.zking.g150831_android23_qq","com.zking.g150831_android23_qq.QQLoginService");        intent.setComponent(componentName);
0 0