如何在静态方法中使用电话管理器和位置管理器服务等系统服务?


ConnectivityManager connManager = (ConnectivityManager) SystemService(CONNECTIVITY_SERVICE);
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
audioManager = (AudioManager) getSystemService

(Context.AUDIO_SERVICE(;

将上下文作为参数传递:

public static void foo(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
SensorManager sm = (SensorManager) context.getSystemService(SENSOR_SERVICE);
}

并像使用它一样使用

foo(this);

您可以按如下方式实现它:

public class AccessData{
public static void doSomething(final Context context){
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// Use TelephonyManager object.
}
}

您可以从活动访问此方法,如下所示:

AccessData.doSomething(this);

在 Xamarin.Android 中(不确定本机 Android(,您可以从以下任何位置访问上下文:Application.Context

这样,您无需将其作为参数传递。

相关内容

最新更新