java - 如何将值从 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
. 我怎样才能做到这一点?
我试图将字符串设为公开的、静态的但不起作用。
解决方案
在您的服务中创建一个像 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 外部使用服务功能,只要确保它不为空即可。
推荐阅读
- c# - 在 Start.cs 中添加 UseHsts() 有什么意义
- r - 有没有办法不用 R 中的 ckanr 下载整个 CKAN 数据包?
- java - 获取数组列表中缺少的数字
- tensorflow - 您如何管理 100 台虚拟服务器进行推理?
- react-native - 如何在博览会上更新 android build?
- django - 有没有一种简单的方法可以在 Django 管理站点中创建链式动态下拉列表?
- css - 为什么溢出:隐藏不能防止兄弟div中的边距折叠为显示:内联块?
- javascript - 在没有 javascript (nodejs) 中的第 3 方库的情况下,在本月 1 日运行一个函数?
- android - 在我的情况下,如何从 api 获取准确的数据?
- node.js - 在 SSR 上的反应组件中导入 scss