Android中Helper帮助类

package com.huaiye.ecs.common.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * ******************************
 * @文件名称:KukiHelper.java
 * @文件作者:Administrator
 * @创建时间:201574 * @文件描述:ccc
 * *****************************
 */
public class Helper {

    static Context context = App.getInstance();

    private Helper() {
    }

    // sp convert to px
    public static int sp2px(int spValue) {
        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
        int pxValue = (int) (spValue * scaledDensity + 0.5f);
        return pxValue;
    }

    // px convert to sp
    public static int px2sp(int pxValue) {
        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
        int spValue = (int) (pxValue / scaledDensity + 0.5f);
        return spValue;
    }

    // dp convert to px
    public static int dp2px(int dpValue) {
        float density = context.getResources().getDisplayMetrics().density;
        int pxValue = (int) (dpValue * density + 0.5f);
        return pxValue;
    }

    // px convert to dp
    public static int px2dp(int pxValue) {
        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
        int dpValue = (int) (pxValue * scaledDensity + 0.5f);
        return dpValue;
    }

    // findView
    public static <T extends View> T findViewById(View rootView, int id) {
        View target = rootView.findViewById(id);
        return (T) target;
    }

    // findView
    public static <T extends View> T findViewById(Activity ac, int id) {
        View target = ac.findViewById(id);
        return (T) target;
    }

    // 获取包名
    public static String packageName() {
        String name = context.getPackageName();
        return name;
    }

