我有一个名为omer.ludlowcastle
的主程序包和另一个程序包omer.ludlowcastle.utils
我在omer.ludlowcastle.utils
中写了这个函数:
public boolean checkInternet (){
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
} else {
Toast.makeText(getApplicationContext(), "You are not connected to Internet", Toast.LENGTH_LONG).show();
return false;
}
}
我在主包中的一个活动中使用此函数:
public void Login (View v){
if(omer.ludlowcastle.utils.functions.checkInternet()){
//do other stuff
}
else {
//do other stuff
}
}
但是if
大括号中的行会出现以下错误:
Cannot make a static reference to the non-static method checkInternet() from the type functions
如何解决这个问题?
答案 0 :(得分:1)
使方法成为静态:
public static boolean checkInternet()
或者,获取checkInternet函数所在的任何类的对象,并调用其checkInternet()
函数,但是创建静态方法可能不会占用大量资源。
答案 1 :(得分:0)
您必须将utils包中的方法设置为static。
public static boolean checkInternet()
实用程序类用于make静态方法,它们不保存状态,因此如果编写实用程序类,则方法必须是静态的。这是一般用途。
答案 2 :(得分:0)
修改方法并使其静止
public static boolean checkInternet (){
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
} else {
Toast.makeText(getApplicationContext(), "You are not connected to Internet", Toast.LENGTH_LONG).show();
return false;
}
}
答案 3 :(得分:0)
只需将您的方法设为静态:
public static boolean checkInternet (){
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
} else {
Toast.makeText(getApplicationContext(), "You are not connected to Internet", Toast.LENGTH_LONG).show();
return false;
}
}
答案 4 :(得分:0)
您正在获取无法对类型函数中的非静态方法checkInternet()进行静态引用,因为方法不是静态的。您有两个选择:
2.或者创建类的对象为
Functions funObj = new Functions();
然后使用object作为
调用方法public void Login (View v){
if(funObj.checkInternet()){
//do other stuff
}
else {
//do other stuff
}
}
希望它有所帮助。