Android開發人員不得不收集的代碼(不斷更新)

轉載自    http://www.jianshu.com/p/72494773aace


爲方便查找,已進行大致歸類,其目錄如下所示:

  • 尺寸相關SizeUtils.java
    • dp與px轉換 dp2pxpx2dp
    • sp與px轉換 sp2pxpx2sp
    • 各種單位轉換 applyDimension
    • 在onCreate()即可強行獲取View的尺寸(註釋萌萌噠) forceGetViewSize
    • ListView中提前測量View尺寸(註釋萌萌噠) measureView
  • 設備相關DeviceUtils.java
    • 獲取設備MAC地址 getMacAddress
    • 獲取設備廠商,如Xiaomi getManufacturer
    • 獲取設備型號,如MI2SC getModel
    • 獲取設備SD卡是否可用 isSDCardEnable
    • 獲取設備SD卡路徑 getSDCardPath
  • 手機相關PhoneUtils.java
    • 判斷設備是否是手機 isPhone
    • 獲取手機的IMIE getDeviceIMEI
    • 獲取手機狀態信息 getPhoneStatus
    • 撥打電話 callDial
    • 發送短信 sendSms
    • 獲取手機聯繫人 getAllContactInfo
    • 打開手機聯繫人界面點擊聯繫人後便獲取該號碼(註釋萌萌噠) getContantNum
    • 獲取手機短信並保存到xml中 getAllSMS
  • 網絡相關NetworkUtils.java
    • 打開網絡設置界面 openWirelessSettings
    • 判斷是否網絡連接 isConnected
    • 判斷wifi是否連接狀態 isWifiConnected
    • 獲取移動網絡運營商名稱 getNetworkOperatorName
    • 獲取移動終端類型 getPhoneType
    • 獲取連接的網絡類型(2G,3G,4G) getCurNetworkType
    • 獲取當前手機的網絡類型(WIFI,2G,3G,4G) getNetWorkStatus
  • App相關AppUtils.java
    • 安裝指定路徑下的Apk installApk
    • 卸載指定包名的App uninstallApp
    • 獲取當前App信息 getAppInfo
    • 獲取所有已安裝App信息 getAllAppsInfo
    • 打開指定包名的App openAppByPackageName
    • 打開指定包名的App應用信息界面 openAppInfo
    • 可用來做App信息分享 shareAppInfo
    • 判斷當前App處於前臺還是後臺 isApplicationBackground
  • 屏幕相關ScreenUtils.java
    • 獲取手機分辨率 getDeviceWidthgetDeviceHeight
    • 設置透明狀態欄(api >= 19方可使用) setTransparentStatusBar
    • 隱藏狀態欄(註釋萌萌噠) hideStatusBar
    • 獲取狀態欄高度 getStatusBarHeight
    • 獲取狀態欄高度+標題欄(ActionBar)高度 getTopBarHeight
    • 設置屏幕爲橫屏(註釋萌萌噠) setLandscape
    • 獲取屏幕截圖 snapShotWithStatusBarsnapShotWithoutStatusBar
  • 鍵盤相關KeyboardUtils.java
    • 避免輸入法面板遮擋
    • 動態隱藏軟鍵盤 hideSoftInput
    • 點擊屏幕空白區域隱藏軟鍵盤(註釋萌萌噠) clickBlankArea2HideSoftInput0
    • 動態顯示軟鍵盤 showSoftInput
    • 切換鍵盤顯示與否狀態 toggleSoftInput
  • 正則相關RegularUtils.java
    • 正則工具類
  • 加解密相關EncryptUtils.java
    • MD5加密 encryptMD5
    • SHA加密 encryptSHA
  • 未歸類UnclassifiedUtils.java
    • 獲取服務是否開啓 isRunningService
  • 更新Log

做這份整理只是想把它作爲Android的一本小字典,當遇到一些瑣碎問題時,不用再面向百度或者谷歌查詢API的使用,費時費力,這裏有的話,大家儘管擼走。希望它能逐日壯大起來,期待你的Star和完善,用途的話大家想把它們整理成工具類或者什麼的話都可以,之後我也會封裝工具類並分享之,但本篇只是提供查閱,畢竟看md比看類文件要爽多了,其中好多代碼我也是各種搜刮來的,也要謝謝各位的總結,大部分代碼已驗證過可行,如有錯誤,請及時告之,開設QQ羣提供討論,羣號:74721490

分類已上傳至Github,傳送門→期待你的Star和完善

好了,廢話不多說,開始開車,嘟嘟......

尺寸相關

dp與px轉換

/**
* dp轉px
*/
public static int dp2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}

/**
* px轉dp
*/
public static int px2dp(Context context, float pxValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (pxValue / scale + 0.5f);
}

sp與px轉換

/**
* sp轉px
*/
public static int sp2px(Context context, float spValue) {
    final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    return (int) (spValue * fontScale + 0.5f);
}

