0
我想看看用戶是否具有互聯網連接時,應用程序啓動:無法啓動活動ComponentInfo java.lang.IllegalStateException:的onCreate()之前系統服務不提供給活動
package nco.supp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import nco.supp.Status;
import nco.supp.Register;
public class ncosuppActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
NetworkManager networkManager = new NetworkManager();
if (!networkManager.haveNetworkConnection()) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setPositiveButton("Ok", null);
}
Button loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ncosuppActivity.this, Status.class));
}
});
Button registerButton = (Button) findViewById(R.id.registerButton);
registerButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ncosuppActivity.this, Register.class));
}
});
}
}
package nco.supp;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkManager extends Activity{
public boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
}
我收到此錯誤:
java.lang.RuntimeException: Unable to start activity ComponentInfo{nco.supp/nco.supp.ncosuppActivity}:
java.lang.IllegalStateException: System services not available to Activities before onCreate()
任何想法?
爲什麼要擴展NetworkManager的Activity,當你只想用Object的時候。 – kosa
getSystemService需要活動 – Waqleh
我認爲最簡單的方法可能是將代碼haveNetworkConnection移動到ncosuppActivity並移除NetworkManager networkManager = new NetworkManager(); line和NetworkManager類。 – kosa