using Context in a static environment [ 844 views ]
Goal: get Context in a static method
Sometimes we need a context in a static method, but we don’t have… Let’s dig one.
public static Application getGlobalContext(){ try { final Class<?> activityThreadClass = Class.forName("android.app.ActivityThread"); final Method method = activityThreadClass.getMethod("currentApplication"); return (Application) method.invoke(null, (Object[]) null); } catch (final ClassNotFoundException e) { // handle exception } catch (final NoSuchMethodException e) { // handle exception } catch (final IllegalArgumentException e) { // handle exception } catch (final IllegalAccessException e) { // handle exception } catch (final InvocationTargetException e) { // handle exception } return null; }
example: get the device ID (IMEI) in a static function.
public static String deviceID_IMEI(){ TelephonyManager tm = (TelephonyManager)getGlobalContext().getSystemService(Context.TELEPHONY_SERVICE); String device_id = tm.getDeviceId(); return device_id; }