Context 是一个核心类,Context是一个场景,它是一个抽象类。
在 Android 中,Context 是一个核心类,用于提供应用程序的全局信息和操作环境。
它是一个抽象类,实际上有多个实现类,最常用的是 Activity 和 Application 类。
Context 提供了访问应用程序资源、启动活动(Activity)、发送广播、访问数据库等功能。以下是一些 Context 的主要功能和用法:
-
获取资源:
-
getResources(): 获取应用程序的资源,如字符串、图像等。
-
getString(int resId): 获取字符串资源。
-
String appName = context.getResources().getString(R.string.app_name);
-
启动活动(Activity):
-
startActivity(Intent intent): 启动一个新的活动。
-
Intent intent = new Intent(context, AnotherActivity.class);
context.startActivity(intent);
-
发送广播:
-
sendBroadcast(Intent intent): 发送广播。
-
Intent broadcastIntent = new Intent("custom.action");
context.sendBroadcast(broadcastIntent);
-
访问文件和数据库:
-
openFileInput() 和 openFileOutput(): 用于访问应用程序的私有文件。
-
getDatabasePath(String name): 获取数据库的路径。
-
File file = context.getFileStreamPath("filename.txt");
-
获取系统服务:
-
getSystemService(String serviceName): 获取系统服务,如 LOCATION_SERVICE、SENSOR_SERVICE 等。
-
LocationManager locationManager = (LocationManager)
context.getSystemService(Context.LOCATION_SERVICE);
-
应用程序信息:
-
getPackageName(): 获取应用程序的包名。
-
getPackageManager(): 获取包管理器。
-
String packageName = context.getPackageName();
Context 的实际实现类包括:
-
Activity: 表示应用程序中的一个活动。
-
Service: 表示应用程序中的一个服务。
-
Application: 表示整个应用程序的上下文,是一个全局的上下文。
注意:在某些情况下,由于 Context 对象可能会引起内存泄漏,需要谨慎使用。
在需要长时间持有 Context 引用的地方,考虑使用 ApplicationContext 或通过 WeakReference 避免内存泄漏问题。
在 Android 开发中,有时候需要长时间持有 Context
引用,但长时间引用 Context
可能导致内存泄漏。为了避免这个问题,可以考虑使用 ApplicationContext
或通过 WeakReference
来持有 Context
引用。
使用 ApplicationContext 的例子:
public class MyApplication extends Application {
private static Context appContext;
@Override
public void onCreate() {
super.onCreate();
appContext = getApplicationContext();
}
public static Context getAppContext() {
return appContext;
}
}
在这个例子中,通过自定义 Application
类并在其 onCreate
方法中保存 ApplicationContext
的引用。然后,通过静态方法 getAppContext
来获取应用程序级别的 Context
引用。
使用 WeakReference 的例子:
public class MyClass {
private WeakReference<Context> contextReference;
public MyClass(Context context) {
contextReference = new WeakReference<>(context);
}
public Context getContext() {
return contextReference.get();
}
}
在这个例子中,MyClass
使用 WeakReference
来持有 Context
引用。这样,如果 Context
不再被其他强引用持有,垃圾回收器会在适当的时候回收 WeakReference
,从而避免内存泄漏。
使用 ApplicationContext
或 WeakReference
来持有 Context
引用是一种良好的做法,特别是在长时间持有 Context
的场景中,例如在单例中或在异步任务中。这有助于防止因为长时间持有 Activity
或 Service
的引用而导致的内存泄漏问题。
import android.content.Context;
public class CustomManager{
private static CustomManager mInstance;
private Context mContext;
private CustomManager(Context context){
this.mContext = context;
}
public static synchronized CustomManager getInstance(Context context){
if (mInstance == null){
mInstance = new CustomManager(context);
}
return mInstance;
}
}
长时间持有 Context
的场景中,例如在单例中或在异步任务中,如果使用WeakReference的方式,可能会有回收后,再引用对象所引起的空指针的问题。