user3788866
user3788866

Reputation: 118

How to get device imei number in non-activity class?

I am trying to make a non-activity class for some useful functions like getting device Imei number. But when i am using

    mngr = (TelephonyManager)myContext(Context.TELEPHONY_SERVICE);

it is giving me this error:

    The method myContext(String) is undefined for the type FunctionsForWorking

Upvotes: 1

Views: 1878

Answers (2)

Emisael Carrera
Emisael Carrera

Reputation: 687

I'm calling a thread in my App.java class -> OnCreate method, and I'm getting the device IMEI like this:

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

String IMEI = telephonyManager.getDeviceId();

It's enough passing the context through parameters to your implementation

Upvotes: 1

Psypher
Psypher

Reputation: 10829

Service has its own context you can use that, for your concern about getting the IMEI in a service use below code:

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v("ranjith","started service");
        TelephonyManager c=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        String device_id = c.getDeviceId();
        return super.onStartCommand(intent, flags, startId);
    }
}

For your question about how to pass context to non-Activity class, the answer is just pass it as a parameter in the constructor to the other class, for eg:-

public class myActivityclass extends Activity{
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout1);
        nonActivityclass c=new nonActivityclass(Context context);
        -----------------------------
}

In the non-Activity class:

public class nonActivityclass{
Context context;
public nonActivityclass(Context context)
{
         this.context=context
}
//you can use context now
}

Upvotes: 0

Related Questions