    // 获取版本号
    public static int versionCode() {
        int version = -1;
        try {
            String packageName = packageName();
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            version = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return version;
    }

    // 获取版本名称
    public static String versionName() {
        String versionCode = null;
        try {
            String packageName = packageName();
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            versionCode = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    // 获取xml中配置的String     public static String getStringResource(int id) {
        return context.getResources().getString(id);
    }

    // 获取xml中的Color 色值
    public static int getColorResource(int id) {
        return context.getResources().getColor(id);
    }

    // 获取xml中的Integer     public static int getIntegerResource(int id) {
        return context.getResources().getInteger(id);
    }

    // 获取xml中的String数组
    public static String[] getStringArrayResource(int id) {
        return context.getResources().getStringArray(id);
    }

    // 获取Assets下的资源输入流
    public static InputStream getAssetsResource(String filename) {
        try {
            return context.getAssets().open(filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 获取Assets下的String资源
    public static String getAssetString(String name) {
        String string = "";
        AssetManager asset = context.getAssets();
        try {
            InputStream input = asset.open(name);
            byte[] buffer = new byte[input.available()];
            input.read(buffer);
            input.close();
            string = new String(buffer, "utf-8");

        } catch (IOException e) {
            e.printStackTrace();
        }
        return string;
    }

    // 获取assets下的Bitmap文件
    public static Bitmap getAssetBitmap(String name) {
        InputStream is = getAssetsResource(name);
        if (is != null) {
            Bitmap bm = BitmapFactory.decodeStream(is);
            return bm;
        }
        return null;
    }

    // 获取Raw下的资源输入流
    public static InputStream getRawResource(int id) {
        return context.getResources().openRawResource(id);
    }

    // 获取xml中的Integer数组
    public static int[] getIntegerArrayResource(int id) {
        return context.getResources().getIntArray(id);
    }

    // 获取Drawable
    public static Drawable getDrawable(int id) {
        return context.getResources().getDrawable(id);
    }

    // 获取Animations
    public static Animation getAnimation(int id) {
        return AnimationUtils.loadAnimation(context, id);
    }

    // 窗口宽度
    public static int getScreenWidth() {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    // 窗口高度
    public static int getScreenHeight() {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    // IMEI
    public static String getIMEI() {
        String imei = ((TelephonyManager) context
                .getApplicationContext()
                .getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        return imei;
    }

    // IMSI
    public static String getIMSI() {
        String imsi = ((TelephonyManager) context.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
        return imsi;
    }

    public static String getDeviceUniqueId(){
        String serial = null;

        String m_szDevIDShort = "35" +
                Build.BOARD.length()%10+ Build.BRAND.length()%10 +

                Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +

                Build.DISPLAY.length()%10 + Build.HOST.length()%10 +

                Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +

                Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +

                Build.TAGS.length()%10 + Build.TYPE.length()%10 +

                Build.USER.length()%10 ; //13 
        try {
            serial = Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }

        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    // 设备型号
    public static String getModel() {
        return Build.MODEL;
    }

    // 设备制造商
    public static String getManufacturer() {
        return Build.MANUFACTURER;
    }

    /**
     * 获得状态栏的高度
     */
    public static int getStatusHeight() {
        int statusHeight = -1;
        try {
            Class clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    /**
     * 获取当前屏幕截图,包含状态栏
     */
    public static Bitmap snapShotWithStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int width = getScreenWidth();
        int height = getScreenHeight();
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
        view.destroyDrawingCache();
        return bp;

    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    public static int statusHeight(Activity activity) {
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        return statusBarHeight;
    }

    /**
     * 获取当前屏幕截图,不包含状态栏
     */
    public static Bitmap snapShotWithoutStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;

        int width = getScreenWidth();
        int height = getScreenHeight();
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
                - statusBarHeight);
        view.destroyDrawingCache();
        return bp;

    }

    // 系统版本名
    public static String getOsReleaseVersion() {
        return Build.VERSION.RELEASE;
    }

    // 系统SDK版本
    public static int getOsSdkVersion() {
        return Build.VERSION.SDK_INT;
    }

    // 获取 uuid
    public static String getUUid() {
        String uuidString = UUID.randomUUID().toString();
        return uuidString;
    }

    // Application  元素 keyname 获取对应的value
    public static <T> T getAppMetaData(String name) {
        ApplicationInfo appInfo;
        try {
            appInfo = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        if (appInfo.metaData != null && appInfo.metaData.containsKey(name)) {
            return (T) appInfo.metaData.get(name);
        }
        return null;
    }

    /**
     * 获取系统安装的所有App的包信息
     * @return
     */
    public static List getInstalledPackages(){
        PackageManager pm = context.getPackageManager();
        return pm.getInstalledPackages(0);
    }

    /**
     * 判断App是否是系统安装的
     * @param pi
     * @return
     */
    public static boolean isAppSystemInstalled(PackageInfo pi){
        if((pi.applicationInfo.flags& ApplicationInfo.FLAG_SYSTEM)==0&&
                (pi.applicationInfo.flags&ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)==0){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 获取应用程序名称
     */
    public static String getAppName() {
//        第一种方案
//        try {
//            PackageManager packageManager = context.getPackageManager();
//            PackageInfo packageInfo = packageManager.getPackageInfo(
//                    context.getPackageName(), 0);
//            int labelRes = packageInfo.applicationInfo.labelRes;
//            return context.getResources().getString(labelRes);
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
        PackageManager packageManager = context.getPackageManager();
        return packageManager.getApplicationLabel(context.getApplicationInfo()).toString();
    }

    // 一个获得当前进程的名字的方法
    public static String getCurrentProcessName() {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    /**
     * 使用SSL不信任的证书
     * 默认设置的是HttpsURLConnection     */
    public static void useUntrustedCertificate() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(
                            X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(
                            X509Certificate[] certs, String authType) {
                    }
                }
        };
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开软键盘
     */
    public static void openKeyboard(EditText mEditText) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**
     * 关闭软键盘
     */
    public static void closeKeyboard(EditText mEditText) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }


    // mac地址
    // 需要权限 ACCESS_WIFI_STATE
    public static String getLocalMacAddress() {
        String macSerial = null;
        String str = "";

        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }

        if(TextUtils.isEmpty(macSerial)){
            macSerial = ((TelephonyManager) context
                    .getApplicationContext()
                    .getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        }

        if(TextUtils.isEmpty(macSerial)){
            String serial = null;

            String m_szDevIDShort = "35" +
                    Build.BOARD.length()%10+ Build.BRAND.length()%10 +

                    Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +

                    Build.DISPLAY.length()%10 + Build.HOST.length()%10 +

                    Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +

                    Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +

                    Build.TAGS.length()%10 + Build.TYPE.length()%10 +

                    Build.USER.length()%10 ; //13 
            try {
                serial = android.os.Build.class.getField("SERIAL").get(null).toString();
                //API>=9 使用serial                return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
            } catch (Exception exception) {
                //serial需要一个初始化
                serial = "serial"; // 随便一个初始化
            }

            //使用硬件信息拼凑出来的15位号码
            macSerial = new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        }
        return macSerial;
    }

    /**
     * sdcard是否可用
     *
     * @return
     */
    public static boolean isSDCardUseful() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 当前App是否处于前台
     * onResume/onStop中判断
     * onStopActivity回到后台后的最后一个生命周期方法
     *
     * @return
     */
    public static boolean isAppForeground() {
//        方法的原型
//        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
//        String packageName = getApplicationContext().getPackageName();
//
//        List appProcesses = activityManager
//                .getRunningAppProcesses();
//        if (appProcesses == null)
//            return false;
//
//        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
//            // 进程名称是否与包名一致
//            // 这种方法判断有误差,如果App启动的所在线程是一个附属线程,在附属线程中判断的话,进程名永远都会与包名一致
//            if (appProcess.processName.equals(packageName)
//                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
//                return true;
//            }
//        }

//        废弃方法+
//        /**
//         * android.permission.GET_TASKS
//         * 之前,使用该接口需要 android.permission.GET_TASKS
//         * 即使是自己开发的普通应用,只要声明该权限,即可以使用getRunningTasks接口。
//         * 但从L开始,这种方式以及废弃。
//         * 应用要使用该接口必须声明权限android.permission.REAL_GET_TASKS
//         * 而这个权限是不对三方应用开放的。(在Manifest里申请了也没有作用)
//         * 系统应用(有系统签名)可以调用该权限。
//         * 该方法废弃
//         */
//        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//        List tasks = am.getRunningTasks(1);
//        if (tasks != null && !tasks.isEmpty()) {
//            ActivityManager.RunningTaskInfo topTask = tasks.get(0);
//            ComponentName topTaskInfo = topTask.topActivity;
//            Log.d("hjq", "top pkg " + topTaskInfo.getPackageName());
//            if (topTaskInfo.getPackageName().equals(context.getPackageName())) {
//                return true;
//            }
//        }

        // 获取当前的进程号
        int pid = android.os.Process.myPid();
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List processInfos = am.getRunningAppProcesses();
        if (processInfos != null && !processInfos.isEmpty()) {
            for (ActivityManager.RunningAppProcessInfo tmp : processInfos) {
                if (tmp.pid == pid) {
                    // 判断该进程是否属于前台进程
                    if (tmp.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        }

        return false;
    }

    /**
     * 判断屏幕是否被点亮
     * @return
     */
    public static boolean isScreenOn(){
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = pm.isScreenOn();
        return isScreenOn;
    }

    /**
     * 重新启动App
     *
     * @param context
     */
    public static void restartApplication(Context context) {
        PackageManager pm = context.getPackageManager();
        Intent intent = pm.getLaunchIntentForPackage(context.getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    /**
     * 网络相关的工具方法
     */
    public static class NetWork {

        /**
         * 判断网络是否可用
         *
         * @return
         */
        public static boolean isNetworkAvailable() {
            /*
             *  mNetworkInfo.isAvailable() mNetworkInfo.isConnected() 函数返回
             *  1,显示连接已保存,但标题栏没有,即没有实质连接上   not connect available
             *
             *  2,显示连接已保存,标题栏也有已连接上的图标,       connect available
             *
             *  3,选择不保存后                                  not connect available
             *
             *  4,选择连接,在正在获取IP地址时                    not connect not available
             *  avalibale更可靠用来判断网络是否可用
             */
            if (context != null) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
                if (mNetworkInfo != null) {
                    return mNetworkInfo.isAvailable();
                }
            }

            return false;
        }

        /**
         * 判断WIFI网络是否可用
         *
         * @return
         */
        public static boolean isWifiConnected() {
            if (context != null) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                if (mWiFiNetworkInfo != null) {
                    return mWiFiNetworkInfo.isAvailable();
                }
            }
            return false;
        }


        /**
         * 判断MOBILE网络是否可用
         *
         * @return
         */
        public static boolean isMobileConnected() {
            if (context != null) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mMobileNetworkInfo = mConnectivityManager
                        .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if (mMobileNetworkInfo != null) {
                    return mMobileNetworkInfo.isAvailable();
                }
            }
            return false;
        }

        /**
         * 获取当前的网络状态 :没有网络0WIFI网络13G网络22G网络3
         *
         * @return
         */
        public static int getNetworkType() {
            int netType = 0;
            ConnectivityManager connMgr = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo == null) {
                return netType;
            }
            int nType = networkInfo.getType();
            if (nType == ConnectivityManager.TYPE_WIFI) {
                netType = 1;// wifi
            } else if (nType == ConnectivityManager.TYPE_MOBILE) {
                int nSubType = networkInfo.getSubtype();
                TelephonyManager mTelephony = (TelephonyManager) context
                        .getSystemService(Context.TELEPHONY_SERVICE);
                if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
                        && !mTelephony.isNetworkRoaming()) {
                    netType = 2;// 3G
                } else {
                    netType = 3;// 2G
                }
            }
            return netType;
        }

        /**
         * 打开无线网络设置界面
         */
        public static void openWirelessSettings() {
            Intent intent = new Intent("/");
            ComponentName cm = new ComponentName("com.android.settings",
                    "com.android.settings.WirelessSettings");
            intent.setComponent(cm);
            intent.setAction("android.intent.action.VIEW");
            context.startActivity(intent);
        }


        /**
         * mac地址
         * android.permission.ACCESS_WIFI_STATE
         */
        public static String getMacAddress() {
            String macSerial = null;
            String str = "";

            try {
                Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
                InputStreamReader ir = new InputStreamReader(pp.getInputStream());
                LineNumberReader input = new LineNumberReader(ir);

                for (; null != str; ) {
                    str = input.readLine();
                    if (str != null) {
                        macSerial = str.trim();// 去空格
                        break;
                    }
                }
            } catch (IOException ex) {
                // 赋予默认值
                ex.printStackTrace();
            }
            return macSerial;
        }

        /**
         * 获取IP地址,只有WIFI条件下可用
         *
         * @return
         */
        public static String getMobileIP() {
            // 优先从WIFI获取IP地址
            String ip = ipFromWifi();

            // Wifi获取不到或者Wifi没有开,那么通过网络接口获取IP地址
            if (TextUtils.isEmpty(ip)) {
                return ipFromInternet();
            }

            return ip;
        }

        /**
         * 通过WIFI获取IP地址
         *
         * @return
         */
        private static String ipFromWifi() {
            //获取wifi服务
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            //判断wifi是否开启
            if (!wifiManager.isWifiEnabled()) {
                return null;
            }
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            // 地址转换
            return (ipAddress & 0xFF) + "." +
                    ((ipAddress >> 8) & 0xFF) + "." +
                    ((ipAddress >> 16) & 0xFF) + "." +
                    (ipAddress >> 24 & 0xFF);
        }

        /**
         * 通过Internet获取IP地址,需要Internet网络权限
         * android.permission.INTERNET
         *
         * @return
         */
        private static String ipFromInternet() {
            try {
                for (Enumeration en = NetworkInterface
                        .getNetworkInterfaces(); en.hasMoreElements(); ) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration enumIpAddr = intf
                            .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()
                                && inetAddress instanceof Inet4Address) {
                            // IPV4地址
                            // if (!inetAddress.isLoopbackAddress() && inetAddress
                            // instanceof Inet6Address) {
                            return inetAddress.getHostAddress().toString();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    /**
     * App签名 sha1相关
     */
    public static class AppSig {

        /**
         * 获取App签名
         *
         * @return
         */
        public static String getAppSignature() {
            try {
                PackageManager packageManager = context.getPackageManager();
                //请注意需要PackageManager.GET_SIGNATURES 这个flag
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),
                        PackageManager.GET_SIGNATURES);
                Signature[] signs = packageInfo.signatures;
                Signature sign = signs[0];
                // X509证书,X.509是一种非常通用的证书格式
                CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) certFactory
                        .generateCertificate(new ByteArrayInputStream(sign.toByteArray()));
                // md5
                MessageDigest md = MessageDigest.getInstance("MD5");
                // 获得公钥
                byte[] b = md.digest(cert.getEncoded());
                //key即为应用签名
                //.replace(":", "");
                String key = byte2HexFormatted(b);

                return key;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            } catch (CertificateException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * 获得app sha1         *
         * @return
         */
        public static String getAppSignSha1() {
            try {
                PackageManager packageManager = context.getPackageManager();
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
                // X509证书,X.509是一种非常通用的证书格式
                Signature[] signs = packageInfo.signatures;
                Signature sign = signs[0];
                CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(sign.toByteArray()));                    // md5
                MessageDigest md = MessageDigest.getInstance("SHA1");
                // 获得公钥
                byte[] b = md.digest(cert.getEncoded());
                return byte2HexFormatted(b);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * 将获取到得编码进行16进制转换
         *
         * @param arr
         * @return
         */
        private static String byte2HexFormatted(byte[] arr) {
            StringBuilder str = new StringBuilder(arr.length * 2);
            for (int i = 0; i < arr.length; i++) {
                String h = Integer.toHexString(arr[i]);
                int l = h.length();
                if (l == 1)
                    h = "0" + h;
                if (l > 2)
                    h = h.substring(l - 2, l);
                str.append(h.toUpperCase());
                if (i < (arr.length - 1))
                    str.append(':');
            }
            return str.toString();
        }

    }

}

你可能感兴趣的:(Android移动开发)