Why does Android require a Context to access a resource?

I get why Android requires you to pass a Context object when trying to get a view for example, show a Toast, etc.

However, I don't really get the point for requiring it to access resources that could be shared by different Contexts in your application.

I several times found myself trying to access a resource from a utility class using a static method or something along those lines, and find it pretty annoying to require a passing of a Context param.

I fail to see where something could go south with this.


From the official documentation :

Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

In clear, the context is the middleman between the telephone resource, and your code. And it seems logical, that you cannot access to this from everywhere.

The reason you can only access to Context in Activity and Application classes, is because both derives from Context :

java.lang.Object

↳ android.content.Context

  ↳ android.content.ContextWrapper

      ↳ android.view.ContextThemeWrapper

          ↳ android.app.Activity

Extend Application class by your own public class MyApp extends Application and register MyApp in your manifest and have MyApp something like this:

class MyApp extends Application {
...
private static ApplicationContext context;

@Override
public static void onCreate() {
  super.onCreate();
  context = this;
}

public static String string(int resId) {
   return context.getString(resId);
}

}

Then you can do MyApp.string(R.id.mystring) from everywhere. You can do the same for other resource types.

You can also do (MyApp)getApplication() if you prefer so.

链接地址: http://www.djcxy.com/p/60000.html

上一篇: navigationController弹出视图时取消选定单元格的内容?

下一篇: 为什么Android需要上下文来访问资源?