using Context in a static environment (simple way) [ 854 views ]
Goal: find a simple way to reach a usable context in a static method
I have found many complicated ways to get a usable context, but I have an easy and simple way.
1. we need a static class, with a global context variable
public class GLB { ... public static Context context; // context or static use ... public static Context globalContext(){ // get the global context return GLB.context; } ... }
2. set this variable in the main activity
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GLB.context = getApplicationContext(); ... }
3. and of course we can get this context anywhere where we want
public static String deviceID_IMEI(){ TelephonyManager tm = (TelephonyManager)globalContext().getSystemService(Context.TELEPHONY_SERVICE); String device_id = tm.getDeviceId(); return device_id; }
so easy enough…