【问题标题】:Cannot make a static reference to the non-static method getIMEI() from the type Util无法从 Util 类型对非静态方法 getIMEI() 进行静态引用
【发布时间】:2013-01-15 13:56:11
【问题描述】:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String test =  Util.imei();
}


import android.content.Context;
import android.telephony.TelephonyManager;

public class Util{
    Context context;

    public Util(Context context) {
        this.context = context;
    }

    public String imei() {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }
}

出现错误“无法从 Util 类型对非静态方法 imei() 进行静态引用”。 如果我将行更改为:

public static String imei() {
    ...
    static Context context;

我收到错误并崩溃应用程序。("E/AndroidRuntime(629): Caused by:java.lang.NullPointerException")

【问题讨论】:

    标签: android exception imei


    【解决方案1】:

    两种写法:

    第一个 非静态

    public class Util {
        Context context;
    
        public Util(Context context) {
            this.context = context;
        }
    
        public String imei() {
            TelephonyManager telephonyManager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            return telephonyManager.getDeviceId();
        }
    }
    

    然后在onCreate方法中

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Util u = new Util(this);
        String test =  u.imei();
    }
    

    第二次 静态

    public class Util {
        public static String imei(Context context) {
            TelephonyManager telephonyManager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            return telephonyManager.getDeviceId();
        }
    }
    

    然后在onCreate方法中

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String test =  Util.imei(this);
    }
    

    【讨论】:

    • 我假设您在 Activity 中创建了 AsyncTask。然后写String test = Util.imei(TheActivity.this);,否则你必须构造AsyncTask传递context
    【解决方案2】:

    您正在尝试访问类中的方法而不为它创建对象。只有静态方法我们可以这样调用。在您的情况下,为Util 创建一个对象并使用该对象调用imei()

    喜欢,

    Util utilObj = new Util();
    String imei = utilObj.imei();
    

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      在访问其方法之前首先创建 Util 类的引用。

      Util util = new Util();
      String _imei = util.imei();
      

      【讨论】:

        猜你喜欢
        • 2015-08-18
        • 1970-01-01
        • 1970-01-01
        • 2013-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多