如何正确使用另一个包的功能 - android

时间:2013-01-07 13:04:36

标签: android package

我有一个名为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

如何解决这个问题?

5 个答案:

答案 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()进行静态引用,因为方法不是静态的。您有两个选择:

  1. 将函数和方法checkInternet()声明为static。因为它是Utility类的方法更合适的方式。因此,您可以在现在使用它时调用它。
  2. 2.或者创建类的对象为

    Functions funObj = new Functions();
    

    然后使用object作为

    调用方法
    public void Login (View v){
        if(funObj.checkInternet()){
            //do other stuff
        }
    
        else {
            //do other stuff
        }
    }
    

    希望它有所帮助。