概念: 在我们的app中调用另一个 app的服务,我们称之为远程服务。需要使用 AIDL进行 ·IPC·(跨进程通信)。

  1. IPC:Inter-Process Communication,即跨进程通信
  2. AIDL:Android Interface Definition Language,即Android接口定义语言;用于让某个Service与多个应用程序组件之间进行跨 进程通信,从而可以实现多个应用程序共享同一个Service的功能。

参考文章: Android:远程服务Service(含AIDL & IPC讲解)

示例demo
远程服务创建
  • 新建 RemoteService.aidl 文件 (在android Studio中有这种文件类型)
// IRemoteService.aidlpackage com.example.www.remoteservice;// Declare any non-default types here with import statementsinterface IRemoteService {     /** Request the process ID of this service, to do evil things with it. */        int getPid();        /** Demonstrates some basic types that you can use as parameters         * and return values in AIDL.         */        int basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,                double aDouble, String aString);}
  • 新建远程服务服务 AIDLService
package com.example.www.remoteservice;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class AIDLService extends Service {    private String TAG = "REMOTESERVICE";    @Override    public IBinder onBind(Intent intent) {        // TODO Auto-generated method stub        Log.d(TAG, "DDService onBind");        return mBinder;    }    @Override    public void onCreate() {        // TODO Auto-generated method stub        super.onCreate();        Log.d(TAG, "DDService onCreate........" + "Thread: " + Thread.currentThread().getName());    }    /*与本地服务不同,此处新建Stub类型的Binder*/    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {        public int getPid() {            Log.d(TAG, "Thread: " + Thread.currentThread().getName());            /*返回给调用者当前的线程编号*/            return (int) Thread.currentThread().getId();        }        public int basicTypes(int anInt, long aLong, boolean aBoolean,                              float aFloat, double aDouble, String aString) {            Log.d(TAG, "Thread: " + Thread.currentThread().getName());            Log.d(TAG, "basicTypes aDouble: " + aDouble + " anInt: " + anInt + " aBoolean " + aBoolean + " aString " + aString);            /*返回给调用者当前的线程编号*/            return (int) Thread.currentThread().getId();        }    };}
  • AndroidManifest.xml 配置远程服务
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.www.remoteservice">    <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=".AIDLService"            android:enabled="true"            android:exported="true"            android:process=":xlzh" >            <intent-filter>                <action android:name="com.example.www">action>                            intent-filter>        service>    application>manifest>
  • 开启远程服务 MainActivity
package com.example.www.remoteservice;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        startService(new Intent(this, AIDLService.class));    }}

至此远程服务创建完毕

本地区调用远程服务

项目的目录结构:

  • 把远程服务的 IRemoteService.aidl 包文件 拷贝到 本地 aidl包下面
    如上图所示:
    IRemoteService.aidl
// IRemoteService.aidlpackage com.example.www.remoteservice;// Declare any non-default types here with import statementsinterface IRemoteService {     /** Request the process ID of this service, to do evil things with it. */        int getPid();        /** Demonstrates some basic types that you can use as parameters         * and return values in AIDL.         */        int basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,                double aDouble, String aString);}
  • 绑定远程服务 MainActivity
package com.example.www.client;import android.app.Service;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.Toast;import com.example.www.remoteservice.IRemoteService;public class MainActivity extends AppCompatActivity {    private MyServiceConnection mConn;    private String TAG = "com.example.aidl";    private IRemoteService remoteService;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    public void bind(View view) {        /*        * com.example.www 表示 远程服务端 service 配置的action name        * com.example.www.remoteservice 表示 远程服务 Service 所在的 包名        * */        Intent intent = new Intent("com.example.www");        intent.setPackage("com.example.www.remoteservice");        mConn = new MyServiceConnection();        bindService(intent, mConn, Service.BIND_AUTO_CREATE);    }    public void unbind(View view) {        unbindService(mConn);    }    class MyServiceConnection implements ServiceConnection {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            Log.d(TAG, "Bind Service success!");            /*获取服务端handle*/            remoteService = IRemoteService.Stub.asInterface(service);            try {                int pid1 = remoteService.getPid();                int pid2 = remoteService.basicTypes(12, 1223, true, 12.2f, 12.3, "我们的爱,我明白");                /*打印带有getPid接口和basicTypes接口时服务端的线程号*/                Toast.makeText(getApplicationContext(), pid1 + "---" + pid2, Toast.LENGTH_LONG).show();                Log.d(TAG, "remoteService.getPid(): " + pid1 + " remoteService.basicTypes(): " + pid2);            } catch (RemoteException e) {                e.printStackTrace();            }        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    }}
  • 布局文件 activity_main.xml
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    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=".MainActivity">    <Button        android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginStart="8dp"        android:layout_marginTop="8dp"        android:text="bind"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent"        android:onClick="bind"/>    <Button        android:id="@+id/button2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginStart="8dp"        android:layout_marginTop="8dp"        android:text="unbind"        app:layout_constraintStart_toEndOf="@+id/button"        app:layout_constraintTop_toTopOf="parent"        android:onClick="unbind"/>android.support.constraint.ConstraintLayout>

更多相关文章

  1. android 如何结束一个线程?
  2. Android(安卓)API Demos学习 - Service部分
  3. Android中定时器的使用(Timer)
  4. Android(安卓)AsyncLayoutInflater 源码解析
  5. 线程 同步 ConditionVariable
  6. ava(Android)线程池
  7. android 9.0 拍照 相册选择 图片 裁切后进行 上传到服务器(亲测可
  8. Android(安卓)通过initrc控制命令、服务启动时间
  9. Android(安卓)Service用法讲解与实例

随机推荐

  1. Android Material Design 之 Coordinator
  2. android之GridView和Gallery
  3. Android: Multithreading For Performanc
  4. Android设计原则及规范指南!UI设计师值得
  5. Android 广播监听USB插拔
  6. Android Custom UI: Making a Vintage Th
  7. inotify in android
  8. Android调用MediaScanner进行扫描
  9. Android 全局异常捕捉 + 本地异常日志
  10. Android图像处理之熔铸特效