调用远程服务

本文介绍了一个简单的远程服务交互示例,包括如何通过AIDL定义接口、实现服务端及客户端调用流程。服务端通过继承Service并重写onBind方法返回Binder实例来提供远程调用能力,客户端则通过Intent绑定服务并利用AIDL接口调用远程方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

远程服务类
清单文件中注册

<service android:name=".RemoteService">
            <intent-filter>
                <action android:name="com.gjj.remoteservice"/>
            </intent-filter>
</service>

package com.example.test;

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

import com.example.test2.IRemoteInterface;


/**
 * Created by joy on 2016/1/12.
 */
public class RemoteService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("绑定了");
        return new Mybind();
    }

    class Mybind extends IRemoteInterface.Stub {

        @Override
        public void qianxian()  {
            RemoteService.this.say();
        }

    }

    public void say(){
        System.out.println("我是远程服务");
    }
}

IRemoteInterface.Stub为创建的AIDL文件自动生成的类
首先创建AIDL文件IRemoteInterface接口,然后在android studio中make module自动生成IRemoteInterface.java,现在可以调用了
注意这里的AIDL文件的包名必须和客户端的一致


客户端

package com.example.test2;

import android.app.Activity;
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.view.View;

public class LocalActivity extends Activity {

    private IRemoteInterface remoteInterface;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local);
    }

    public void startRemoteService(View v){
        Intent intent=new Intent();
        intent.setAction("com.gjj.remoteservice");

        bindService(intent,new MyServiceConn(),BIND_AUTO_CREATE);
    }


    public void callRemoteMethod(View v){
        try {
            remoteInterface.qianxian();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    class MyServiceConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            remoteInterface=  IRemoteInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值