using Context in a static environment  [ 715 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;
  }
#sidebar a { color:#fff; } #sidebar ul ul li { color: #DEF585; } #sidebar h2 { color: #fff; } #sidebar ul p, #sidebar ul select { color: #BEDDBE; } #backfly { background: url(images/golfBallWallPaper.jpg) left bottom fixed repeat-x #65a51d; }