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

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

// 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转化工具类

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地址,这是一个工具类,专门解决这个问题,这里需要两个权限:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.INTERNET" >
    </uses-permission>

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

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.唤醒屏幕并解锁

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();  
    }

需要添加权限

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

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

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

需要添加权限

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

6.安装APK

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

@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地址

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.获取当前程序的版本号

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 可能会无效)

public static String getNetworkOperatorName(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getNetworkOperatorName();
    }

11.手机号码正则

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

12.邮箱正则

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

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

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

14.获取方法执行时间

long startTime=System.currentTimeMillis();
//执行方法
long endTime=System.currentTimeMillis();
float excTime=(float)(endTime-startTime)/1000;
System.out.println("执行时间:"+excTime+"s");
  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值