使用应用程序上下文中无处不在? [英] Using Application context everywhere?

查看:132
本文介绍了使用应用程序上下文中无处不在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Android应用程序,有什么不对的以下做法:

In an Android app, is there anything wrong with the following approach:

public class MyApp extends android.app.Application {

    private static MyApp instance;

    public MyApp() {
    	instance = this;
    }

    public static Context getContext() {
    	return instance;
    }

}

和无处不在传递(如SQLiteOpenHelper),其中环境是必需的(而不是漏水,当然)?

and pass it everywhere (e.g. SQLiteOpenHelper) where context is required (and not leaking of course)?

推荐答案

有几个这种方法潜在的问题,但在很多情况下(比如你的例子),它会很好地工作。

There are a couple of potential problems with this approach, though in a lot of circumstances (such as your example) it will work well.

在特别是当有任何与要求背景下的GUI处理处理你要小心。例如,如果你通过应用程序上下文到 LayoutInflater ,你会得到一个异常。一般来说,你的做法是极好的:这是很好的做法,该活动中使用活动的背景下,并通过上下文之外的活动的范围的避免内存泄漏的。

In particular you should be careful when dealing with anything that deals with the GUI that requires a Context. For example, if you pass the application Context into the LayoutInflater you will get an Exception. Generally speaking, your approach is excellent: it's good practice to use an Activity's Context within that Activity, and the Application Context when passing a context beyond the scope of an Activity to avoid memory leaks.

此外,作为替代你的模式,你可以使用电话 getApplicationContext()在上下文对象(如活动)的快捷方式,以获得应用程序上下文。

Also, as an alternative to your pattern you can use the shortcut of calling getApplicationContext() on a Context object (such as an Activity) to get the Application Context.

这篇关于使用应用程序上下文中无处不在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