Android开发中常用的工具类

提示工具类(Snackebar&Toast)

1
2
3
4
5
6
7
8
9
10
11
12
13
public class SnackbarUtil {
private static Snackbar snackbar;
public static void show(View view, String message) {
if (snackbar == null) {
snackbar = Snackbar.make(view, message, Snackbar.LENGTH_SHORT);
} else {
snackbar.setText(message);
}
snackbar.show();
}
}

Log打印工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class LogUtil {
private static boolean ENABLE = true;
public static void v(String tag, String msg) {
if (ENABLE) {
Log.v(tag, msg);
}
}
public static void d(String tag, String msg) {
if (ENABLE) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (ENABLE) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (ENABLE) {
Log.w(tag, msg);
}
}
public static void e(String tag, String msg) {
if (ENABLE) {
Log.e(tag, msg);
}
}
}

判断网络连接的工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ConnUtil {
public static boolean isNetConnected(Context context) {
if (context != null) {
ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
return info.isAvailable();
}
}
return false;
}
}

Wifi下获取手机的IP地址和MAC地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public String getLocalIpAddress() {
try{
for(Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for(Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if(!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch(SocketException ex) {
Log.e("WifiPreference IpAddress", ex.toString());
}
return null;
}
public String getLocalMacAddress(Context context) {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();
}