传递活动或上下文的其他实例上下文、实例

2023-09-12 05:47:54 作者:宁负天下人、也不负你*

能否请你告诉我什么是最好的做法是通过活动上下文其他实例(;)

Can you please tell me whats the best practice to pass activity or context to other instance(;)

不过...

什么是更好的通过? 活动上下文 是有活动好主意作为全球(公共静态活动活动) What is better to pass? Activity or Context Is good idea to have the Activity as Global (public static Activity activity)

这里是我的code。你会怎样改变? (基于Android的好做法)

here is my code. What would you change? (based on good android practices)

推荐答案

传递一个活动成没有特别要求的活动对象通常是一个坏主意。 活动扩展上下文所以它的工作原理,以满足需要的方法上下文

Passing an Activity into another object that does not specifically require the Activity object is usually a bad idea. Activity extends Context so it works to satisfy a method that requires Context.

在你的情况,你可以得到上下文查看传递到方法。但是,如果你需要的上下文用于其它目的,你应该避免将活动,并完成类似 Activity.getApplicationContext()

In your case, you can get the Context from the View that is passed into the method. However, if you need the Context for other purposes, you should avoid passing Activity and do something like Activity.getApplicationContext().

这样做的理由是,如果对象,你传递一个活动进入生活比活动,参考较长到活动将prevent的Andr​​oid从做适当的垃圾收集( GC ),消耗不必要的内存。这就是所谓的内存泄漏

The reason for this is if the object you pass an Activity into lives longer than the Activity, the reference to the Activity will prevent Android from doing proper Garbage Collection (GC) and consume unnecessary memory. This is called a "memory leak".

编辑:

要处理,你需要调用的情况 Activity.findViewById()对这些事情记在心里。首先,这是一个查看办法(的 http://developer.android.com/reference/android/view/View.html#findViewById(INT)),所以一定要从正确的观点来调用它。

To handle situations where you need to call Activity.findViewById() keep these things in mind. First, that is a View method (http://developer.android.com/reference/android/view/View.html#findViewById(int)) so be sure to call it from the correct view.

第二,如果你需要一个查看活动你应该通过它作为一个的WeakReference

Second, if you need a View from an Activity you should pass it in as a WeakReference