跨应用Service

本文介绍在Android中如何实现跨应用启动Service、绑定Service以及通过AIDL进行跨应用通信的方法。涉及Intent使用、AIDL文件创建及Binder接口实现等内容。

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

一、跨应用启动Service:

5.0版本后只支持显式Intent,可用

i.setComponent(new Component("包名",“包名.服务类名”))

来实现跨应用启动Service.


二、跨应用绑定Service:

需要在被绑定Service的App中建立AIDS文件,并且在onBind中返回,如下

public IBinder onBind(Intent intent) {
    return new IMyService.Stub() {
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
        }
    };
}

然后就可以调用方法实现绑定了

case R.id.button3:
    bindService(i,this,Context.BIND_AUTO_CREATE);
    break;
case R.id.button4:
    unbindService(this);
    break;

三、跨应用通信

步骤1:在app1中新建AIDL文件

// IMyService.aidl
package com.example.wjb.helloworld;

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

interface IMyService {
    /**
     * 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 setData(String data);
}
步骤2:在app2中new—>Folder—>AIDL Folder建立,在里面新建一个包,包名为app1的包名,再将app1的AIDL文件复制过来。 就是通过AIDL中的setData方法来实现通信。

步骤3:在app1的MyService中的onBind里实现

public IBinder onBind(Intent intent) {
    return new IMyService.Stub() {
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
        }

        @Override
        public void setData(String data) throws RemoteException {
            MyService.this.data=data;
        }
    };
}
步骤4:在app2中的onServiceConnected方法实现binder与app1中的MyService的连接

private IMyService binder = null;
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    
    binder = IMyService.Stub.asInterface(service);
}
步骤5:现在可用binder.setData()方法来传递数据给MyService了

if(binder!=null){
    try {
        binder.setData(et.getText().toString());
    }catch (RemoteException e){
        e.printStackTrace();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值