android - 跨进程服务双向通信 - 对新手详细教程

这篇博客详细介绍了Android跨进程服务的单向和双向通信。首先,通过创建AIDL文件实现服务间的单向通信,然后在服务一中定义回调接口,通过IMyCallbackListener.aidl实现双向通信。博客涵盖了从创建AIDL文件、修改服务和Activity代码到解决Android Studio可能出现的问题的完整步骤。通过示例展示了如何在服务一和二之间发送和接收消息。
摘要由CSDN通过智能技术生成

一、单向通信

1.新建项目:MyServiceOne

2.新建Service:File -> new -> service

package com.likego.myserviceone;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

3.新建aidl:File -> new -> AIDL ->AIDL File

// IMyAidlInterface.aidl
package com.likego.myserviceone;

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

interface 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);
}

4.新建项目MyServiceTwo

5.在MyServiceTwo项目下新建MyServiceTwo

6.复制MyServiceOne下的aidl文件夹到MyServiceTwo项目同目录下,并clean一下项目二(andorid studio的BUG,不clean无法找到这个接口文件)build -> clean project,最后两个项目的结构如下:

7.准备工作完成了,开始修改代码,切换到项目一,修改服务一:

package com.likego.myserviceone;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class MyService extends Service {
    private static final String TAG = "MyService";
    //实现接口
    private final IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub(){
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
                               double aDouble, String aString) {
            Log.d(TAG, "basicTypes: 服务二给我发消息了");
            Log.d(TAG, "basicTypes() called with: anInt = [" + anInt + "], aLong = [" + aLong + "]," +
                    " aBoolean = [" +
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值