android远程服务

概念: 在我们的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.aidl
package com.example.www.remoteservice;

// Declare any non-default types here with import statements

interface 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>
                <!--<category android:name="android.intent.category.DEFAULT" />-->
            </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.aidl
package com.example.www.remoteservice;

// Declare any non-default types here with import statements

interface 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITzhongzi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值