android中有哪些utils的作用,AndroidUtils

多年开发Android积攒下来好多常用的工具方法,保存在随笔中,持续更新。

TimeUtil

/**

* 获取距当前时刻的时间戳

*

* @param createTime

* @return

*/

public static String getTimestamp(long createTime) {

long currrentMillis = System.currentTimeMillis();

// if (createTime < 0 || currrentMillis < createTime) {

// return null;

// }

StringBuffer sb =new StringBuffer();

Date date =new Date(createTime);

Calendar now = Calendar.getInstance();

SimpleDateFormat sdf_hms =new SimpleDateFormat("HH:mm");

SimpleDateFormat sdf_full =new SimpleDateFormat("yyyy-MM-dd HH:mm");

long standardMillis =1000 * (now.get(Calendar.HOUR_OF_DAY) *3600 + now.get(Calendar.MINUTE) *60 + now.get(Calendar.SECOND));

long diffMillis = currrentMillis - createTime;

if (diffMillis <60 *1000) {

sb.append("刚刚");

}else if (diffMillis <3600 *1000) {

sb.append(diffMillis /60000 +"分钟前");

}else if (diffMillis < standardMillis) {

sb.append("今天 " + sdf_hms.format(date));

}else if (diffMillis < standardMillis +MILLISECOND_OF_DAY) {

sb.append("昨天 " + sdf_hms.format(date));

}else {

sb.append(sdf_full.format(date));

}

return sb.toString();

}

//判断选择的日期是否是今天

public static boolean isToday(long time) {

return isThisTime(time,"yyyy-MM-dd");

}

//判断选择的日期是否是本月

public static boolean isThisMonth(long time) {

return isThisTime(time,"yyyy-MM");

}

private static boolean isThisTime(long time, String pattern) {

Date date =new Date(time);

SimpleDateFormat sdf =new SimpleDateFormat(pattern);

String param = sdf.format(date);//参数时间

String now = sdf.format(new Date());//当前时间

if (param.equals(now)) {

return true;

}

return false;

}

//判断选择的日期是否是本周

public static boolean isThisWeek(long time) {

Calendar calendar = Calendar.getInstance();

int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);

calendar.setTime(new Date(time));

int paramWeek = calendar.get(Calendar.WEEK_OF_YEAR);

if (paramWeek == currentWeek) {

return true;

}

return false;

}

/**

* 将long时间格式字符串转换为字符串 yyyy-MM-dd HH:mm MM月dd日 yyyy-MM-dd

*

* @return

*/

public static String timeLong2String(long data) {

Date date =new Date(data);

SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd HH:mm");

// SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日");

// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

return formatter.format(date);

}

ScreenUtil

public static int px2sp(Context context,float pxValue) {

final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;

return (int) (pxValue / fontScale +0.5f);

}

public static int dp2px(Context context,int dp) {

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();

return (int) ((dp * displayMetrics.density) +0.5);

}

public static int px2dp(Context context,float pxValue) {

final float scale = context.getResources().getDisplayMetrics().density;

return (int) (pxValue / scale +0.5f);

}

/**

* 获取屏幕宽度

*/

public static int getScreenWidth(Context context) {

DisplayMetrics dm = context.getResources().getDisplayMetrics();

return dm.widthPixels;

}

/**

* 获取屏幕高度

*/

public static int getScreenHeight(Context context) {

DisplayMetrics dm = context.getResources().getDisplayMetrics();

return dm.heightPixels;

}

/**

* 获取状态栏高度

*/

public static int getStatusBarHeight(Context context) {

// 一般是25dp

int height =dp2px(context,20);

//获取status_bar_height资源的ID

int resourceId = context.getResources().getIdentifier("status_bar_height","dimen","android");

if (resourceId >0) {

height = context.getResources().getDimensionPixelSize(resourceId);

LogUtil.i("real statusBar height:" + height);

}

return height;

}

/**

* 虚拟操作拦(home等)是否显示

*/

