GetSystemService from non Activity class

I need to get LAC and Cid codes in android app. However, I need to do this inside the not-Activity class. The code I found is the following:

TelephonyManager telephonyManager =(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
int cid = cellLocation.getCid();
int lac = cellLocation.getLac();

      

However, the setSystemService method is only present in Activity classes, and I haven't found anything to send "some kind of activity" to the class. Is there a way to do this without activity?

+3


source to share


2 answers


You can pass context

as an argument to the constructor

class. Inside constructor

you can initialize TelephonyManager

.

Example:

In the class

public class MyClass {

private TelephonyManager mTelephonyManager;

public MyClass(Context context) {
    mTelephonyManager =(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
}

      



}

In action

public class MyActivity extends Activity {

....

//Initializing class
MyClass myClass = new MyClass(this);

..

      

+3


source


You just need to pass an object Context

to call getSystemService()

from it. You can also use object Activity

like Activity

extends Context

.



Then just call context.getSystemService()

0


source







All Articles