gpt4 book ai didi

Android:从我正在运行的服务中获取变量

转载 作者:搜寻专家 更新时间:2023-11-01 08:10:40 25 4
gpt4 key购买 nike

我的 Activity 启动了一个服务,当我关闭我的应用程序时,该服务继续运行。好的,没错。但是当我再次打开我的应用程序时,在 Activity 中,我需要知道在我之前启动的正在运行的服务(类)上定义的公共(public)变量的值。

我该怎么做?

谢谢

最佳答案

如果您将 Activity 绑定(bind)到 Service,则您应该在 Service 中实现 Binder 接口(interface),例如

public class ServiceBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}

在您的 Activity 中,创建一个新的 ServiceConnection 类,它将用于让您访问您的服务:

private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mMyService = ((MyService.ServiceBinder)service).getService();
}

public void onServiceDisconnected(ComponentName className) {
mMyService = null;
}
};

此处的成员变量 mMyService 将使您能够访问服务类的所有公共(public)成员。

要创建连接,请在您的 Activity 中实现 doBindServicedoUnbindService:

void doBindService() {
bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
}

void doUnbindService() {
// Detach our existing connection.
unbindService(mConnection);
}

希望这对您有所帮助!

关于Android:从我正在运行的服务中获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9953326/

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