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); |
Thanks for this tutorial, it's useful.
回覆刪除