您的位置:首页 > 其它

跨应用Service

2015-09-07 18:48 483 查看
一、跨应用启动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();
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: