android - 为什么在创建 Intent 实例时传递 'this'?

标签 android android-intent memory-leaks android-context

我是 Android 应用程序开发的新手。 我试图了解什么是 Intent 及其用途。

我的问题是,在开始另一个 Activity 时,为什么将“this”关键字作为 Intent 的上下文参数传递?

Intent foo = new Intent(this, viewContacts.class);

我知道 any activity 扩展了 Context 类,但为什么我们传递的是 activity context 而不是 application context

我的观点-

当另一个 Activity 启动时,当前 Activity 将被销毁,但其上下文将传递给另一个 Activity 。引用this文章,它说

The most obvious way of avoiding context related memory leak is to avoid escaping the context outside of its own scope.

那么我们不是将当前 Activity 的上下文传递给第一个超出范围的另一个 Activity 吗? 不就是内存泄漏的例子吗?

最佳答案

why is it that we are passing the activity context and not the application context?

两者都可以在这里工作。与 getApplicationContext() 相比,this 的输入更少,执行速度更快。

When another activity starts the current activity will get destroyed but its context will passed to the other one.

您假设 Intent 持有此 Context。它没有。

So aren't we passing the context of current activity to another one where the first one goes out of scope?

没有。

Intent 可以是隐式的也可以是显式的。显式 Intent 是附加了 ComponentName 的,用于标识组件的特定应用程序(按包名称)和 Java 类(按完全限定类名称)此 Intent 是有意的。提供 ContextClass 对象的双参数构造函数用于构建 ComponentName。在构造函数工作完成后,IntentComponentName 都不会保留 Context

关于android - 为什么在创建 Intent 实例时传递 'this'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41334470/

相关文章:

android - 如何将应用程序中的 Activity 上下文传递给其他应用程序中的服务

android - 如果将 "developer payload"留空会发生什么 Google Play 应用内结算

Android - 存储 Activity 结果返回 null

安卓 :Capture media button action when Music player is Active

c# - C#.NET内存泄漏:GC阶段1和阶段2运行时的锯齿状内存使用情况

android - 如果 Activity 崩溃,如何清除通知?

android - 静态代码中的应用内购买错误

Android,无法隐式启动 Activity

c++ - 异常:循环中内存位置的 std::bad_alloc

c++ - SDL TTF 库内存泄漏(每帧创建和释放曲面)