工具類封裝 dp px log Toast

dp px 轉換

/**
	 * 根據手機的分辨率從 dp 的單位 轉成爲 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}
 
	/**
	 * 根據手機的分辨率從 px(像素) 的單位 轉成爲 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
 

獲取屏幕寬高

public class AppScreenMgr {
    /**
     * Get the width of the screen.
     *獲得屏幕寬度
     * @param context
     *            The context to use. Usually your
     *            {@link android.app.Application} or
     *            {@link Activity} object.
     * @return Return the width of the screen.
     */
    public static int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context
            .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        return metrics.widthPixels;
    }

    /**
     * Get the height of the screen.
     *獲得屏幕高度
     * @param context
     *            The context to use. Usually your
     *            {@link android.app.Application} or
     *            {@link Activity} object.
     * @return Return the height of the screen.
     */
    public static int getScreenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context
            .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        return metrics.heightPixels;
    }

    /**
     *
     * Whether the Status bar is hidden or not,the method always helps you get
     * the height of Status bar.
     *獲得狀態欄的高度
     * @param context
     *            The context to use. Usually your
     *            {@link android.app.Application} or
     *            {@link Activity} object.
     * @return Return the height of Status bar.
     */
    public static int getStatusHeight(Context context) {
        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int id = (Integer) (clazz.getField("status_bar_height").get(object));
            statusHeight = context.getResources().getDimensionPixelSize(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    /**
     * 功能描述:獲取整塊屏幕的高度
     *
     * @param context
     * @return int
     */
    public static int getRealScreenHeight(Context context) {
        int dpi = 0;
        Display display = ((Activity) context).getWindowManager()
                                              .getDefaultDisplay();
        DisplayMetrics dm = 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, dm);
            dpi = dm.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dpi;
    }

    /**
     * 功能描述:獲取虛擬按鍵區域的高度
     *
     * @param context
     * @return int 如果有虛擬按鍵則返回其高度否則返回0;
     */
    public static int getNavigationAreaHeight(Context context) {
        int realScreenHeight = AppScreenMgr.getRealScreenHeight(context);
        int screenHeight = AppScreenMgr.getScreenHeight(context);

        return realScreenHeight - screenHeight;
    }

    /**
     * 獲取導航欄高度
     * @param c
     * @return
     */
    public static int getNavigationBarrH(Context c) {
        Resources resources = c.getResources();
        int identifier = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        return resources.getDimensionPixelOffset(identifier);
    }

    private AppScreenMgr()
    {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * 獲取當前屏幕截圖,包含狀態欄
     */
    public static Bitmap snapShotWithStatusBar(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 = null;
        bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
        view.destroyDrawingCache();
        return bp;

    }

    /**
     * 獲取當前屏幕截圖,不包含狀態欄
     */
    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(activity);
        int height = getScreenHeight(activity);
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return bp;
    }

    /**
     * 獲得標題欄高度
     *
     * @param context 上下文,爲Activity對象
     * @return 標題欄高度
     */
    public static int getTitleBarHeight(Activity context) {
        int contentTop = context.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
        return contentTop - getStatusBarHeight(context);
    }

    /**
     * 獲取通知欄高度
     *
     * @param context 上下文
     * @return 通知欄高度
     */
    public static int getStatusBarHeight(Context context) {
        int statusBarHeight = 0;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object obj = clazz.newInstance();
            Field field = clazz.getField("status_bar_height");
            int temp = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(temp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     *  獲取指定Activity的截屏,保存到png文件
     *
     * @param activity activity
     * @return 截屏Bitmap
     */
    private static Bitmap takeScreenShot(Activity activity) {
        // View是你需要截圖的View
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();

        // 獲取狀態欄高度
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        Log.i("TAG", "" + statusBarHeight);

        // 獲取屏幕長和高
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        int height = activity.getWindowManager().getDefaultDisplay()
                             .getHeight();
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
            - statusBarHeight);
        view.destroyDrawingCache();
        return b;
    }

    /**
     * 保存bitmap
     *
     * @param b           bitmap
     * @param strFileName 文件名
     * @return 是否保存成功
     */
    private static boolean savePic(Bitmap b, String strFileName) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(strFileName);
            if (null != fos) {
                b.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
                return true;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 截取webView快照(webView加載的整個內容的大小)
     *
     * @param webView webview
     * @return 截屏bitmap
     */
    private static Bitmap captureWebView(WebView webView) {
        Picture snapShot = webView.capturePicture();

        Bitmap bmp = Bitmap.createBitmap(snapShot.getWidth(), snapShot.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        snapShot.draw(canvas);
        return bmp;
    }

    /**
     * 根據毫秒獲得格式化日期
     *
     * @param time   毫秒數
     * @param format 格式化字符串
     * @return 格式化後的字符串
     */
    private static String getDate(long time, String format) {
        Date date = new Date(time);
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String daystr = formatter.format(date);
        return daystr;
    }

    /**
     * 是否存在sd卡
     *
     * @return 是否存在sd卡
     */
    private static Boolean isExistsSD() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            return true;
        return false;
    }

    /**
     * 獲得文件名
     *
     * @param context 上下文
     * @return 文件名
     */
    private static String getFileName(Context context) {
        String fileName = getDate(System.currentTimeMillis(), "yyyyMMddHHmmss") + ".png";
        final String localPath;
        if (isExistsSD()) {
            localPath = context.getExternalCacheDir() + File.separator + fileName;
        } else {
            localPath = context.getFilesDir() + fileName;
        }

        return localPath;
    }

    /**
     * 截屏並保存
     *
     * @param a activity
     * @return 保存的路徑
     */
    public static String shoot(Activity a) {
        String localPath = getFileName(a);
        boolean ret = AppScreenMgr.savePic(AppScreenMgr.takeScreenShot(a), localPath);
        if (ret) {
            return localPath;
        } else {
            return "";
        }
    }

    /**
     * 截屏並保存
     *
     * @param context 上下文
     * @param webView webview
     * @return 保存的路徑
     */
    public static String shootWebView(Context context, WebView webView) {
        String localPath = getFileName(context);
        boolean ret = AppScreenMgr.savePic(AppScreenMgr.captureWebView(webView), localPath);
        if (ret) {
            return localPath;
        } else {
            return "";
        }
    }
}

log日誌的封裝

public class AppLogMessageMgr {
    //是否輸出
    private static boolean isDebug = true;

    /*
     * 設置debug模式(true:打印日誌  false:不打印)
     */
    public static void isEnableDebug(boolean isDebug){
        AppLogMessageMgr.isDebug = isDebug;
    }
    
    /**
     * 
     * @param tag
     * @param msg
     */
    public static void i(String tag,String msg){
        if(isDebug){
            Log.i(tag, msg != null ? msg : "");
        }
    }

    public static void i(Object object,String msg){
        if(isDebug){
            Log.i(object.getClass().getSimpleName(), msg != null ? msg : "");
        }
    }

    public static void i(String msg){
        if(isDebug){
            Log.i(" [INFO] --- ", msg != null ? msg : "");
        }
    }

    /**
     * 
     * @param tag
     * @param msg
     */
    public static void d(String tag,String msg){
        if(isDebug){
            Log.d(tag, msg != null ? msg : "");
        }
    }

    public static void d(Object object,String msg){
        if(isDebug){
            Log.d(object.getClass().getSimpleName(), msg != null ? msg : "");
        }
    }

    public static void d(String msg){
        if(isDebug){
            Log.d(" [DEBUG] --- ", msg != null ? msg : "");
        }
    }

    /**
     * 
     * @param tag
     * @param msg
     */
    public static void w(String tag,String msg){
        if(isDebug){
            Log.w(tag, msg != null ? msg : "");
        }
    }

    public static void w(Object object,String msg){
        if(isDebug){
            Log.w(object.getClass().getSimpleName(), msg != null ? msg : "");
        }
    }

    public static void w(String msg){
        if(isDebug){
            Log.w(" [WARN] --- ", msg != null ? msg : "");
        }
    }

    /**
     * 
     * @param tag
     * @param msg
     */
    public static void e(String tag,String msg){
        if(isDebug){
            Log.e(tag, msg !=null ? msg : "");
        }
    }

    public static void e(Object object,String msg){
        if(isDebug){
            Log.e(object.getClass().getSimpleName(), msg !=null ? msg : "");
        }
    }

    public static void e(String msg){
        if(isDebug){
            Log.e(" [ERROR] --- ", msg !=null ? msg : "");
        }
    }

    /**
     * 
     * @param tag
     * @param msg
     */
    public static void v(String tag, String msg){
        if(isDebug){
            Log.v(tag, msg != null ? msg : "");
        }
    }

    public static void v(Object object, String msg){
        if(isDebug){
            Log.v(object.getClass().getSimpleName(), msg != null ? msg : "");
        }
    }

    public static void v( String msg){
        if(isDebug){
            Log.v(" [VERBOSE] --- ", msg != null ? msg : "");
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章