安卓常用工具方法

文出处:**http://www.jianshu.com/p/72494773aace
为方便查找,已进行大致归类,其目录如下所示:

尺寸相关
dp与px转换 dp2px、px2dp
sp与px转换 sp2px、px2sp
各种单位转换 applyDimension
在onCreate()即可强行获取View的尺寸 forceGetViewSize
ListView中提前测量View尺寸 measureView
设备相关
获取设备MAC地址 getMacAddress
获取设备厂商,如Xiaomi getManufacturer
获取设备型号,如MI2SC getModel
获取设备SD卡是否可用 isSDCardEnable
获取设备SD卡路径 getSDCardPath
手机相关
判断设备是否是手机 isPhone
获取手机的IMIE getDeviceIMEI
获取手机状态信息 getPhoneStatus
拨打电话 callDial
发送短信 sendSms
获取手机联系人 getAllContactInfo
打开手机联系人界面点击联系人后便获取该号码 getContantNum
获取手机短信并保存到xml中 getAllSMS
网络相关
打开网络设置界面 openWirelessSettings
判断是否网络连接 isConnected
判断wifi是否连接状态 isWifiConnected
获取移动网络运营商名称 getNetworkOperatorName
获取移动终端类型 getPhoneType
获取连接的网络类型(2G,3G,4G) getCurNetworkType
获取当前手机的网络类型(WIFI,2G,3G,4G) getNetWorkStatus
App相关
安装指定路径下的Apk installApk
卸载指定包名的App uninstallApp
获取App名称 getAppName
获取当前App版本号 getVersonName
获取当前App版本Code getVersionCode
打开指定包名的App openOtherApp
打开指定包名的App应用信息界面 showAppInfo
分享Apk信息 shareApkInfo
获取App信息的一个封装类(包名、版本号、应用信息、图标、名称等) getAppInfos
判断当前App处于前台还是后台 isApplicationBackground
屏幕相关
获取手机分辨率 getDeviceWidth、getDeviceHeight
获取状态栏高度 getStatusBarHeight
获取状态栏高度+标题栏(ActionBar)高度 getTopBarHeight
获取屏幕截图 snapShotWithStatusBar、snapShotWithoutStatusBar
设置透明状态栏,需在setContentView之前调用
键盘相关
避免输入法面板遮挡
动态隐藏软键盘 hideSoftInput
点击屏幕空白区域隐藏软键盘
动态显示软键盘 showSoftInput
切换键盘显示与否状态 toggleSoftInput
正则相关
正则工具类
加解密相关
MD5加密 encryptMD5
SHA加密 encryptSHA
未归类
获取服务是否开启 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的尺寸
*/
public static int[] forceGetViewSize(View view) {
    int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    view.measure(widthMeasureSpec, heightMeasureSpec);
    return new int[]{view.getMeasuredWidth(), view.getMeasuredHeight()};
}

ListView中提前测量View尺寸

/**
 * ListView中提前测量View尺寸
 * 如headerView,用的时候拷贝到ListView中
 */
private void measureView(View view) {
    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卡路径
 */
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;
}

文/Blankj(简书作者)
原文链接:http://www.jianshu.com/p/72494773aace
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值