Context用于获取application状态信息。为Activities,Fragments,Services访问resource files,images,themes,styles以及external directory location。还能访问android内建服务(services),例如layout inflation,keyboard,查找content providers(内容提供器)。
在许多情况下需要context的时候,我们只是简单的在当前activity实例中进行传递。在另外情况下,在activity创建的对象里,例如adapters或者fragment,我们需要在activity实例的对象里进行传递。而在activity外(例如application或者service)时,我们可以使用“application”context来代替。
明确创建一个component
// Provide context if MyActivity is an internal activity.
Intent intent = new Intent(context, MyActivity.class);
startActivity(intent);
需要两个信息:
1、package name,表明包含该component的application;
2、该component的完整java类名。
创建一个View
TextView textView = new TextView(context);
context包含以下view所需的信息:
1、device的screen size和尺寸,用于dp,sp和像素之间转换;
2、样式属性;
3、onClick属性的activity参考
inflating an XML Layout File
为了inflate一个XML Layout文件进入memory,使用context取LayoutInflater。(???)
// The context contains a reference to the main Looper,
// which manages the queue for the application's main thread.
Intent broadcastIntent = new Intent("custom-action");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
恢复系统服务
从application发送notification,需要NotificationManager系统服务:
// Context objects are able to fetch or start system services.
NotificationManager manager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int notificationId = 1;
// Context is required to construct RemoteViews
Notification.Builder builder =
new Notification.Builder(context).setContentTitle("custom title");
notificationManager.notify(notificationId, builder.build());
application Vs Activity Context
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/MyCustomTheme">
Adapters
Array Adapter
当ListView构建adapters时,通常在layout inflation中调用getContext()。
if (convertView == null) {
convertView =
LayoutInflater
.from(getContext())
.inflate(R.layout.item_user, parent, false);
}
> If you instantiate the ArrayAdapter with the application context,however, you are likely to notice that the themes/styles are not beingapplied. For this reason, make sure you are passing in the Activitycontext in these cases.