/**
* px轉sp
*/
public static int px2sp(Context context, float pxValue) {
 final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    return (int) (pxValue / fontScale + 0.5f);
}

各種單位轉換

/**
 * 各種單位轉換
 * 該方法存在於TypedValue
 */
public static float applyDimension(int unit, float value, DisplayMetrics metrics) {
    switch (unit) {
        case TypedValue.COMPLEX_UNIT_PX:
            return value;
        case TypedValue.COMPLEX_UNIT_DIP:
            return value * metrics.density;
        case TypedValue.COMPLEX_UNIT_SP:
            return value * metrics.scaledDensity;
        case TypedValue.COMPLEX_UNIT_PT:
            return value * metrics.xdpi * (1.0f / 72);
        case TypedValue.COMPLEX_UNIT_IN:
            return value * metrics.xdpi;
        case TypedValue.COMPLEX_UNIT_MM:
            return value * metrics.xdpi * (1.0f / 25.4f);
    }
    return 0;
}

在onCreate()即可強行獲取View的尺寸

/**
* 在onCreate()即可強行獲取View的尺寸
* 需回調onGetSizeListener接口,在onGetSize中獲取view寬高
* 用法示例如下所示
* SizeUtils.forceGetViewSize(view);
* SizeUtils.setListener(new SizeUtils.onGetSizeListener() {
 *     @Override
 *     public void onGetSize(View view) {
 *         Log.d("tag", view.getWidth() + " " + view.getHeight());
 *     }
* });
*/
public static void forceGetViewSize(final View view) {
    view.post(new Runnable() {
        @Override
        public void run() {
            if (mListener != null) {
                mListener.onGetSize(view);
            }
        }
    });
}

/**
* 獲取到View尺寸的監聽
*/
public interface onGetSizeListener {
    void onGetSize(View view);
}

public static void setListener(onGetSizeListener listener) {
    mListener = listener;
}

private static onGetSizeListener mListener;

ListView中提前測量View尺寸

/**
 * ListView中提前測量View尺寸,如headerView
 * 用的時候去掉註釋拷貝到ListView中即可
 * 參照以下注釋代碼
 */
public static void measureViewInLV(View view) {
    Log.i("tips", "U should copy the follow code.");
    /*
    ViewGroup.LayoutParams p = view.getLayoutParams();
    if (p == null) {
        p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
    }
    int width = ViewGroup.getChildMeasureSpec(0, 0, p.width);
    int height;
    int tempHeight = p.height;
    if (tempHeight > 0) {
        height = MeasureSpec.makeMeasureSpec(tempHeight,
                MeasureSpec.EXACTLY);
    } else {
        height = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    }
    view.measure(width, height);
    */
}

設備相關

獲取設備MAC地址

/**
 * 獲取設備MAC地址
 * 需添加權限<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
 */
public static String getMacAddress(Context context) {
    String macAddress = null;
    WifiManager wifi = (WifiManager) context
            .getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifi.getConnectionInfo();
    if (null != info ) {
        macAddress = info.getMacAddress();
        if (null != macAddress) {
            macAddress = macAddress.replace(":", "");
        }
    }
    return macAddress;
}

獲取設備廠商,如Xiaomi

/**
* 獲取設備廠商,如Xiaomi
*/
public static String getManufacturer() {
    String MANUFACTURER = Build.MANUFACTURER;
    return MANUFACTURER;
}

獲取設備型號,如MI2SC

/**
 * 獲取設備型號,如MI2SC
 */
public static String getModel() {
    String model = Build.MODEL;
    if (model != null) {
        model = model.trim().replaceAll("\\s*", "");
    } else {
        model = "";
    }
    return model;
}

獲取設備SD卡是否可用

/**
 * 獲取設備SD卡是否可用
 */
public static boolean isSDCardEnable() {
    return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}

獲取設備SD卡路徑

/**
 * 獲取設備SD卡路徑
 */
public static String getSDCardPath() {
    return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
}

手機相關

判斷設備是否是手機

/**
 * 判斷設備是否是手機
 */
public static boolean isPhone(Context context) {
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    return tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
}

獲取手機的IMIE

/**
 * 獲取當前設備的IMIE,需與上面的isPhone一起使用
 * 需添加權限<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 */
public static String getDeviceIMEI(Context context) {
    String deviceId;
    if (isPhone(context)) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        deviceId = tm.getDeviceId();
    } else {
        deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }
    return deviceId;
}

獲取手機狀態信息

/**
 * 獲取手機狀態信息
 * 需添加權限<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 * 返回如下
 * DeviceId(IMEI) = 99000311726612
 * DeviceSoftwareVersion = 00
 * Line1Number =
 * NetworkCountryIso = cn
 * NetworkOperator = 46003
 * NetworkOperatorName = 中國電信
 * NetworkType = 6
 * honeType = 2
 * SimCountryIso = cn
 * SimOperator = 46003
 * SimOperatorName = 中國電信
 * SimSerialNumber = 89860315045710604022
 * SimState = 5
 * SubscriberId(IMSI) = 460030419724900
 * VoiceMailNumber = *86
 */
