gpt4 book ai didi

android - 在这种情况下我应该如何获取上下文?

转载 作者:行者123 更新时间:2023-11-29 02:11:26 25 4
gpt4 key购买 nike

我必须在 accelerometercompass 等传感器之上设计一个 Sensor Manager 类。这个项目将是一个 类库项目,将在其他需要传感器设备数据的android项目中引用和使用。问题是,为了在我的 Sensor Manager 类中使用 accelerometercompass 等设备,我需要 Context。我不知道在这种情况下如何访问当前上下文。

我是否应该要求我的 Sensor Manager 的调用者/用户在某些方法的参数中传递 Context?如果不止一个类(class)或 Activity 使用我的传感器管理器怎么办?实际上我只会使用一个上下文,它会导致问题吗?

或者是否有任何简单、安全和可靠的方法来获取当前应用程序的上下文?

更新

这是我目前的设计...

我已经为 SensorManager 以及 SensorManager 中的每个设备实现了单例。例如,SensorManager 中只有一个加速度计实例。调用方将获取 SensorManager,然后调用 RegisterForAccelerometer 方法。因此,只要 SensorManager 的加速度计实例中的加速度计坐标有任何更新,所有注册的调用者都会收到通知。现在,当我第一次尝试开始监听加速度计的坐标时,问题就来了,因为我需要上下文。

最佳答案

在我看来,您必须传递使用这些设备的特定 Activitycontext。我假设您没有将这些类作为 Singleton

此外,如果您想将类设为单例,我想您可以传递Application context 而不是Activity context,但我不会如果这行得通,请确定这一点。

更新:

Application 上下文请引用此 http://developer.android.com/reference/android/app/Application.html .

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

所以无论你在哪个Activity中你都会通过这个Application context

关于android - 在这种情况下我应该如何获取上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7146778/

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