在Android编程中,Context类到底是什么,它的用途是什么?

我在developer site上阅读了有关它的内容,但我无法清楚地理解它。

最佳答案

简单地说:

顾名思义,它是应用程序/对象当前状态的上下文。它使新创建的对象了解正在发生的事情。通常,您调用它来获取有关程序另一部分( Activity 和程序包/应用程序)的信息。

您可以通过调用getApplicationContext()getContext()getBaseContext()this来获取上下文(在从Context扩展的类中,例如Application,Activity,Service和IntentService类)。

上下文的典型用法:

  • 创建新对象:
    创建新的 View ,适配器,监听器:
    TextView tv = new TextView(getContext());
    ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
    
  • 访问标准公共(public)资源:
    诸如LAYOUT_INFLATER_SERVICE,SharedPreferences之类的服务:
    context.getSystemService(LAYOUT_INFLATER_SERVICE)
    getApplicationContext().getSharedPreferences(*name*, *mode*);
    
  • 隐式访问组件:
    关于内容提供商,广播,意图
    getApplicationContext().getContentResolver().query(uri, ...);
    
  • 09-26 18:49
    查看更多