public static String getPhoneStatus(Context context) {
    TelephonyManager tm = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    String str = "";
    str += "DeviceId(IMEI) = " + tm.getDeviceId() + "\n";
    str += "DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion() + "\n";
    str += "Line1Number = " + tm.getLine1Number() + "\n";
    str += "NetworkCountryIso = " + tm.getNetworkCountryIso() + "\n";
    str += "NetworkOperator = " + tm.getNetworkOperator() + "\n";
    str += "NetworkOperatorName = " + tm.getNetworkOperatorName() + "\n";
    str += "NetworkType = " + tm.getNetworkType() + "\n";
    str += "honeType = " + tm.getPhoneType() + "\n";
    str += "SimCountryIso = " + tm.getSimCountryIso() + "\n";
    str += "SimOperator = " + tm.getSimOperator() + "\n";
    str += "SimOperatorName = " + tm.getSimOperatorName() + "\n";
    str += "SimSerialNumber = " + tm.getSimSerialNumber() + "\n";
    str += "SimState = " + tm.getSimState() + "\n";
    str += "SubscriberId(IMSI) = " + tm.getSubscriberId() + "\n";
    str += "VoiceMailNumber = " + tm.getVoiceMailNumber() + "\n";
    return str;
}

撥打電話

// 需添加權限<uses-permission android:name="android.permission.CALL_PHONE"/>
/**
* 撥打電話
*/
public static void callDial(Context context, String phoneNumber) {
    context.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber)));
}

發送短信

/**
* 發送短信
*/
public static void sendSms(Context context, String phoneNumber, String content) {
    Uri uri = Uri.parse("smsto:" + (TextUtils.isEmpty(phoneNumber) ? "" : phoneNumber));
    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
    intent.putExtra("sms_body", TextUtils.isEmpty(content) ? "" : content);
    context.startActivity(intent);
}

獲取手機聯繫人

/**
 * 獲取手機聯繫人
 * 需添加權限<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 * 需添加權限<uses-permission android:name="android.permission.READ_CONTACTS" />
 */
public static List<HashMap<String, String>> getAllContactInfo(Context context) {
    SystemClock.sleep(3000);
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    // 1.獲取內容解析者
    ContentResolver resolver = context.getContentResolver();
    // 2.獲取內容提供者的地址:com.android.contacts
    // raw_contacts表的地址 :raw_contacts
    // view_data表的地址 : data
    // 3.生成查詢地址
    Uri raw_uri = Uri.parse("content://com.android.contacts/raw_contacts");
    Uri date_uri = Uri.parse("content://com.android.contacts/data");
    // 4.查詢操作,先查詢raw_contacts,查詢contact_id
    // projection : 查詢的字段
    Cursor cursor = resolver.query(raw_uri, new String[] { "contact_id" },
            null, null, null);
    // 5.解析cursor
    while (cursor.moveToNext()) {
        // 6.獲取查詢的數據
        String contact_id = cursor.getString(0);
        // cursor.getString(cursor.getColumnIndex("contact_id"));//getColumnIndex
        // : 查詢字段在cursor中索引值,一般都是用在查詢字段比較多的時候
        // 判斷contact_id是否爲空
        if (!TextUtils.isEmpty(contact_id)) {//null   ""
            // 7.根據contact_id查詢view_data表中的數據
            // selection : 查詢條件
            // selectionArgs :查詢條件的參數
            // sortOrder : 排序
            // 空指針: 1.null.方法 2.參數爲null
            Cursor c = resolver.query(date_uri, new String[] { "data1",
                            "mimetype" }, "raw_contact_id=?",
                    new String[] { contact_id }, null);
            HashMap<String, String> map = new HashMap<String, String>();
            // 8.解析c
            while (c.moveToNext()) {
                // 9.獲取數據
                String data1 = c.getString(0);
                String mimetype = c.getString(1);
                // 10.根據類型去判斷獲取的data1數據並保存
                if (mimetype.equals("vnd.android.cursor.item/phone_v2")) {
                    // 電話
                    map.put("phone", data1);
                } else if (mimetype.equals("vnd.android.cursor.item/name")) {
                    // 姓名
                    map.put("name", data1);
                }
            }
            // 11.添加到集合中數據
            list.add(map);
            // 12.關閉cursor
            c.close();
        }
    }
    // 12.關閉cursor
    cursor.close();
    return list;
}

打開手機聯繫人界面點擊聯繫人後便獲取該號碼

/**
 * 打開手機聯繫人界面點擊聯繫人後便獲取該號碼
 * 參照以下注釋代碼
 */
