android - 关于安卓上下文

标签 android android-context

我在这里粘贴了一些我的代码:

public void onCreate(Bundle savedInstanceState) {
        Log.e("Main Activity", "OnCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_frame);

        //GlowEffect is the custom class's constructor:GlowEffect(context);
        new GlowEffect2(getApplictionContext());

        AlertDialog.Builder builder = new Builder(this);
...
...

我发现当我将 **Builder(this)** 中的参数更改为 Builder(getApplicationContext()); 该应用程序将崩溃!虽然 GlowEffect2 构造函数可以很好地工作,但无论参数是“this”还是 “getApplicationContext()”。 那么这两个参数之间的区别是什么?

最佳答案

如您所见,constructor对于 Builder 需要一个 Context对象作为参数。

Activity 和 Application 对象都是 Context 的子类,因此它们都是创建 Builder 的有效参数。

Object -> Context -> ContextWrapper -> Application
Object -> Context -> ContextWrapper -> ContextThemeWrapper -> Activity

应用程序和 Activity 之间有什么区别?我认为最明显的区别之一是它们的生命周期:

  • Activity 会在特定的 UI 部分运行时一直存在,并且会在各种情况下被销毁和重新创建,例如在方向改变时,或者当 Activity 未被查看时,Android 操作系统需要通过销毁未被查看的 Activity 来释放一些内存。

  • 只要应用程序本身在运行,应用程序就会一直存在。

至于您的具体问题,崩溃的堆栈跟踪是什么?这questiongetApplicationContext() 可能为 null,因为在创建 Activity 时应用程序仍在启动(答案说该问题已在 Android OS 1.6 中修复)。

关于android - 关于安卓上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7961982/

相关文章:

android - WorkManager两次启动Worker

java - 如何在 api 18 中使用 keystore 时修复 "java.security.InvalidKeyException: Unsupported key algorithm: EC. Only RSA supported"

android - 需要通过特定的 APN 进行连接。但不想失去与其他应用程序的连接

Android ProgressDialog上下文问题

java - Android - 从静态 'helper' 方法注册接收器(无法获取上下文)?

java - 在非 Activity 类比较器中获取上下文

android studio - java : package com. google.android.gms.maps 不存在

android - 更大更新后删除 Android 应用程序的所有用户数据

android ContextCompat.getColor 无法解析方法

android - 如何从启动器中隐藏 Android 应用程序