Fork me on GitHub

N个非常有用的Android程序片段(持续更新)

Android常用代码片段汇总。

1.判断网络是否已经连接

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
// check all network connect, WIFI or mobile
public static boolean isNetworkAvailable(final Context context) {
boolean hasWifoCon = false;
boolean hasMobileCon = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfos = cm.getAllNetworkInfo();
for (NetworkInfo net : netInfos) {
String type = net.getTypeName();
if (type.equalsIgnoreCase("WIFI")) {
LevelLogUtils.getInstance().i(tag, "get Wifi connection");
if (net.isConnected()) {
hasWifoCon = true;
}
}
if (type.equalsIgnoreCase("MOBILE")) {
LevelLogUtils.getInstance().i(tag, "get Mobile connection");
if (net.isConnected()) {
hasMobileCon = true;
}
}
}
return hasWifoCon || hasMobileCon;
}

2.Android的Px与Dp转化工具类

1
2
3
4
5
6
7
8
9
10
11
public class DensityUtils {
public static int Dp2Px(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
public static int Px2Dp(Context context, float px) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (px / scale + 0.5f);
}
}

3.Android获得WIFI IP地址或者手机网络IP

有的时候我们需要获得WIFI的IP地址获得手机网络的IP地址,这是一个工具类,专门解决这个问题,这里需要两个权限:

1
2
3
4
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>

第一个权限是获得WIFI的IP地址需要使用的,第二个权限是获得移动网络的IP需要使用的,代码如下:

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
public class GetIPAddressUtil {
public static String getWifiIP(Context context) {
String ip = null;
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int i = wifiInfo.getIpAddress();
ip = (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
+ "." + (i >> 24 & 0xFF);
}
return ip;
}
public static String getMobileIP() {
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("哎呀,出错了...", ex.toString());
}
return null;
}
}

4.唤醒屏幕并解锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void wakeUpAndUnlock(Context context){
KeyguardManager km= (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
//解锁
kl.disableKeyguard();
//获取电源管理器对象
PowerManager pm=(PowerManager) context.getSystemService(Context.POWER_SERVICE);
//获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,"bright");
//点亮屏幕
wl.acquire();
//释放
wl.release();
}

需要添加权限

1
2
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />

5.判断当前App处于前台还是后台状态

1
2
3
4
5
6
7
8
9
10
11
12
13
public static boolean isApplicationBackground(final Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
@SuppressWarnings("deprecation")
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}

需要添加权限

1
2
<uses-permission
android:name="android.permission.GET_TASKS" />

6.安装APK

1
2
3
4
5
6
7
8
9
10
public static void installApk(Context context, File file) {
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setType("application/vnd.android.package-archive");
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}

7.获取当前设备宽高,单位px

1
2
3
4
5
6
7
8
9
10
11
12
13
@SuppressWarnings("deprecation")
public static int getDeviceWidth(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
return manager.getDefaultDisplay().getWidth();
}
@SuppressWarnings("deprecation")
public static int getDeviceHeight(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
return manager.getDefaultDisplay().getHeight();
}

8.获取当前设备的MAC地址

1
2
3
4
5
6
7
8
9
10
11
12
public static String getMacAddress(Context context) {
String macAddress;
WifiManager wifi = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
macAddress = info.getMacAddress();
if (null == macAddress) {
return "";
}
macAddress = macAddress.replace(":", "");
return macAddress;
}

9.获取当前程序的版本号

1
2
3
4
5
6
7
8
9
10
public static String getAppVersion(Context context) {
String version = "0";
try {
version = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return version;
}

10.返回移动网络运营商的名字

(例:中国联通、中国移动、中国电信) 仅当用户已在网络注册时有效, CDMA 可能会无效)

1
2
3
4
5
public static String getNetworkOperatorName(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getNetworkOperatorName();
}

11.手机号码正则

1
public static final String REG_PHONE_CHINA = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";

12.邮箱正则

1
public static final String REG_EMAIL = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

13.通过资源文件名获取资源id

1
2
3
public static int getResource(Context c, String imageName) {
return c.getResources().getIdentifier(imageName, "mipmap", c.getPackageName());
}

14.获取方法执行时间

1
2
3
4
5
long startTime=System.currentTimeMillis();
//执行方法
long endTime=System.currentTimeMillis();
float excTime=(float)(endTime-startTime)/1000;
System.out.println("执行时间:"+excTime+"s");
任磊_Coder wechat
关注博主是一种态度,评论博主是一种欣赏。
坚持原创技术分享,您的支持将鼓励我继续创作!