public static void getContantNum() {
    Log.i("tips", "U should copy the follow code.");
    /*
    Intent intent = new Intent();
    intent.setAction("android.intent.action.PICK");
    intent.setType("vnd.android.cursor.dir/phone_v2");
    startActivityForResult(intent, 0);
    @Override
    protected void onActivityResult ( int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Uri uri = data.getData();
            String num = null;
            // 創建內容解析者
            ContentResolver contentResolver = getContentResolver();
            Cursor cursor = contentResolver.query(uri,
                    null, null, null, null);
            while (cursor.moveToNext()) {
                num = cursor.getString(cursor.getColumnIndex("data1"));
            }
            cursor.close();
            num = num.replaceAll("-", "");//替換的操作,555-6 -> 5556
        }
    }
    */
}

獲取手機短信並保存到xml中

/**
 * 獲取手機短信並保存到xml中
 * 需添加權限<uses-permission android:name="android.permission.READ_SMS"/>
 * 需添加權限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 */
public static void getAllSMS(Context context) {
    //1.獲取短信
    //1.1獲取內容解析者
    ContentResolver resolver = context.getContentResolver();
    //1.2獲取內容提供者地址   sms,sms表的地址:null  不寫
    //1.3獲取查詢路徑
    Uri uri = Uri.parse("content://sms");
    //1.4.查詢操作
    //projection : 查詢的字段
    //selection : 查詢的條件
    //selectionArgs : 查詢條件的參數
    //sortOrder : 排序
    Cursor cursor = resolver.query(uri, new String[]{"address", "date", "type", "body"}, null, null, null);
    //設置最大進度
    int count = cursor.getCount();//獲取短信的個數
    //2.備份短信
    //2.1獲取xml序列器
    XmlSerializer xmlSerializer = Xml.newSerializer();
    try {
        //2.2設置xml文件保存的路徑
        //os : 保存的位置
        //encoding : 編碼格式
        xmlSerializer.setOutput(new FileOutputStream(new File("/mnt/sdcard/backupsms.xml")), "utf-8");
        //2.3設置頭信息
        //standalone : 是否獨立保存
        xmlSerializer.startDocument("utf-8", true);
        //2.4設置根標籤
        xmlSerializer.startTag(null, "smss");
        //1.5.解析cursor
        while (cursor.moveToNext()) {
            SystemClock.sleep(1000);
            //2.5設置短信的標籤
            xmlSerializer.startTag(null, "sms");
            //2.6設置文本內容的標籤
            xmlSerializer.startTag(null, "address");
            String address = cursor.getString(0);
            //2.7設置文本內容
            xmlSerializer.text(address);
            xmlSerializer.endTag(null, "address");
            xmlSerializer.startTag(null, "date");
            String date = cursor.getString(1);
            xmlSerializer.text(date);
            xmlSerializer.endTag(null, "date");
            xmlSerializer.startTag(null, "type");
            String type = cursor.getString(2);
            xmlSerializer.text(type);
            xmlSerializer.endTag(null, "type");
            xmlSerializer.startTag(null, "body");
            String body = cursor.getString(3);
            xmlSerializer.text(body);
            xmlSerializer.endTag(null, "body");
            xmlSerializer.endTag(null, "sms");
            System.out.println("address:" + address + "   date:" + date + "  type:" + type + "  body:" + body);
        }
        xmlSerializer.endTag(null, "smss");
        xmlSerializer.endDocument();
        //2.8將數據刷新到文件中
        xmlSerializer.flush();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

網絡相關

打開網絡設置界面

/**
 * 打開網絡設置界面
 * 3.0以下打開設置界面
 */
public static void openWirelessSettings(Context context) {
    if (android.os.Build.VERSION.SDK_INT > 10) {
        context.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
    } else {
        context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
    }
}

判斷是否網絡連接

/**
 * 判斷是否網絡連接
 * 需添加權限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 */
public static boolean isConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Activity.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    return info != null && info.isConnected();
}

判斷wifi是否連接狀態

/**
 * 判斷wifi是否連接狀態
 * 需添加權限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 */
public static boolean isWifiConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm != null && cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
}

獲取移動網絡運營商名稱

/**
 * 獲取移動網絡運營商名稱
 * 如中國聯通、中國移動、中國電信
 */
public static String getNetworkOperatorName(Context context) {
    TelephonyManager tm = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    return tm != null ? tm.getNetworkOperatorName() : null;
}

獲取移動終端類型

/**
 * 獲取移動終端類型
 * PHONE_TYPE_NONE  : 0 手機制式未知
 * PHONE_TYPE_GSM   : 1 手機制式爲GSM,移動和聯通
 * PHONE_TYPE_CDMA  : 2 手機制式爲CDMA,電信
 * PHONE_TYPE_SIP   : 3
 */
public static int getPhoneType(Context context) {
    TelephonyManager tm = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    return tm != null ? tm.getPhoneType() : -1;
}

獲取連接的網絡類型(2G,3G,4G)

/**
 * 獲取連接的網絡類型(2G,3G,4G)
 * 聯通的3G爲UMTS或HSDPA,移動和聯通的2G爲GPRS或EGDE,電信的2G爲CDMA,電信的3G爲EVDO
 */
