2015年5月6日 星期三

[Android] Making static reference to the non-static method

To get the MAC address of the user's device (in my case I also removed the colleen for manipulation), we can use:

1
2
3
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String MAC = info.getMacAddress().replace(":", "");

If multiple Activities are to use this information, we can copy paste these three lines for every Activity, or we can create a global function with these three lines and reuse the code. To do this we must not simply:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class GlobalVariable extends Application{
 public String getMAC(){
  WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
  WifiInfo info = manager.getConnectionInfo();
  return info.getMacAddress().replace(":", "");
 }
}

//Usage:
GlobalVariable global = new GlobalVariable();
global.getMAC();

This will result in error

If you simply set getMAC() to static, you will get a compile error:
Cannot make a static reference to the non-static method getSystemService(String)

To solve this, simply pass a context into the static method like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class GlobalVariable extends Application{
 public static String getMAC(Context ctx){
  WifiManager manager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
  WifiInfo info = manager.getConnectionInfo();
  return info.getMacAddress().replace(":", "");
 }
}

//Usage:
GlobalVariable.getMAC(this);

1 則留言: