pda/zhuike/.svn/pristine/ac/acf5d31428f04273e2c16eaa378...

688 lines
24 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.novelbook.android.utils;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
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.res.Resources;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.TextureView;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.novelbook.android.netsubscribe.BookSubscribe;
import com.novelbook.android.netutils.OnSuccessAndFaultListener;
import com.novelbook.android.netutils.OnSuccessAndFaultSub;
//import com.yanzhenjie.permission.AndPermission;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class CommonUtil {
private static final String TAG= CommonUtil.class.getSimpleName();
public static int getScreenHeight(Context context){
int diff = statusBarDiff(context);
int ret=0;
if(diff >0){
ret = getRealScreenSize(context).y;// -diff; // return height for no navigation bar //有虚拟按键 honor 8 或 没有虚拟按键但顶部有其他占用高度的 mi8
Log.d(TAG, String.format("getNavigationBarSize:screen height is getRealScreenSize(context).y -diff = %s , diff is %s" ,ret ,diff));
}else {
ret = getAppUsableScreenSize(context).y; //return for with navigationbar //没有虚拟按键 mate20
Log.d(TAG, String.format("getNavigationBarSize:screen height is getAppUsableScreenSize(context).y =%s", ret));
}
return ret;
}
/**
* 获取是否存在NavigationBar
* @param context
* @return
*/
public static int statusBarDiff(Context context) {
Point appUsableSize = getAppUsableScreenSize(context);
Point realScreenSize = getRealScreenSize(context);
Log.d(TAG, String.format("getNavigationBarSize:getDpi %s,getScreenHeightWithOutBottomBar %s, usablesize.y %s,realScreenSize.y %s" +
",realScreenSize.y -usablesize.y =%s, statusbar height %s"
,getDpi(context) ,getScreenHeightWithOutBottomBar(context),appUsableSize.y ,realScreenSize.y, realScreenSize.y-appUsableSize.y ,getStatusBarHeight(context) ));
Point p = getNavigationBarSize(context);
// Toast.makeText(context,String.format("getNavigationBarSize: usablesize.y %s,realScreenSize.y %s,diff %s",
// appUsableSize.y ,realScreenSize.y,realScreenSize.y-appUsableSize.y - getStatusBarHeight(context)),Toast.LENGTH_LONG).show();
return realScreenSize.y-appUsableSize.y - getStatusBarHeight(context);
}
//状态栏高度
public static int getStatusBarHeight(Context c) {
int resourceId = c.getResources()
.getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
return c.getResources().getDimensionPixelSize(resourceId);
}
return 0;
}
//返回值就是导航栏的高度,得到的值单位px
public float getNavigationBarHeight(Context c) {
float result = 0;
int resourceId = c.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
result = c.getResources().getDimension(resourceId);
}
return result;
}
public static Point getNavigationBarSize(Context context) {
Point appUsableSize = getAppUsableScreenSize(context);
Point realScreenSize = getRealScreenSize(context);
Log.d(TAG, String.format("getNavigationBarSize: usablesize.y %s,realScreenSize.y %s,realScreenSize.y -usablesize.y =%s, statusbar height %s"
,appUsableSize.y ,realScreenSize.y, realScreenSize.y-appUsableSize.y ,getStatusBarHeight(context) ));
// navigation bar on the side
if (appUsableSize.x < realScreenSize.x) {
return new Point(realScreenSize.x - appUsableSize.x, appUsableSize.y);
}
// navigation bar at the bottom
if (appUsableSize.y < realScreenSize.y) {
return new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y);
}
// navigation bar is not present
return new Point();
}
public static Point getAppUsableScreenSize(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size;
}
public static Point getRealScreenSize(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
if (Build.VERSION.SDK_INT >= 17) {
display.getRealSize(size);
} else if (Build.VERSION.SDK_INT >= 14) {
try {
size.x = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
size.y = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
} catch (IllegalAccessException e) {} catch (InvocationTargetException e) {} catch (NoSuchMethodException e) {}
}
return size;
}
/**
* 获取虚拟功能键高度
* @param context
* @return
*/
public static int getVirtualBarHeigh(Context context) {
int vh = 0;
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
try {
@SuppressWarnings("rawtypes")
Class c = Class.forName("android.view.Display");
@SuppressWarnings("unchecked")
Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
method.invoke(display, dm);
vh = dm.heightPixels - windowManager.getDefaultDisplay().getHeight();
} catch (Exception e) {
e.printStackTrace();
}
return vh;
}
/**
* 获取屏幕原始尺寸高度,包括虚拟功能键高度
* @param context
* @return
*/
public static int getDpi(Context context){
int dpi = 0;
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
@SuppressWarnings("rawtypes")
Class c;
try {
c = Class.forName("android.view.Display");
@SuppressWarnings("unchecked")
Method method = c.getMethod("getRealMetrics",DisplayMetrics.class);
method.invoke(display, displayMetrics);
dpi=displayMetrics.heightPixels;
}catch(Exception e){
e.printStackTrace();
}
return dpi;
}
/**
* 获取 虚拟按键+ 顶部状态栏 + x 的高度
* @param context
* @return
*/
public static int getBottomStatusHeight(Context context){
int totalHeight = getDpi(context);
int contentHeight = getScreenHeight(context);
return totalHeight - contentHeight;
}
/**
* 获得屏幕高度
*
* @param context
* @return
*/
public static int getScreenHeightWithOutBottomBar(Context context)
{
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
/**
* 标题栏高度
* @return
*/
public static int getTitleHeight(Activity activity){
return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
}
/**
* 获得状态栏的高度
*
* @param context
* @return
*/
public static int getStatusHeight(Context context)
{
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 int getAPIVersion(){
int APIVersion;
try {
APIVersion = Integer.valueOf(android.os.Build.VERSION.SDK);
} catch (NumberFormatException e) {
APIVersion = 0;
}
return APIVersion;
}
/**
*
* @param context
* @param px
* @return
*/
public static float convertPixelsToDp(final Context context, final float px) {
return px / context.getResources().getDisplayMetrics().density;
}
/**
*
* @param context
* @param dp
* @return
*/
public static float convertDpToPixel(final Context context, final float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
/**
* sp转px
*
* @param context
* @param spVal
* @return
*/
public static int sp2px(Context context, float spVal)
{
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}
/**
* px转sp
*
* @param context
* @param pxVal
* @return
*/
public static float px2sp(Context context, float pxVal)
{
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
public static String subString(String text,int num){
String content = "";
if (text.length() > num){
content = text.substring(0,num -1) + "...";
}else{
content = text;
}
return content;
}
/**
* 获取版本号
*
* @return 当前应用的版本号
*/
public static String getVersion(Context context) {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
return info.versionName;
} catch (Exception e) {
e.printStackTrace();
return "找不到版本号";
}
}
/**
* @return 版本号
*/
public static int getVersionCode(Context context) {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
return info.versionCode;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public static int getVersionCodeLong(Context context) {
if(Constants.version >0){
return Constants.version;
}
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Constants.version = (int) info.getLongVersionCode();
}else return getVersionCode(context);
} catch (Exception e) {
e.printStackTrace();
return 0;
}catch (NoSuchMethodError e){
e.printStackTrace();
return 0;
}
return Constants.version;
}
public static String getPackageName(Context context) {
try {
return context.getPackageName();
} catch (Exception e) {
e.printStackTrace();
return "";
}catch (NoSuchMethodError e){
e.printStackTrace();
return "";
}
}
/**
* 获取当前手机系统语言。
*
* @return 返回当前系统语言。例如:当前设置的是“中文-中国”则返回“zh-CN”
*/
public static String getSystemLanguage() {
return Locale.getDefault().getLanguage();
}
/**
* 获取当前系统上的语言列表(Locale列表)
*
* @return 语言列表
*/
public static Locale[] getSystemLanguageList() {
return Locale.getAvailableLocales();
}
/**
* 获取当前手机系统版本号
*
* @return 系统版本号
*/
public static String getSystemVersion() {
return android.os.Build.VERSION.RELEASE;
}
/**
* 获取手机型号
*
* @return 手机型号
*/
public static String getSystemModel() {
return android.os.Build.MODEL;
}
/**
* 获取手机厂商
*
* @return 手机厂商
*/
public static String getDeviceBrand() {
return android.os.Build.BRAND;
}
/**
* 获取APP版本
* @param context
* @return
*/
public static String getVersionName(Context context) {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo;
String versionName = "";
try {
packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
versionName = packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
public static String getDateString(long time,String format){
String f = TextUtils.isEmpty(format) ?"yyyy年MM月dd日 HH:mm:ss":format;
Date dt = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String rt =sdf.format(dt);
Log.d(TAG, String.format("getDateString:timestamp %s, formated time %s",time,rt));
/* long time2 =System.currentTimeMillis();
dt = new Date(time2);
rt =sdf.format(dt);
Log.d(TAG, String.format("getDateString:timestamp %s, formated time %s",time2,rt));*/
return sdf.format(dt);
/* Timestamp ts = new Timestamp(time);
String tsStr = "";
DateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
//方法一
tsStr = sdf2.format(ts);
System.out.println(tsStr);
//方法二
tsStr = ts.toString();
System.out.println(tsStr);
} catch (Exception e) {
e.printStackTrace();
}*/
}
public static String getDateString(long time){
return getDateString(time,"");
}
public static String getTimeCnt4Read(Long time,boolean isIncludeSec)
{
int ish = (int) (time/1000/60/60);
int ism = (int) ((time - ish*3600*1000)/1000/60);
int iss = (int) ((time -ish*3600*1000 - ism*60*1000)/1000);
// int ish =Integer.valueOf(String.valueOf(hour));
// int ism = Integer.valueOf(String.valueOf(minute));
// int iss = Integer.valueOf(String.valueOf(second));
String sh = String.valueOf( ish>0 ?ish+"小时" :"") ;
String sm = String.valueOf(ism>0 ? ism +"分" :"") ;
String ss = String.valueOf(iss>=0 ?iss +"秒":"" ) ;
// if (10>ish && ish>0)sh ="0"+sh;
if (ish>0&& 10>ism && ism>0)sm ="0"+sm;
if (ism>0 && 10>iss && iss>0)ss ="0"+ss;
if(!isIncludeSec)
return sh + sm +(ish==0?(ism>0 ? "钟" :""):"");
return sh + sm +ss;
}
public static int getDayscnt(Long time )
{
int days =(int) (time/1000/60/60/24);
if(days>0){
days++;
}
return days;
}
public static String getFileName() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String date = format.format(new Date(System.currentTimeMillis()));
return date;// 2012年10月03日 23:41:31
}
public static String getDateEN() {
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date1 = format1.format(new Date(System.currentTimeMillis()));
return date1;// 2012-10-03 23:41:31
}
public static String getChannel(Context context) {
try {
PackageManager pm = context.getPackageManager();
ApplicationInfo appInfo = pm.getApplicationInfo(getPackageName(context), PackageManager.GET_META_DATA);
return appInfo.metaData.getString("UMENG_CHANNEL");
} catch (PackageManager.NameNotFoundException ignored) {
}
return "";
}
public static String getMeta(Context context,String key) {
try {
PackageManager pm = context.getPackageManager();
ApplicationInfo appInfo = pm.getApplicationInfo(getPackageName(context), PackageManager.GET_META_DATA);
return appInfo.metaData.getString(key);
} catch (PackageManager.NameNotFoundException ignored) {
}
return "";
}
public static void checkPermission (Activity thisActivity, String permission, int requestCode, String errorText) {
//判断当前Activity是否已经获得了该权限
boolean hasPermision =true;
try{
hasPermision = ContextCompat.checkSelfPermission(thisActivity,permission) == PackageManager.PERMISSION_GRANTED;
}catch (Exception e){
}
Log.e(TAG, String.format("checkAndRequestPermission: %s 有权限? ",hasPermision) );
if(!hasPermision) {
Log.e(TAG, String.format("checkAndRequestPermission: %s 曾经被用户拒绝过? %s",permission,ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
permission)) );
//如果App的权限申请曾经被用户拒绝过就需要在这里跟用户做出解释
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
permission)) {
Toast.makeText(thisActivity,errorText,Toast.LENGTH_SHORT).show();
//进行权限请求
ActivityCompat.requestPermissions(thisActivity,
new String[]{permission},
requestCode);
} else {
//进行权限请求
Log.e(TAG, String.format("checkAndRequestPermission: %s start requestperimisions ",permission ) );
// startAppSettingActivity(thisActivity);
ActivityCompat.requestPermissions(thisActivity, new String[]{permission}, requestCode);
}
} else {
}
}
private static boolean isSDK2API23() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
private static boolean isHavePermission(Context context, String permission) {
return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(context, permission);
}
private static boolean isUserNoShowPermissionDialig(Activity activity, String permission) {
return !(ActivityCompat.shouldShowRequestPermissionRationale(activity, permission));
}
private static void startAppSettingActivity(Activity activity) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + activity.getPackageName()));
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
activity.startActivityForResult(intent, 100);
}
/*private void requestPermission(Activity thisActivity,String permission) {
AndPermission.with(thisActivity).runtime()
.permission(permission)
// 准备方法,和 okhttp 的拦截器一样,在请求权限之前先运行改方法,已经拥有权限不会触发该方法
.rationale((context, permissions, executor) -> {
// 此处可以选择显示提示弹窗
executor.execute();
})
// 用户给权限了
// 用户拒绝权限,包括不再显示权限弹窗也在此列
.onDenied(permissions -> {
// 判断用户是不是不再显示权限弹窗了,若不再显示的话进入权限设置页
if (AndPermission.hasAlwaysDeniedPermission(thisActivity, permissions)) {
// 打开权限设置页
// AndPermission.with(thisActivity).permissionSetting(thisActivity).execute();
return;
}
})
.start();
}*/
public static void getSearchTabTtitle(Context context){
BookSubscribe.getSearchTitles(Constants.SEX,new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
@Override
public void onSuccess(String result) {
// mFirstPage= gson.fromJson(result, FirstPage.class);
try {
Constants.lstSex = GsonUtil.parserStringBlocks(result,"sex");
Constants.lstNt =GsonUtil.parserStringBlocks(result,"nt");
Constants.lstProgressType =GsonUtil.parserProgressType(result,"progress");
// initTabs();
// loadSearchData();
} catch (Exception e) {
Log.e(TAG, "onSuccess: prepare book",e );
e.printStackTrace();
}
}
@Override
public void onFault(String errorMsg) {
//失败
// getSearchTabTtitle();
}
},context));
}
/* public static boolean isNavigationBarShow(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
Point realSize = new Point();
display.getSize(size);
display.getRealSize(realSize);
boolean result = realSize.y!=size.y;
return realSize.y!=size.y;
}else {
boolean menu = ViewConfiguration.get(getActivity()).hasPermanentMenuKey();
boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
if(menu || back) {
return false;
}else {
return true;
}
}
}*/
/**
* 获取是否有虚拟按键
* 通过判断是否有物理返回键反向判断是否有虚拟按键
* mate20 不行
* @param context
* @return
*/
/* public static boolean checkDeviceHasNavigationBar2(Context context) {
boolean hasMenuKey = ViewConfiguration.get(context)
.hasPermanentMenuKey();
boolean hasBackKey = KeyCharacterMap
.deviceHasKey(KeyEvent.KEYCODE_BACK);
if (!hasMenuKey & !hasBackKey) {
// 做任何你需要做的,这个设备有一个导航栏
return true;
}
return false;
}
*/
}