有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从活动传递给非活动构造函数的上下文实例是什么?

Android API中的几个类需要在其构造函数中使用Context参数,例如ArrayAdapterSQLiteOpenHelperIntent。当从Activity内部创建这样一个对象时,哪个上下文实例更适合传递给它们:this(活动实例本身)或活动的getApplicationContext()方法返回的对象,为什么

到目前为止,我已经使用了这两种方法,并没有看到结果功能上的任何差异。有什么经验法则吗


共 (1) 个答案

  1. # 1 楼答案

    getApplicationContext()方法的文档中:

    Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.

    Consider for example how this interacts with {@ #registerReceiver(BroadcastReceiver, IntentFilter)}:

    • If used from an Activity context, the receiver is being registered within that activity. This means that you are expected to unregister before the activity is done being destroyed; in fact if you do not do so, the framework will clean up your leaked registration as it removes the activity and log an error. Thus, if you use the Activity context to register a receiver that is static (global to the process, not associated with an Activity instance) then that registration will be removed on you at whatever point the activity you used is destroyed.

    • If used from the Context returned here, the receiver is being registered with the global state associated with your application. Thus it will never be unregistered for you. This is necessary if the receiver is associated with static data, not a particular component. However using the ApplicationContext elsewhere can easily lead to serious leaks if you forget to unregister, unbind, etc.