public static int getNetTpye(Context context) {
    TelephonyManager telephonyManager = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    switch (telephonyManager.getNetworkType()) {
        case TelephonyManager.NETWORK_TYPE_GPRS:
        case TelephonyManager.NETWORK_TYPE_EDGE:
        case TelephonyManager.NETWORK_TYPE_CDMA:
        case TelephonyManager.NETWORK_TYPE_1xRTT:
        case TelephonyManager.NETWORK_TYPE_IDEN:
            return Constants.NETWORK_CLASS_2_G;
        case TelephonyManager.NETWORK_TYPE_UMTS:
        case TelephonyManager.NETWORK_TYPE_EVDO_0:
        case TelephonyManager.NETWORK_TYPE_EVDO_A:
        case TelephonyManager.NETWORK_TYPE_HSDPA:
        case TelephonyManager.NETWORK_TYPE_HSUPA:
        case TelephonyManager.NETWORK_TYPE_HSPA:
        case TelephonyManager.NETWORK_TYPE_EVDO_B:
        case TelephonyManager.NETWORK_TYPE_EHRPD:
        case TelephonyManager.NETWORK_TYPE_HSPAP:
            return Constants.NETWORK_CLASS_3_G;
        case TelephonyManager.NETWORK_TYPE_LTE:
            return Constants.NETWORK_CLASS_4_G;
        default:
            return Constants.NETWORK_CLASS_UNKNOWN;
    }
}
public class Constants {
    // Unknown network class
    public static final int NETWORK_CLASS_UNKNOWN = 0;
    // wifi network
    public static final int NETWORK_WIFI = 1;
    // "2G" networks
    public static final int NETWORK_CLASS_2_G = 2;
    // "3G" networks
    public static final int NETWORK_CLASS_3_G = 3;
    // "4G" networks
    public static final int NETWORK_CLASS_4_G = 4;
}

獲取當前手機的網絡類型(WIFI,2G,3G,4G)

/**
 * 獲取當前手機的網絡類型(WIFI,2G,3G,4G)
 * 需添加權限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 * 需要用到上面的方法
 */
public static int getCurNetworkType(Context context) {
    int netWorkType = Constants.NETWORK_CLASS_UNKNOWN;
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        int type = networkInfo.getType();
        if (type == ConnectivityManager.TYPE_WIFI) {
            netWorkType = Constants.NETWORK_WIFI;
        } else if (type == ConnectivityManager.TYPE_MOBILE) {
            netWorkType = getNetworkTpye(context);
        }
    }
    return netWorkType;
}

App相關

安裝指定路徑下的Apk

/**
 * 安裝指定路徑下的Apk
 * 根據路徑名是否符合和文件是否存在判斷是否安裝成功
 * 更好的做法應該是startActivityForResult回調判斷是否安裝成功比較妥當
 * 這裏做不了回調,後續自己做處理
 */
public static boolean installApp(Context context, String filePath) {
    if (filePath != null && filePath.length() > 4
            && filePath.toLowerCase().substring(filePath.length() - 4).equals(".apk")) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(filePath);
        if (file.exists() && file.isFile() && file.length() > 0) {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return true;
        }
    }
    return false;
}

卸載指定包名的App

/**
 * 卸載指定包名的App
 * 這裏卸載成不成功只判斷了packageName是否爲空
 * 如果要根據是否卸載成功應該用startActivityForResult回調判斷是否還存在比較妥當
 * 這裏做不了回調,後續自己做處理
 */
public boolean uninstallApp(Context context, String packageName) {
    if (!TextUtils.isEmpty(packageName)) {
        Intent intent = new Intent(Intent.ACTION_DELETE);
        intent.setData(Uri.parse("package:" + packageName));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        return true;
    }
    return false;
}

獲取當前App信息

/**
 * 封裝App信息的Bean類
 */
public static class AppInfo {

    private String name;
    private Drawable icon;
    private String packagName;
    private String versionName;
    private int versionCode;
    private boolean isSD;
    private boolean isUser;

    public Drawable getIcon() {
        return icon;
    }

    public void setIcon(Drawable icon) {
        this.icon = icon;
    }

    public boolean isSD() {
        return isSD;
    }

    public void setSD(boolean SD) {
        isSD = SD;
    }

    public boolean isUser() {
        return isUser;
    }

