导读

1.案例

案例

app AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.hala.srevicedemo"><application
        android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><service
            android:name=".MyService"android:enabled="true"android:exported="true"><intent-filter><action android:name="com.hala.myservice"/></intent-filter></service></application></manifest>

app 布局文件 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.hala.srevicedemo.MainActivity"><Button
       android:id="@+id/start"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="启动服务"android:onClick="onClick"/><Button
        android:id="@+id/stop"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="停止服务"android:onClick="onClick"/><Button
        android:id="@+id/bind"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="绑定服务"android:onClick="onClick"/><Button
        android:id="@+id/unbind"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="解锁服务"android:onClick="onClick"/></LinearLayout>

app MainActivity.java

package com.hala.srevicedemo;import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;public class MainActivity extends AppCompatActivity {private ServiceConnection conn=new ServiceConnection() {//当客户端正常连接着Service时,执行服务的绑定操作会被调用//如果没有ServiceConnection,会出现绑定后解绑,无法再次绑定的情况@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {Log.d("TAG","hello,bind again");//以下是关于aidl操作IMyAidlInterface imal=IMyAidlInterface.Stub.asInterface(service);try {imal.showProgress();} catch (RemoteException e) {e.printStackTrace();}/*以下是关于Binder操作的代码只能在同进程间传递(MyService中也有修改)//强制转换MyService.MyBinder mb=(MyService.MyBinder)service;int step=mb.getProcess();Log.d("TAG","当前进度为:"+step);*/}//当客户端和服务的连接丢失了@Overridepublic void onServiceDisconnected(ComponentName name) {}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void onClick(View view){//start 与 stop为一组//bind 与 unbind为一组switch (view.getId()){case R.id.start://如果服务已经创建,重复启动不会重新创建,操作的是同一个服务,除非先销毁Intent it=new Intent(this,MyService.class);startService(it);break;case R.id.stop://这里虽然是两个intent,但确实针对同一个对象Intent it1=new Intent(this,MyService.class);stopService(it1);break;case R.id.bind://绑定服务:最大作用是对Service执行的任务进行监控,如下载到哪了,音乐播放到哪了Intent it2=new Intent(this,MyService.class);bindService(it2,conn,BIND_AUTO_CREATE);break;case R.id.unbind://要指明解绑哪个连接,所以conn要设置为全局unbindService(conn);break;}}
}

app MyService.java

package com.hala.srevicedemo;import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;//实现进度监控(两个要素):
//ServicerConnection:用与绑定客户端和Service->见MainActivity.java有说明
//IBinder:在android中用于远程操作对象的一个基本接口
//因为IBinder强制要求我们实现一些方法,而Binder类是给所有强制方法实现了一个空方法
//在开发中我们会自己写一个内部类,继承Binder类,在里边写自己的方法
public class MyService extends Service {public static final String TAG = "TAG";private int i;public MyService() {}/*** 创建*/@Overridepublic void onCreate() {super.onCreate();Log.e(TAG,"服务创建了");//开启一个线程,模拟耗时任务new Thread(){@Overridepublic void run() {super.run();try {for(i = 0; i <100; i++){sleep(1000);}} catch (InterruptedException e) {e.printStackTrace();}}}.start();}/*** 启动* @param intent* @param flags* @param startId* @return*/@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.e(TAG,"服务启动了");return super.onStartCommand(intent, flags, startId);}/*** 绑定* @param intent* @return*/@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.Log.e(TAG,"服务绑定了");return new IMyAidlInterface.Stub() {@Overridepublic void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {}@Overridepublic void showProgress() throws RemoteException {Log.d("TAG","当前进度是:"+i);}};//Binder操作返回值//return new MyBinder();}/*关于Binder操作自定义操作class MyBinder extends Binder{public int getProcess(){return i;}}*//*** 解绑* @param intent* @return*/@Overridepublic boolean onUnbind(Intent intent) {Log.e(TAG,"服务解绑了");return super.onUnbind(intent);}/*** 销毁*/@Overridepublic void onDestroy() {super.onDestroy();Log.e(TAG,"服务销毁了");}
}


⚠️创建aidl文件完成后,要重新build,生成java文件,因为真正起作用的是这个java文件,java文件在哪里查看呢?
转换为工程视图,如下下图所示找到那个文件

app aidl文件 IMyAidlInterface.aidl

// IMyAidlInterface.aidl
package com.hala.srevicedemo;// Declare any non-default types here with import statementsinterface IMyAidlInterface {/*** Demonstrates some basic types that you can use as parameters* and return values in AIDL.*/void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,double aDouble, String aString);//定义自己所需要的方法void showProgress();
}

aidldemo 布局文件 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.hala.aidldemo.MainActivity"><Button
        android:id="@+id/start"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="远程启动服务"android:onClick="onClick"/><Button
        android:id="@+id/stop"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="远程停止服务"android:onClick="onClick"/><Button
        android:id="@+id/bind"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="远程绑定服务"android:onClick="onClick"/><Button
        android:id="@+id/unbind"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="远程解锁服务"android:onClick="onClick"/></LinearLayout>

在工程视图下如下图复制aidl到要建立远程联系的app,注意同样需要重新build

aidldemo MainActivity.java

package com.hala.aidldemo;import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;import com.hala.srevicedemo.IMyAidlInterface;public class MainActivity extends AppCompatActivity {ServiceConnection conn=new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {//使用了aidlIMyAidlInterface imal=IMyAidlInterface.Stub.asInterface(service);try {imal.showProgress();} catch (RemoteException e) {e.printStackTrace();}}@Overridepublic void onServiceDisconnected(ComponentName name) {}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void onClick(View view){switch(view.getId()){case R.id.start://Android 5.0后service的intent一定要显式声明Intent it=new Intent();//参数为Service起的别名it.setAction("com.hala.myservice");//参数为Service所在的包名it.setPackage("com.hala.srevicedemo");startService(it);break;case R.id.stop://Android 5.0后service的intent一定要显式声明Intent it1=new Intent();it1.setAction("com.hala.myservice");it1.setPackage("com.hala.srevicedemo");stopService(it1);break;case R.id.bind://Android 5.0后service的intent一定要显式声明Intent it2=new Intent();it2.setAction("com.hala.myservice");it2.setPackage("com.hala.srevicedemo");bindService(it2,conn,BIND_AUTO_CREATE);break;case R.id.unbind:unbindService(conn);break;}}
}

显示结果

aidldemo

app

Android 之路56---AIDL建立远程通信相关推荐

  1. Android探索之旅 | AIDL原理和实例讲解

    前言 为使应用程序之间能够彼此通信,Android提供了IPC (Inter Process Communication,进程间通信)的一种独特实现: AIDL (Android Interface ...

  2. Android之四大组件(AIDL Service的使用)

    跨进程调用Service(AIDL Service) Android系统中的进程之间不能共享内存,因此,需要提供一些机制在不同进程之间进行数据通信. 在前一篇文章(关于Android中的四大组件(Se ...

  3. Android绑定多个aidl,android aidl 多`module`版的实现

    多module版,pojo类型数据的双向传递 [service client] android中如何进行跨进程通信的? aidl是什么? android中如何通过aidl实现跨进程通信? 最简单的ai ...

  4. Android开发——进程间通信之AIDL(一)

    0.  前言 不论是Android还是其他操作系统,都会有自己的IPC机制,所谓IPC(Inter-Process Communication)即进程间通信.首先线程和进程是很不同的概念,线程是CPU ...

  5. Android 之路30---UI基础控件

    导读 1.TextView 2.Button 3.Android各种控件的监听器 4.EditText 5.ImageView及ImageButton 6.Android 中Xml文件引用资源的方法 ...

  6. 不得不说的Android Binder机制与AIDL

    说起Android的进程间通信,想必大家都会不约而同的想起Android中的Binder机制.而提起Binder,想必也有不少同学会想起初学Android时被Binder和AIDL支配的恐惧感.但是作 ...

  7. Android应用中通过AIDL机制实现进程间的通讯实例

    Android中,每个应用程序都有自己的进程,当需要在不同的进程之间传递对象时,该如何实现呢?显然,Java中是不支持跨进程内存共享的,因此要传递对象,需要把对象解析成操作系统能够理解的数据格式,以达 ...

  8. 大话android 进程通信之AIDL

    上一篇的service涉及到进程通信问题,主要解决办法是通过 messenger来发送消息,这也是Google推荐的进程通信方式,比较简单易懂嘛~~,messenger底层也是通过binder来实现的 ...

  9. 使用Android Studio新建Project并建立多个module

    使用Android Studio新建Project并建立多个module 分类: Android 2014-03-29 23:25 187人阅读 评论(0) 收藏 举报 说明:本篇内容涉及如何在AS中 ...

  10. Android进阶笔记:AIDL内部实现详解 (二)

    接着上一篇分析的aidl的流程解析.知道了aidl主要就是利用Ibinder来实现跨进程通信的.既然是通过对Binder各种方法的封装,那也可以不使用aidl自己通过Binder来实现跨进程通讯.那么 ...

最新文章

  1. 第2关:利用栈判断字符串括号是否匹配
  2. Java多态详解(入门可看)
  3. 计算机技术应用及信息管理,计算机应用技术与信息管理整合研究(共2808字).doc...
  4. Vue+Openlayer使用overlay实现弹窗弹出显示与关闭
  5. 洛谷——P1640 [SCOI2010]连续攻击游戏
  6. 深入浅出剖析 OpenCV 视觉处理
  7. SpringBoot高级-任务-异步任务
  8. 50张非常精美的Apple主题桌面壁纸(上篇)
  9. 面试中有这些特征的公司可以pass了
  10. linux硬件开发学习,硬件学习该从何下手
  11. GridSearchCV( )参数详情
  12. 多种方式判断PC端,IOS端,移动端
  13. 删除页码和从第三页开始有页码
  14. LeCo-33.搜索旋转数组
  15. PHP 基本语句
  16. Word里一级标题里页眉很近
  17. 强制双休!腾讯调整加班机制,21 点前必须离开工位
  18. python教程99--控制鼠标键盘模块 pyautogui
  19. c语言中7行7列星号怎么做,C语言*星号的秘密
  20. 如何用因果推断和实验驱动用户增长? | 7月28日TF67

热门文章

  1. win10显卡相关配置
  2. SAP中使用LSMW批量导入总账科目
  3. python-图片上添加字符
  4. 毕业设计 单片机智能录音器设计与实现 - 物联网 嵌入式
  5. C#中Invoke,BeginInvoke的作用
  6. 泰勒公式求解极限(泰勒展不开)
  7. 计算机与plc通信参数,PLC与PC计算机通信
  8. win10 任务栏全透明一步直达
  9. c语言编程票务系统,C语言课程设计票务管理系统
  10. 权限和归属——基本权限和特殊权限