Search code examples
androidtelephonymanager

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

Solution

  • 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
    }