gpt4 book ai didi

java - 如何将值从 MainActivity 传递到 ServiceConnection?

转载 作者:行者123 更新时间:2023-12-02 04:38:51 25 4
gpt4 key购买 nike

我有一个带有私有(private)字符串属性MainActivity。在我的代码中,我有以下内容:

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 的属性中放置一个字符串。我怎样才能做到这一点?

我尝试将字符串设为公共(public)、静态,但不起作用。

最佳答案

在您的服务中创建一个像 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 外部使用服务函数,只需确保它不为 null。

关于java - 如何将值从 MainActivity 传递到 ServiceConnection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56531084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com