public static boolean isNavigationBarShow(Activity activity) {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {

Display display = activity.getWindowManager().getDefaultDisplay();

Point size =new Point();

Point realSize =new Point();

display.getSize(size);

display.getRealSize(realSize);

return realSize.y != size.y;

}else {

boolean menu = ViewConfiguration.get(activity).hasPermanentMenuKey();

boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);

if (menu || back) {

return false;

}else {

return true;

}

}

}

/**

* 获取虚拟操作拦(home等)高度

*/

public static int getNavigationBarHeight(Activity activity) {

if (!isNavigationBarShow(activity))

return 0;

int height =0;

Resources resources = activity.getResources();

//获取NavigationBar的高度

int resourceId = resources.getIdentifier("navigation_bar_height","dimen","android");

if (resourceId >0)

height = resources.getDimensionPixelSize(resourceId);

return height;

}

NetWorkUtil

/**

* 没有网络

*/

public static final int NETWORKTYPE_INVALID =0;

/**

* wap网络

*/

public static final int NETWORKTYPE_WAP =1;

/**

* 2G网络

*/

public static final int NETWORKTYPE_2G =2;

/**

* 3G和3G以上网络,或统称为快速网络

*/

public static final int NETWORKTYPE_3G =3;

/**

* wifi网络

*/

public static final int NETWORKTYPE_WIFI =4;

private static boolean isFastMobileNetwork(Context context) {

TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

switch (telephonyManager.getNetworkType()) {

case TelephonyManager.NETWORK_TYPE_1xRTT:

return false;// ~ 50-100 kbps

case TelephonyManager.NETWORK_TYPE_CDMA:

return false;// ~ 14-64 kbps

case TelephonyManager.NETWORK_TYPE_EDGE:

return false;// ~ 50-100 kbps

case TelephonyManager.NETWORK_TYPE_EVDO_0:

return true;// ~ 400-1000 kbps

case TelephonyManager.NETWORK_TYPE_EVDO_A:

return true;// ~ 600-1400 kbps

case TelephonyManager.NETWORK_TYPE_GPRS:

return false;// ~ 100 kbps

case TelephonyManager.NETWORK_TYPE_HSDPA:

return true;// ~ 2-14 Mbps

case TelephonyManager.NETWORK_TYPE_HSPA:

return true;// ~ 700-1700 kbps

case TelephonyManager.NETWORK_TYPE_HSUPA:

return true;// ~ 1-23 Mbps

case TelephonyManager.NETWORK_TYPE_UMTS:

return true;// ~ 400-7000 kbps

case TelephonyManager.NETWORK_TYPE_EHRPD:

return true;// ~ 1-2 Mbps

case TelephonyManager.NETWORK_TYPE_EVDO_B:

return true;// ~ 5 Mbps

case TelephonyManager.NETWORK_TYPE_HSPAP:

return true;// ~ 10-20 Mbps

case TelephonyManager.NETWORK_TYPE_IDEN:

return false;// ~25 kbps

case TelephonyManager.NETWORK_TYPE_LTE:

return true;// ~ 10+ Mbps

case TelephonyManager.NETWORK_TYPE_UNKNOWN:

return false;

default:

return false;

}

}

/**

* 获取网络状态,wifi,wap,2g,3g.

*

* @param context 上下文

* @return int 网络状态

*/

public static int getNetWorkType(Context context) {

ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = manager.getActiveNetworkInfo();

if (networkInfo !=null && networkInfo.isConnected()) {

String type = networkInfo.getTypeName();

if (type.equalsIgnoreCase("WIFI")) {

return NETWORKTYPE_WIFI;

}else if (type.equalsIgnoreCase("MOBILE")) {

String proxyHost = android.net.Proxy.getDefaultHost();

return TextUtils.isEmpty(proxyHost)

? (isFastMobileNetwork(context) ?NETWORKTYPE_3G :NETWORKTYPE_2G)

:NETWORKTYPE_WAP;

}

}else {

return NETWORKTYPE_INVALID;

}

return NETWORKTYPE_INVALID;

}

