有人可以解释为什么我收到错误:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.project/com.project.Deals}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
当我使用下面的两个课程时,现在已经这么做了。我很感激帮助
public class Deals extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText("This is the Artists tab");
setContentView(textview);
NetworkConnection nc = new NetworkConnection();
boolean networkAvail = nc.isNetworkConnAvail();
if (networkAvail == true){
}
}
};
public class NetworkConnection extends Activity {
/** Called when the activity is first created. */
public boolean isNetworkConnAvail() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null)
return networkInfo.isConnected();
return false;
}
}
答案 0 :(得分:1)
将此添加到您的清单:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
删除它:
extends Activity
class NetworkConnection
中的
<强>更新强>
更好的想法是将代码更改为:
public class Deals extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
boolean networkAvail = isNetworkConnAvail();
if (networkAvail == true){
//do something
}
}
public boolean isNetworkConnAvail() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null)
return networkInfo.isConnected();
return false;
}
}
`
答案 1 :(得分:1)
问题出在您的NetworkConnection类中,您从未调用onCreate尝试此操作:
public boolean isNetworkConnAvail(Context context) {
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null)
return networkInfo.isConnected();
return false;
}
从你的其他班级这样称呼它:
nc.isNetworkConnAvail(this);
或者在NetworkConnection的构造函数中调用超类的onCreate方法。如果您只是为了能够使用getSystemService而扩展Activity,那么您也可以不扩展Activity并且只在构造函数或方法本身中传递Context,因为这将使您可以访问这些方法: )