-1

In my Android app I wanna generate the device ID. At first I just generate the device ID inside an activity as below. It worked fine.

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

Then I wanna create a device object and try to do the above in it as a method,

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

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

}

It gives an syntax error and say

The method getSystemService(String) is undefined for the type Device

So how can I fix this. I wanna create a device class and create device object and do my stuff. Is it possible. I imported the below,

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

So is it possible. Can someone help me to do my work. Thanks.

Samantha Withanage
  • 3,811
  • 10
  • 30
  • 59

3 Answers3

1

When you try to access getSystemService outside of the android activity class then you must need the context.

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

and this are complete method

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

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

}

Thanks

Md Abdul Gafur
  • 6,213
  • 2
  • 27
  • 37
1

getSystemService(String) needs a context. So you need to pass context to the constructor of Non Activity class and use it there.

new  Device(ActivityName.this);

Then

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

Then

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

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

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
1

Try changing this method in your Device class

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

and While calling from your Activity , just pass the current activity reference this

 deviceObject.generateDeviceId(this);
Jagadesh Seeram
  • 2,630
  • 1
  • 16
  • 29