android设备ID生成给出错误

时间:2014-01-01 07:33:11

标签: android device telephonymanager

在我的 Android 应用中,我想生成设备ID 。首先,我只是在活动中生成设备ID ,如下所示。它运作良好。

TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String uid = tManager.getDeviceId();
return uid;

然后我想创建一个设备对象并尝试在其中作为方法执行上述操作,

public String generateDeviceId() {
    // DeviceId = deviceId;

    TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String uid = tManager.getDeviceId();
    return uid;

}

它提供语法错误并说

  

未定义类型为Device

的方法getSystemService(String)

那么我该如何解决这个问题呢。我想创建一个设备类并创建设备对象并完成我的工作。可能吗。我导入了以下内容,

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

所以有可能。有人可以帮我做我的工作。感谢。

3 个答案:

答案 0 :(得分:2)

尝试在Device类中更改此方法

public String generateDeviceId(Context context) {
   // DeviceId = deviceId;
   TelephonyManager tManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
   String uid = tManager.getDeviceId();
   return uid;
}

从您的Activity致电时,只需传递当前活动参考this

即可
 deviceObject.generateDeviceId(this);

答案 1 :(得分:1)

当您尝试在android活动类之外访问getSystemService时,您必须需要上下文。

    TelephonyManager tm = 
(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);

这是完整的方法

    public String generateDeviceId(Context context) {
        // DeviceId = deviceId;

        TelephonyManager tManager = (TelephonyManager)context. getSystemService(Context.TELEPHONY_SERVICE);
        String uid = tManager.getDeviceId();
        return uid;

}

由于

答案 2 :(得分:1)

getSystemService(String)需要一个上下文。所以你需要将上下文传递给Non Activity类的构造函数并在那里使用它。

new  Device(ActivityName.this);

然后

Context mContext;
public Device(Context context) 
{
     mContext = context;
} 

然后

TelephonyManager tManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);

http://developer.android.com/reference/android/content/Context.html#getSystemService(java.lang.String)