zoukankan      html  css  js  c++  java
  • 入门篇: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;

     

     

  • 相关阅读:
    iOS 宏(define)与常量(const)的正确使用
    Android中全屏 取消标题栏,TabHost中设置NoTitleBar的三种方法(转)
    如何在 GitHub 建立个人主页和项目演示页面
    Git 使用指南(cmd + gui)
    Google C++ 编码规范(中文版)
    SVN服务器搭建和使用
    演化理解 Android 异步加载图片(转)
    Android之断点续传下载(转)
    Android学习笔记——关于onConfigurationChanged(转)
    (转)Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (三) —— SharePreferences
  • 原文地址:https://www.cnblogs.com/androidNot/p/5612766.html
Copyright © 2011-2022 走看看