入门篇:10.Android中AIDL(安卓接口定义语言)跨应用操作Service

Android系统中的进程之间不能共享内存,因此,需要提供一些机制在不同进程之间进行数据通信。

为了使其他的应用程序也可以访问本应用程序提供的服务,Android系统采用了远程过程调用(Remote Procedure Call,RPC)方式来实现。与很多其他的基于RPC的解决方案一样,Android使用一种接口定义语言(Interface Definition Language,IDL)来公开服务的接口。我们知道4个Android应用程序组件中的3个(Activity、BroadcastReceiver和ContentProvider)都可以进行跨进程访问,另外一个Android应用程序组件Service同样可以。因此,可以将这种可以跨进程访问的服务称为AIDL(Android Interface Definition Language)服务。

--来自百度百科的解释

1.跨应用启动Service

(1)新建一个应用StartServiceFromAnotherApp

(2)在该应用中新建一个Service,AppService

(3)新建一个应用AnotherApp

       我们的目的是从这个应用中启动StartServiceFromAnotherApp中的AppService

(4)启动Appservice的代码为:

Intent i = new Intent();
i.setComponent(new ComponentName("要启动的service的包名","要启动的service类全称并带包名"));
startService(i);

(5)停止服务stopService(i)即可。

2.跨应用绑定service

(1)创建一个AIDL文件,Interface名为IAppServiceRemoteBinder,创建后会生成一个线程的类。

(2)在AppService中的onBind方法中重写:return new IAppServiceRemoteBinder.Stub();并实现其抽象方法。

(3)在AnotherApp里面启动第一个应用的AppService:

       bindService(i,this,Context.BIND_AUTO_CREATE);//这个i为上面所创建的Intent 对象,this需要实现两个方法onServiceConnected()和onServiceDIsconnected().

(4)停止服务:stopService(this);

3.跨应用绑定service并通信

(1)修改AIDL文件,添加一个抽象方法setData(String data)  

(2)此时AppService里面的onBind方法中IAppServiceRemoteBinder.Stub()会报错,因为需要实现上面抽象方法setData()

(3)在AppService中添加一个String类型的数据  String data = "默认数据";

(4)在setData方法中修改此数据

       AppService.this.data = data;

(5)创建线程状态变量 private boolean running = false;

(6)在onCreate方法里写一个线程,线程开始running = true ,其中的run方法中每隔一秒输出一下data

(7)在onDestory方法中running = false;

(8)回到AnotherApp,添加一个一个输入文本,和一个按钮,按钮为同步数据

(9)在AnotherApp中新建一个文件夹aidl,在aidl中添加一个包,包名为上述的aidl文件的包名,并且在包中复制一个aidl文件。

(10)在MainActivity中创建:private IAppServiceRemoteBinder binder = null;

(11)同步按钮执行:

if(binder!=null){
    try{
        binder.setData(input.getText().toString());
    }catch(RemoteException e){
        e.printStackTrace();
    }
}

(12)在onServiceConnected方法中添加:binder = IAppSerciveRemoteBinder.Stub.asInterface(service);

(13)解除绑定按钮添加:binder = null;

 

 

原文地址:https://www.cnblogs.com/androidNot/p/5612766.html