using Context in a static environment (simple way)  [ 696 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…

#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; }