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

标签 java android service inner-classes

我有一个带有私有(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/

相关文章:

java - 如何使用 JAXB 或 JAX-WS 注释使两个字段相互依赖?

android - "No, missing feature: WATCH"当我尝试使用穿戴应用程序运行我的智能手机应用程序时?

c# - 无法从命令行或调试器启动服务

android - 绑定(bind)与在android中启动服务的优缺点

c# - WTSQueryUserToken 在 C# 的 Windows 7 上总是抛出 "An attempt was made to reference a token that does not exist"

java - 程序不重新绘制?

java - 尝试从 DefaultListModel 对象中删除元素

java - SDP消息构造?

java - 取消固定后数据保留在本地数据存储中

android - 使用依赖 pom/iml 文件手动添加 aar