亲宝软件园·资讯

展开

Android 4个常用工具类 Android开发中4个常用的工具类【Toast、SharedPreferences、网络及屏幕操作】

LovooGod 人气:1
想了解Android开发中4个常用的工具类【Toast、SharedPreferences、网络及屏幕操作】的相关内容吗,LovooGod在本文为您仔细讲解Android 4个常用工具类的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,工具类,Toast,SharedPreferences,网络,屏幕,下面大家一起来学习吧。

本文实例讲述了Android开发中4个常用的工具类。分享给大家供大家参考,具体如下:

1、土司工具类(Toast管理)

/**
 * Toast统一管理类
 *
 * @Project App_ZXing
 * @Package com.android.scan
 * @author chenlin
 * @version 1.0
 * @Date 2013年7月6日
 * @Note TODO
 */
public class ToastUtil {
  private ToastUtil() {
    /* cannot be instantiated */
    throw new UnsupportedOperationException("cannot be instantiated");
  }
  public static boolean isShow = true;
  /**
   * 短时间显示Toast
   *
   * @param context
   * @param message
   */
  public static void show(Context context, CharSequence message) {
    if (isShow)
      Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
  }
  /**
   * 短时间显示Toast
   *
   * @param context
   * @param message
   */
  public static void showShort(Context context, int message) {
    if (isShow)
      Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
  }
  /**
   * 长时间显示Toast
   *
   * @param context
   * @param message
   */
  public static void showLong(Context context, CharSequence message) {
    if (isShow)
      Toast.makeText(context, message, Toast.LENGTH_LONG).show();
  }
  /**
   * 长时间显示Toast
   *
   * @param context
   * @param message
   */
  public static void showLong(Context context, int message) {
    if (isShow)
      Toast.makeText(context, message, Toast.LENGTH_LONG).show();
  }
  /**
   * 自定义显示Toast时间
   *
   * @param context
   * @param message
   * @param duration
   */
  public static void show(Context context, CharSequence message, int duration) {
    if (isShow)
      Toast.makeText(context, message, duration).show();
  }
  /**
   * 自定义显示Toast时间
   *
   * @param context
   * @param message
   * @param duration
   */
  public static void show(Context context, int message, int duration) {
    if (isShow)
      Toast.makeText(context, message, duration).show();
  }
}

2、SharedPreferences工具类

/**
 * SharedPreferences封装类SPUtils
 * @Project  App_ZXing
 * @Package  com.android.scan
 * @author   chenlin
 * @version  1.0
 * @Date    2013年6月6日
 * @Note    TODO
 */