    public void setUser(boolean user) {
        isUser = user;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPackagName() {
        return packagName;
    }

    public void setPackagName(String packagName) {
        this.packagName = packagName;
    }

    public int getVersionCode() {
        return versionCode;
    }

    public void setVersionCode(int versionCode) {
        this.versionCode = versionCode;
    }

    public String getVersionName() {
        return versionName;
    }

    public void setVersionName(String versionName) {
        this.versionName = versionName;
    }

    /**
     * @param name        名稱
     * @param icon        圖標
     * @param packagName  包名
     * @param versionName 版本號
     * @param versionCode 版本Code
     * @param isSD        是否安裝在SD卡
     * @param isUser      是否是用戶程序
     */
    public AppInfo(String name, Drawable icon, String packagName,
                   String versionName, int versionCode, boolean isSD, boolean isUser) {
        this.setName(name);
        this.setIcon(icon);
        this.setPackagName(packagName);
        this.setVersionName(versionName);
        this.setVersionCode(versionCode);
        this.setSD(isSD);
        this.setUser(isUser);
    }
}
/**
 * 獲取當前App信息
 * AppInfo(名稱,圖標,包名,版本號,版本Code,是否安裝在SD卡,是否是用戶程序)
 */
public static AppInfo getAppInfo(Context context) {
    PackageManager pm = context.getPackageManager();
    PackageInfo pi = null;
    try {
        pi = pm.getPackageInfo(context.getApplicationContext().getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return pi != null ? getBean(pm, pi) : null;
}

/**
 * 得到AppInfo的Bean
 */
private static AppInfo getBean(PackageManager pm, PackageInfo pi) {
    ApplicationInfo ai = pi.applicationInfo;
    String name = pi.packageName;
    Drawable icon = ai.loadIcon(pm);
    String packageName = pi.packageName;
    String versionName = pi.versionName;
    int versionCode = pi.versionCode;
    boolean isSD = (ApplicationInfo.FLAG_SYSTEM & ai.flags) != ApplicationInfo.FLAG_SYSTEM;
    boolean isUser = (ApplicationInfo.FLAG_SYSTEM & ai.flags) != ApplicationInfo.FLAG_SYSTEM;
    return new AppInfo(name, icon, packageName, versionName, versionCode, isSD, isUser);
}

獲取所有已安裝App信息

/**
 * 獲取所有已安裝App信息
 * AppInfo(名稱,圖標,包名,版本號,版本Code,是否安裝在SD卡,是否是用戶程序)
 * 依賴上面的getBean方法
 */
public static List<AppInfo> getAllAppsInfo(Context context) {
    List<AppInfo> list = new ArrayList<>();
    PackageManager pm = context.getPackageManager();
    // 獲取系統中安裝的所有軟件信息
    List<PackageInfo> installedPackages = pm.getInstalledPackages(0);
    for (PackageInfo pi : installedPackages) {
        if (pi != null) {
            list.add(getBean(pm, pi));
        }
    }
    return list;
}

打開指定包名的App

/**
 * 打開指定包名的App
 */
public static boolean openAppByPackageName(Context context, String packageName) {
    if (!TextUtils.isEmpty(packageName)) {
        PackageManager pm = context.getPackageManager();
        Intent launchIntentForPackage = pm.getLaunchIntentForPackage(packageName);
        if (launchIntentForPackage != null) {
            context.startActivity(launchIntentForPackage);
            return true;
        }
    }
    return false;
}

打開指定包名的App應用信息界面

/**
 * 打開指定包名的App應用信息界面
 */
public static boolean openAppInfo(Context context, String packageName) {
    if (!TextUtils.isEmpty(packageName)) {
        Intent intent = new Intent();
        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.setData(Uri.parse("package:" + packageName));
        context.startActivity(intent);
        return true;
    }
    return false;
}

可用來做App信息分享

/**
 * 可用來做App信息分享
 */
public static void shareAppInfo(Context context, String info) {
    if (!TextUtils.isEmpty(info)) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, info);
        context.startActivity(intent);
    }
}

判斷當前App處於前臺還是後臺

/**
 * 判斷當前App處於前臺還是後臺
 * 需添加<uses-permission android:name="android.permission.GET_TASKS"/>
 * 並且必須是系統應用該方法纔有效
 */
public static boolean isAppBackground(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;
}

屏幕相關

獲取手機分辨率

/**
* 獲取屏幕的寬度px
*/
public static int getDeviceWidth(Context context) {
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics outMetrics = new DisplayMetrics();// 創建了一張白紙
    windowManager.getDefaultDisplay().getMetrics(outMetrics);// 給白紙設置寬高
    return outMetrics.widthPixels;
}

/**
* 獲取屏幕的高度px
*/
public static int getDeviceHeight(Context context) {
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics outMetrics = new DisplayMetrics();// 創建了一張白紙
    windowManager.getDefaultDisplay().getMetrics(outMetrics);// 給白紙設置寬高
    return outMetrics.heightPixels;
}

獲取狀態欄高度

/**
* 獲取狀態欄高度
*/
public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

獲取ActionBar高度

/**
 * 獲取ActionBar高度
 */
public static int getActionBarHeight(Activity activity) {
    TypedValue tv = new TypedValue();
    if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
        return TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics());
    }
    return 0;
}

獲取屏幕截圖

/**
 * 獲取當前屏幕截圖,包含狀態欄
 */
