在Android中使用电话管理器找到IMEI号码管理器、号码、电话、Android

2023-09-05 09:47:35 作者:可爱界扛把子

我米非常新的Andr​​oid开发。 我想找到手机并使用的IMEI号android.telephony.TelephonyManager;

I m very new to Android Development. I want to find the IMEI number of the phone and using "android.telephony.TelephonyManager;".

TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();

现在的编译器说。 背景不能被解析为一个变量。 任何人能帮助我吗?什么步骤我米失踪 我也包括在XML的用户权限。

Now the compiler says. Context cannot be resolved to a variable. Any one can help me ? What step I m missing I have also included user permission in XML.

推荐答案

确认你的进口,你应该导入: android.content.Context

Verify your Imports , you should import : android.content.Context ,

然后用这个code:

TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// get IMEI
String imei = tm.getDeviceId();
//get The Phone Number
String phone = tm.getLine1Number();

或者直接:用这样的:

Or directly : use this :

TelephonyManager tm = (TelephonyManager) getSystemService(android.content.Context.TELEPHONY_SERVICE);

编辑: *的你应该通过上下文到新类的构造函数:的*

public class YourClass {
    private Context context;

    //the constructor 
    public YourClass( Context _context){

        this.context = _context;
        //other initialisations .....

    }

   //here is your method to get the IMEI Number by using the Context that you passed to your class
   public String getIMEINumber(){
       //...... place your code here 
   }

}

而在你的活动,实例化类和上下文传递给它这样的:

And in your Activity , instanciate your class and pass the context to it like this :

YourClass instance = new YourClass(this);
String IMEI = instance.getIMEINumber();