public static boolean isNetWorkConnect(Context context) {

return getNetWorkType(context) !=0;

}

DeviceUtil

/**

* 获取deviceid

*

* @return

*/

public static String getDeviceId() {

String deviceId =getDeviceIdLocally();

if (TextUtils.isEmpty(deviceId)) {

try {

AdvertisingIdClient.Info idInfo = AdvertisingIdClient.getAdvertisingIdInfo(CCApplication.getInstance());

if (idInfo ==null) {

String uuid =getUUId();

storeDeviceId(uuid);

return uuid;

}else {

String advertId = idInfo.getId();

if (TextUtils.isEmpty(advertId)) {

return getUUId();

}else {

storeDeviceId(advertId);

SharedPrefUtils.getInstance().putString(AppConstant.SharedPreferenceKey.KEYCHAIN_ID, MD5Util.md5Encode(advertId));

return advertId;

}

}

}catch (Exception e) {

return getUUId();

}

}else {

return deviceId;

}

}

public static String getUUId() {

String uuId = UUID.randomUUID().toString();

SharedPrefUtils.getInstance().putString(AppConstant.SharedPreferenceKey.DEVICE_ID, uuId);

SharedPrefUtils.getInstance().putString(AppConstant.SharedPreferenceKey.KEYCHAIN_ID, MD5Util.md5Encode(uuId));

return uuId;

}

private static String getDeviceIdLocally() {

final String fileName ="HMSN.ini";

File file =null;

if (isSDCardAvailable()) {

file =new File(Environment.getExternalStorageDirectory(), fileName);

if (!file.exists()) {

file =null;

}

}

boolean internally =false;

if (file ==null) {

file =new File(CCApplication.getInstance().getFilesDir(), fileName);

internally =true;

}

if (file ==null || !file.exists()) {

String deviceId = SharedPrefUtils.getInstance().getString(AppConstant.SharedPreferenceKey.DEVICE_ID);

if (!TextUtils.isEmpty(deviceId)) {

storeDeviceId(deviceId);

return deviceId;

}

return null;

}

InputStream ins =null;

try {

ins =new FileInputStream(file);

Properties properties =new Properties();

properties.load(ins);

String deviceId = properties.getProperty(AppConstant.SharedPreferenceKey.DEVICE_ID);

if (!TextUtils.isEmpty(deviceId) && !internally &&isSDCardAvailable()) {

storeDeviceId(deviceId);

}

return deviceId;

}catch (Exception e) {

e.printStackTrace();

return null;

}finally {

if (ins !=null) {

try {

ins.close();

}catch (IOException e) {

e.printStackTrace();

}

}

}

}

private static void storeDeviceId(String deviceId) {

SharedPrefUtils.getInstance().putString(AppConstant.SharedPreferenceKey.DEVICE_ID, deviceId);

File file =new File(isSDCardAvailable() ? Environment.getExternalStorageDirectory() : CCApplication.getInstance().getFilesDir(),"HMSN.ini");

OutputStream outs =null;

try {

outs =new FileOutputStream(file);

Properties properties =new Properties();

properties.setProperty(AppConstant.SharedPreferenceKey.DEVICE_ID, deviceId);

properties.store(outs,null);

}catch (Exception e) {

e.printStackTrace();

}finally {

if (outs !=null) {

try {

outs.close();

}catch (IOException e) {

e.printStackTrace();

}

}

}

}

public static boolean isSDCardAvailable() {

return (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()));

}

/**

* 获取本地语言

* @return

*/

public static String getDeviceLanguage() {

return Locale.getDefault().getLanguage();

}

public static String getSimCode() {

TelephonyManager manager = (TelephonyManager) CCApplication.getInstance().getSystemService(Context.TELEPHONY_SERVICE);

return manager.getSimCountryIso();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值