public class SPUtils {
  /**
   * 保存在手机里面的文件名
   */
  public static final String FILE_NAME = "share_data";
  /**
   * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
   *
   * @param context
   * @param key
   * @param object
   */
  public static void put(Context context, String key, Object object) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    if (object instanceof String) {
      editor.putString(key, (String) object);
    } else if (object instanceof Integer) {
      editor.putInt(key, (Integer) object);
    } else if (object instanceof Boolean) {
      editor.putBoolean(key, (Boolean) object);
    } else if (object instanceof Float) {
      editor.putFloat(key, (Float) object);
    } else if (object instanceof Long) {
      editor.putLong(key, (Long) object);
    } else {
      editor.putString(key, object.toString());
    }
    SharedPreferencesCompat.apply(editor);
  }
  /**
   * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
   *
   * @param context
   * @param key
   * @param defaultObject
   * @return
   */
  public static Object get(Context context, String key, Object defaultObject) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    if (defaultObject instanceof String) {
      return sp.getString(key, (String) defaultObject);
    } else if (defaultObject instanceof Integer) {
      return sp.getInt(key, (Integer) defaultObject);
    } else if (defaultObject instanceof Boolean) {
      return sp.getBoolean(key, (Boolean) defaultObject);
    } else if (defaultObject instanceof Float) {
      return sp.getFloat(key, (Float) defaultObject);
    } else if (defaultObject instanceof Long) {
      return sp.getLong(key, (Long) defaultObject);
    }
    return null;
  }
  /**
   * 移除某个key值已经对应的值
   *
   * @param context
   * @param key
   */
  public static void remove(Context context, String key) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.remove(key);
    SharedPreferencesCompat.apply(editor);
  }
  /**
   * 清除所有数据
   *
   * @param context
   */
  public static void clear(Context context) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.clear();
    SharedPreferencesCompat.apply(editor);
  }
  /**
   * 查询某个key是否已经存在
   *
   * @param context
   * @param key
   * @return
   */
  public static boolean contains(Context context, String key) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    return sp.contains(key);
  }
  /**
   * 返回所有的键值对
   *
   * @param context
   * @return
   */
  public static Map<String, ?> getAll(Context context) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    return sp.getAll();
  }
  /**
   * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
   *
   * @author zhy
   *
   */
  private static class SharedPreferencesCompat {
    private static final Method sApplyMethod = findApplyMethod();
    /**
     * 反射查找apply的方法
     *
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private static Method findApplyMethod() {
      try {
        Class clz = SharedPreferences.Editor.class;
        return clz.getMethod("apply");
      } catch (NoSuchMethodException e) {
      }
      return null;
    }
    /**
     * 如果找到则使用apply执行,否则使用commit
     *
     * @param editor
     */
    public static void apply(SharedPreferences.Editor editor) {
      try {
        if (sApplyMethod != null) {
          sApplyMethod.invoke(editor);
          return;
        }
      } catch (IllegalArgumentException e) {
      } catch (IllegalAccessException e) {
      } catch (InvocationTargetException e) {
      }
      editor.commit();
    }
  }
}

3、网络工具类

/**
 * 跟网络相关的工具类
 * @Project  App_ZXing
 * @Package  com.android.scan
 * @author   chenlin
 * @version  1.0
 * @Date    2013年6月8日
 * @Note    TODO
 */
public class NetUtils {
  private NetUtils() {
    /* cannot be instantiated */
    throw new UnsupportedOperationException("cannot be instantiated");
  }
  /**
   * 判断网络是否连接
   *
   * @param context
   * @return
   */
  public static boolean isConnected(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (null != connectivity) {
      NetworkInfo info = connectivity.getActiveNetworkInfo();
      if (null != info && info.isConnected()) {
        if (info.getState() == NetworkInfo.State.CONNECTED) {
          return true;
        }
      }
    }
    return false;
  }
  /**
   * 判断是否是wifi连接
   */
  public static boolean isWifi(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null)
      return false;
    return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
  }
  /**
   * 打开网络设置界面
   */
  public static void openSetting(Activity activity) {
    Intent intent = new Intent("/");
    ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
    intent.setComponent(cm);
    intent.setAction("android.intent.action.VIEW");
    activity.startActivityForResult(intent, 0);
  }
}

4、获得屏幕相关的辅助类

/**
 * 获得屏幕相关的辅助类
 * @Project  App_ZXing
 * @Package  com.android.scan
 * @author   chenlin
 * @version  1.0
 * @Date    2013年6月6日
 */
public class ScreenUtils {
  private ScreenUtils() {
    /* cannot be instantiated */
    throw new UnsupportedOperationException("cannot be instantiated");
  }
  /**
   * 获得屏幕高度
   *
   * @param context
   * @return
   */
  public static int getScreenWidth(Context context) {
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics outMetrics = new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(outMetrics);
    return outMetrics.widthPixels;
  }
  /**
   * 获得屏幕宽度
   *
   * @param context
   * @return
   */
  public static int getScreenHeight(Context context) {
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics outMetrics = new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(outMetrics);
    return outMetrics.heightPixels;
  }
  /**
   * 获得状态栏的高度
   *
   * @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;
  }
  /**
   * 获取当前屏幕截图,包含状态栏
   *
   * @param activity
   * @return
   */
  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;
  }
  /**
   * 获取当前屏幕截图,不包含状态栏
   *
   * @param activity
   * @return
   */
  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;
  }
}

希望本文所述对大家Android程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论