【发布时间】:2019-05-26 11:06:27
【问题描述】:
我真的是 android 新手,我正在开发一个需要检查设备是否连接到互联网的应用程序。这是我不断遇到的错误。
java.lang.IllegalStateException:系统服务不可用于 android.app.Activity.getSystemService 的 onCreate() 之前的活动
public class Fragment_Home extends Fragment implements Class_Home_Adapter.OnItemClickListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
readJsonFile();
return v;
}
private void readJsonFile() {
Class_Check_Internet_Connection class_check_internet_connection = new Class_Check_Internet_Connection();
Log.e(TAG, "Internet Status: " + class_check_internet_connection.internetStatus());
}
这是我用来检查互联网连接的类
public class Class_Check_Internet_Connection extends Activity {
public static boolean isNetworkAvailable(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if ((activeNetworkInfo != null)&&(activeNetworkInfo.isConnected())){
return true;
}else{
return false;
}
}
public boolean internetStatus() {
boolean isNetworkAvailable = Class_Check_Internet_Connection.isNetworkAvailable(this);
return isNetworkAvailable;
}
}
【问题讨论】:
-
没有理由在
Class_Check_Internet_Connection类中“扩展活动”。因为您正在扩展Activity,所以该类需要onCreate()方法,其中将创建Context。但是您正在“绕过”Context的创建 ...所以this为空!