gpt4 book ai didi

Android getContext 基于当前线程? (线程本地?)

转载 作者:太空狗 更新时间:2023-10-29 16:30:29 25 4
gpt4 key购买 nike

我有点厌倦了总是在我的各个类之间传递一个 context 来做一些简单的事情,比如 Toast 或 Alert 对话框,获取应用程序名称和版本,甚至只是访问我的 SQLite 数据库,等等。所有这些都需要 Context 的实例才能运行。

我的所有 Activity 都有一个父类(super class)。在这种情况下,context == this。我有许多辅助方法来整理我的主要 Activity 代码。 .

但是,对于其他类,例如 Helpers、ServiceBroadcastReceiver 等,this != context 所以我总是必须传递额外的 context 变量。

在许多情况下,甚至这些其他类也在 线程上运行。有没有办法为当前运行的线程获取正确的 Context?我正在考虑创建自己的 ThreadLocal 系统,也许在我的 Application 子类中,但我不确定这是否是一种稳定的方法。

你会推荐什么来获取当前线程的上下文?

最佳答案

Is there a way I can get the correct Context for the currently running thread?

没有,因为没有这个概念。如果您有 14 个 Activity 、2 个服务和一个自定义的 Application 子类,它们同时都在内存中,它们都是主应用程序线程的“正确上下文”,因为它们的大部分方法都将在那个线程上被调用。

I'm thinking of creating my own ThreadLocal system, perhaps in my Application subclass, but I am not sure if this is a stable approach.

不会的。此外,它几乎可以确保您拥有 the wrong context most of the time .

getting application Name and Version

使用BuildConfig

Alert dialogs

使用显示它们的 Activity ,因为没有其他正确答案。

关于Android getContext 基于当前线程? (线程本地?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40271880/

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