我在 Android 应用程序中使用以下代码来监控网络连接。
ConnectivityManager conMgr =
(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
如果我在任何 Activity 中,这段代码都可以正常工作,而如果我在通用类中,我就不能调用 方法
getSystemService
我该如何解决这个问题?
最佳答案
如果您想在非 Activity 类中访问 getSystemService
,则只需使用 Constructor 将当前 Activity Context 传递给 Non Activity 类:
public class nonActivity{
Context context;
ConnectivityManager conMgr ;
pulblic nonActivity(Context context){
this.context=context;
// now get getSystemService as :
this.conMgr =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
}
并将当前 Activity Context 传递给非 Activity 类:
nonActivity nonactivityobj=new nonActivity(Your_Current_Activity.this);
关于android - Android 应用程序中的连接管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14068827/