在A.java里写了如下一段代码检测网络,在onCreate能正常获得"Mobile"值;然后在B.java onCreate里写了A gnws=new A();gnws.getnetworkstate();出现了如
“System services not available to Activities before onCreate()” 引用后就不能使用了?求解,新手!!!!
public String getnetworkstate() {
String returnint;
try {
ConnectivityManager connectivityManager = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo net = connectivityManager.getActiveNetworkInfo();
if (net == null) {
returnint = "not";
} else {
returnint = net.getTypeName();
} } catch (Exception e) {
// TODO: handle exception
Log.v("程序出错:", e.getMessage());
returnint="not";
}
return returnint;
}
“System services not available to Activities before onCreate()” 引用后就不能使用了?求解,新手!!!!
public String getnetworkstate() {
String returnint;
try {
ConnectivityManager connectivityManager = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo net = connectivityManager.getActiveNetworkInfo();
if (net == null) {
returnint = "not";
} else {
returnint = net.getTypeName();
} } catch (Exception e) {
// TODO: handle exception
Log.v("程序出错:", e.getMessage());
returnint="not";
}
return returnint;
}
解决方案 »
- 求教,Preference如何实现长按监听
- 求一小Demo 安卓的 邮箱或者链接都可以,顶者有分
- Android 2.3 上实现视频通话
- 为什么,从一个Activity 跳到另一个Activity 出莫名的错误?
- android的bug,很无语的bug。。。呜呜呜呜。。。。
- 关于android中Activity与xml的问题,求高手解答
- EditText被弹出来的输入框挡住
- android 如何实现串行化
- 初装android SDK 启动AVD 屏幕横屏,内容也是横的
- Android客户端http服务器连接出问题
- 点击浏览按钮在相册中浏览不到自定义相机拍到的图片,开机后就能看见
- android下的v4l2 select timeout问题
解决方法:
将A代码改为:
public String getnetworkstate(Context context) {
String returnint;
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo net = connectivityManager.getActiveNetworkInfo();
if (net == null) {
returnint = "not";
} else {
returnint = net.getTypeName();
} } catch (Exception e) {
// TODO: handle exception
Log.v("程序出错:", e.getMessage());
returnint="not";
}
return returnint;
}
然后在B.java onCreate里写了A gnws=new A();gnws.getnetworkstate(XXXXActivity.this);
但问题在于你自己new 了一个Activity实例,例如 Activity A = new ActivityXXX(),显然,对应它而言,它的Context属性来说是无效的,即 ConnectivityManager connectivityManager = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);这段代码是有问题的。
修改原因同LS 。 预知原因,请看我的这篇博客:Android中Context详解 ---- 你所不知道的Context
http://blog.csdn.net/qinjuning/article/details/7310620