跳转到内容

Context

来自代码酷

Context[编辑 | 编辑源代码]

Context(上下文)是Android开发中的一个核心概念,它提供了访问应用资源和系统服务的接口,代表了应用环境的全局信息。作为Android应用的基础组成部分,Context允许组件获取应用特定的功能和服务。

概述[编辑 | 编辑源代码]

Context是一个抽象类,其具体实现由Android系统提供。主要功能包括:

  • 访问应用资源(如字符串、图形等)
  • 启动Activity、Service等组件
  • 获取系统服务(如布局填充器、通知管理器等)
  • 访问应用特定目录和文件

在Android中,Context主要有两种形式: 1. Application Context - 整个应用的生命周期上下文 2. Activity Context - 与特定Activity关联的上下文

主要用途[编辑 | 编辑源代码]

1. 访问资源[编辑 | 编辑源代码]

通过Context可以访问应用资源:

String appName = getContext().getString(R.string.app_name);
Drawable icon = getContext().getDrawable(R.drawable.app_icon);

2. 启动组件[编辑 | 编辑源代码]

使用Context启动其他Android组件:

// 启动Activity
Intent intent = new Intent(getContext(), TargetActivity.class);
getContext().startActivity(intent);

// 启动Service
Intent serviceIntent = new Intent(getContext(), MyService.class);
getContext().startService(serviceIntent);

3. 获取系统服务[编辑 | 编辑源代码]

通过Context获取各种系统服务:

// 获取布局填充器
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

// 获取通知管理器
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);

Context类型比较[编辑 | 编辑源代码]

Context类型 生命周期 适用场景
Application Context 整个应用生命周期 需要长生命周期对象的场景
Activity Context Activity生命周期 UI相关操作

使用注意事项[编辑 | 编辑源代码]

  • 内存泄漏:避免长时间持有Activity Context引用
  • 类型选择:UI操作使用Activity Context,后台任务使用Application Context
  • 服务获取:不同Context获取的系统服务可能行为不同

实际应用示例[编辑 | 编辑源代码]

自定义Application类[编辑 | 编辑源代码]

public class MyApplication extends Application {
    private static Context appContext;

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

    public static Context getAppContext() {
        return appContext;
    }
}

工具类中使用Context[编辑 | 编辑源代码]

public class NetworkUtils {
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) 
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnected();
    }
}

相关概念[编辑 | 编辑源代码]

参见[编辑 | 编辑源代码]