public static Bitmap captureWithStatusBar(Activity activity) {
    View view = activity.getWindow().getDecorView();
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache();
    Bitmap bmp = view.getDrawingCache();
    int width = getScreenWidth(activity);
    int height = getScreenHeight(activity);
    Bitmap bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
    view.destroyDrawingCache();
    return bp;
}

/**
 * 獲取當前屏幕截圖,不包含狀態欄
 * 需要用到上面獲取狀態欄高度的方法
 */
public static Bitmap captureWithoutStatusBar(Activity activity) {
    View view = activity.getWindow().getDecorView();
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache();
    Bitmap bmp = view.getDrawingCache();
    int statusBarHeight = getStatusBarHeight(activity);
    int width = getScreenWidth(activity);
    int height = getScreenHeight(activity);
    Bitmap bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
    view.destroyDrawingCache();
    return bp;
}

設置透明狀態欄(api >= 19方可使用)

/**
* 設置透明狀態欄(api >= 19方可使用)
* 可在Activity的onCreat()中調用
* 需在頂部控件佈局中加入以下屬性讓內容出現在狀態欄之下
* android:clipToPadding="true"
* android:fitsSystemWindows="true"
*/
public static void setTransparentStatusBar(Activity activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        //透明狀態欄
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明導航欄
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }
}

鍵盤相關

避免輸入法面板遮擋

// 在manifest.xml中activity中設置
android:windowSoftInputMode="stateVisible|adjustResize"

動態隱藏軟鍵盤

