gpt4 book ai didi

android - 从其他 Activity 中引用静态 ServiceConnection 是否正确?

转载 作者:行者123 更新时间:2023-11-29 01:39:59 24 4
gpt4 key购买 nike

我在主要 Activity 中开始并使用我的服务:

public static MyServiceConnection serviceConnection;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

serviceConnection = new MyServiceConnection();
startService(new Intent(...));
bindService(new Intent(...), serviceConnection.getServiceConnection(), 0);
}

如果我要开始另一个 Activity (没有完成 Main),我可以像这样使用静态变量吗:

Main.serviceConnection.Method1()

我会得到 NullReferenceException 吗?例如,如果操作系统决定释放一些内存并销毁主要 Activity ?可能吗?

最佳答案

Is it correct to reference static ServiceConnection from other activity?

没有。引用 the documentation :

You should usually pair the binding and unbinding during matching bring-up and tear-down moments of the client's lifecycle. For example:

  • If you only need to interact with the service while your activity is visible, you should bind during onStart() and unbind during onStop().
  • If you want your activity to receive responses even while it is stopped in the background, then you can bind during onCreate() and unbind during onDestroy(). Beware that this implies that your activity needs to use the service the entire time it's running (even in the background), so if the service is in another process, then you increase the weight of the process and it becomes more likely that the system will kill it.

请允许每个组件绑定(bind)到服务本身。

I'm starting and binging my Service at Main activity:

请删除static 关键字。请仅在绑定(bind)到服务的组件中使用 ServiceConnection。如果您有其他组件,它们也可以自己绑定(bind)到服务。

Will I get NullReferenceException?

很有可能。例如,当您认为您将“开始另一个 Activity (没有完成 Main)”时,并不要求“Main” Activity 保持不变。如果 Android 终止了您的进程(在您移至后台后)并且用户通过最近任务列表返回给您,则您的第二个 Activity 可能会在新进程中的“Main”之前创建。

请允许您的第二个 Activity 绑定(bind)到服务本身。或者,不要使用绑定(bind)服务。

关于android - 从其他 Activity 中引用静态 ServiceConnection 是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25297434/

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