首页 > 解决方案 > 如何将值从 MainActivity 传递到 ServiceConnection?

问题描述

我有MainActivity一个private String attribute。在我的代码中,我有以下内容:

private ServiceConnection mTransactionServiceConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        mTransactionService = IPoyntTransactionService.Stub.asInterface(iBinder);
        Log.d(TAG, "Transaction service connected");
        try {
            mTransactionService.getTransaction("fcf98959-c188-42d1-b085-786d21e552ac", UUID.randomUUID().toString(), mTransactionServiceListener);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void onServiceDisconnected(ComponentName componentName) {
        mTransactionService = null;
        Log.d(TAG, "Transaction service disconnected");
    }
};

值:fcf98959-c188-42d1-b085-786d21e552ac是硬编码的。我需要在MainActivity. 我怎样才能做到这一点?

我试图将字符串设为公开的、静态的但不起作用。

标签: javaandroidserviceinner-classes

解决方案


在您的服务中创建一个像 setter 一样工作的函数,例如:

public void setValue(String value){
   this.value = value;
}

在你的 onServiceConnected() 函数里面

并在您初始化服务后从您的 onServiceConnected() 调用它,您可以使用其中的功能。

private ServiceConnection mTransactionServiceConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        mTransactionService = IPoyntTransactionService.Stub.asInterface(iBinder);
        Log.d(TAG, "Transaction service connected");
         **mTransactionService.setValue(the value your want to set);**
        try {
            mTransactionService.getTransaction("fcf98959-c188-42d1-b085-786d21e552ac", UUID.randomUUID().toString(), mTransactionServiceListener);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    public void onServiceDisconnected(ComponentName componentName) {
        mTransactionService = null;
        Log.d(TAG, "Transaction service disconnected");
    }
};

这将更新服务的价值。您还可以从 onServiceConnected 外部使用服务功能,只要确保它不为空即可。


推荐阅读