如何在Android中使用上下文?

问题描述 投票:0回答:1
WifiManager wifimanager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

为什么在这里使用context

任何人都可以解释吗?

android android-wifi android-context
1个回答
1
投票

根据official docs

上下文是有关应用程序环境的全局信息。 这是一个抽象类,其实现由 Android系统。它允许访问特定于应用程序的资源和 类,以及对应用程序级操作(例如, 发射活动,广播和接收意图等]

如果要使用作为[[特定于应用程序的资源]的WIFI_SERVICE,则>您必须使用上下文来检索资源。如果您在活动或片段内部,则无需使用getApplicationContext().getSystemService(Context.WIFI_SERVICE)对象就可以直接调用context,因为活动和片段是从Context类继承的。

但是,如果您处于非活动或片段类中,则必须将上下文对象从活动或片段(带有构造函数或设置器)传递给该类,以获得特定于应用程序的资源。

示例

public class AnyClass{ private Context context; public AnyClass(Context context){ this.context = context; } ... WifiManager wifimanager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE); }

© www.soinside.com 2019 - 2024. All rights reserved.