/**
* 動態隱藏軟鍵盤
*/
public static void hideSoftInput(Activity activity) {
    View view = activity.getWindow().peekDecorView();
    if (view != null) {
        InputMethodManager inputmanger = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

/**
* 動態隱藏軟鍵盤
*/
public static void hideSoftInput(Context context, EditText edit) {
    edit.clearFocus();
    InputMethodManager inputmanger = (InputMethodManager) context
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    inputmanger.hideSoftInputFromWindow(edit.getWindowToken(), 0);
}

點擊屏幕空白區域隱藏軟鍵盤

/**
 * 點擊屏幕空白區域隱藏軟鍵盤(方法1)
 * 在onTouch中處理,未獲焦點則隱藏
 * 參照以下注釋代碼
 */
public static void clickBlankArea2HideSoftInput0() {
    Log.i("tips", "U should copy the following code.");
    /*
    @Override
    public boolean onTouchEvent (MotionEvent event){
        if (null != this.getCurrentFocus()) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }
    */
}

/**
 * 點擊屏幕空白區域隱藏軟鍵盤(方法2)
 * 根據EditText所在座標和用戶點擊的座標相對比,來判斷是否隱藏鍵盤
 * 需重寫dispatchTouchEvent
 * 參照以下注釋代碼
 */
public static void clickBlankArea2HideSoftInput1() {
    Log.i("tips", "U should copy the following code.");
    /*
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    // 根據EditText所在座標和用戶點擊的座標相對比,來判斷是否隱藏鍵盤
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }
    // 獲取InputMethodManager,隱藏軟鍵盤
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    */
}

動態顯示軟鍵盤

/**
* 動態顯示軟鍵盤
*/
public static void showSoftInput(Context context, EditText edit) {
    edit.setFocusable(true);
    edit.setFocusableInTouchMode(true);
    edit.requestFocus();
    InputMethodManager inputManager = (InputMethodManager) context
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.showSoftInput(edit, 0);
}

切換鍵盤顯示與否狀態

/**
* 切換鍵盤顯示與否狀態
*/
public static void toggleSoftInput(Context context, EditText edit) {
    edit.setFocusable(true);
    edit.setFocusableInTouchMode(true);
    edit.requestFocus();
    InputMethodManager inputManager = (InputMethodManager) context
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

正則相關

正則工具類

public class RegularUtils {
    //驗證手機號
    private static final String REGEX_MOBILE = "^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$";
    //驗證座機號,正確格式:xxx/xxxx-xxxxxxx/xxxxxxxx
    private static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}";
    //驗證郵箱
    private static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
    //驗證url
    private static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?";
    //驗證漢字
    private static final String REGEX_CHZ = "^[\\u4e00-\\u9fa5]+$";
    //驗證用戶名,取值範圍爲a-z,A-Z,0-9,"_",漢字,不能以"_"結尾,用戶名必須是6-20位
    private static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?<!_)$";
    //驗證IP地址
    private static final String REGEX_IP = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";

    //If u want more please visit http://toutiao.com/i6231678548520731137/

    /**
     * @param string 待驗證文本
     * @return 是否符合手機號格式
     */
    public static boolean isMobile(String string) {
        return isMatch(REGEX_MOBILE, string);
    }

    /**
     * @param string 待驗證文本
     * @return 是否符合座機號碼格式
     */
    public static boolean isTel(String string) {
        return isMatch(REGEX_TEL, string);
    }

    /**
     * @param string 待驗證文本
     * @return 是否符合郵箱格式
     */
    public static boolean isEmail(String string) {
        return isMatch(REGEX_EMAIL, string);
    }

    /**
     * @param string 待驗證文本
     * @return 是否符合網址格式
     */
    public static boolean isURL(String string) {
        return isMatch(REGEX_URL, string);
    }

    /**
     * @param string 待驗證文本
     * @return 是否符合漢字
     */
    public static boolean isChz(String string) {
        return isMatch(REGEX_CHZ, string);
    }

    /**
     * @param string 待驗證文本
     * @return 是否符合用戶名
     */
    public static boolean isUsername(String string) {
        return isMatch(REGEX_USERNAME, string);
    }

    /**
     * @param regex  正則表達式字符串
     * @param string 要匹配的字符串
     * @return 如果str 符合 regex的正則表達式格式,返回true, 否則返回 false;
     */
    public static boolean isMatch(String regex, String string) {
        return !TextUtils.isEmpty(string) && Pattern.matches(regex, string);
    }
}

加解密相關

MD5加密

/**
* 一個byte轉爲2個hex字符
*/
public static String bytes2Hex(byte[] src) {
    char[] res = new char[src.length * 2];
    final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    for (int i = 0, j = 0; i < src.length; i++) {
        res[j++] = hexDigits[src[i] >>> 4 & 0x0f];
        res[j++] = hexDigits[src[i] & 0x0f];
    }
    return new String(res);
}

/**
* MD5加密
*
* @param data 明文
* @return 密文
*/
public static String getMD5(String data) {
    return TextUtils.isEmpty(data) ? "" : getMD5(data.getBytes());
}

/**
* MD5加密
*
* @param data 明文字節數組
* @return 密文
*/
public static String getMD5(byte[] data) {
    if (data.length > 0) {
        return bytes2Hex(encryptMD5(data));
    }
    return "";
}

/**
* MD5加密
*
* @param data 明文字節數組
* @return 密文字節數組
*/
public static byte[] encryptMD5(byte[] data) {
    if (data.length > 0) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(data);
            return md.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    return null;
}


/**
* 獲取文件的MD5校驗碼
*
* @param filePath 文件路徑
* @return 文件的MD5校驗碼
*/
public static String getMD5File(String filePath) {
    if (!TextUtils.isEmpty(filePath)) {
        FileInputStream in = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            in = new FileInputStream(filePath);
            int len;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                md.update(buffer, 0, len);
            }
            return bytes2Hex(md.digest());
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
    return "";
}

SHA加密

/**
* SHA加密
*
* @param data 明文
* @return 密文
*/
public static String getSHA(String data) {
    return TextUtils.isEmpty(data) ? "" : getSHA(data.getBytes());
}

/**
* SHA加密
*
* @param data 明文字節數組
* @return 密文
*/
public static String getSHA(byte[] data) {
    if (data.length > 0) {
        return bytes2Hex(encryptSHA(data));
    }
    return "";
}

/**
* SHA加密
* @param data 明文字節數組
* @return 密文字節數組
*/
public static byte[] encryptSHA(byte[] data) {
    if (data.length > 0) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(data);
            return md.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    return null;
}

未歸類

獲取服務是否開啓

/**
 * 獲取服務是否開啓
 * @param className 完整包名的服務類名
 */
public static boolean isRunningService(String className, Context context) {
    // 進程的管理者,活動的管理者
    ActivityManager activityManager = (ActivityManager)
            context.getSystemService(Context.ACTIVITY_SERVICE);
    // 獲取正在運行的服務,最多獲取1000個
    List<RunningServiceInfo> runningServices = activityManager.getRunningServices(1000);
    // 遍歷集合
    for (RunningServiceInfo runningServiceInfo : runningServices) {
        ComponentName service = runningServiceInfo.service;
        if (className.equals(service.getClassName())) {
            return true;
        }
    }
    return false;
}

更新Log

2016/07/31 新增點擊屏幕空白區域隱藏軟鍵盤

2016/07/31 新增目錄跳轉功能(然而簡書不支持所以這裏沒更新)

2016/08/01 新增獲取當前App版本Code

2016/08/01 新增目錄中顯示方法名

2016/08/01 新增獲取SD卡路徑,手機和設備進行分類,代碼bug修改部分,小修排版,正在封裝類

2016/08/02 wifi設置界面bug修復,註釋排版還在修改,獲取mac地址增加判空,新增QQ羣:74721490,歡迎加入

2016/08/02 新增隱藏狀態欄,註釋更加全面,工具類已封裝,寫的時候真的是一個一個測試過去的,寶寶心裏苦

2016/08/03 修復在onCreate中獲取view尺寸的bug,MD5和SHA的Bug修復完成(在此感謝ssyijiu)



文/Blankj(簡書作者)
原文鏈接:http://www.jianshu.com/p/72494773aace
著作權歸作者所有,轉載請聯繫作者獲得授權,並標註“簡書作者”。
發佈了54 篇原創文章 · 獲贊 8 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章