Android 常用工具类

来源:互联网 发布:java文件上传下载原理 编辑:程序博客网 时间:2024/05/18 03:33

在Android开发中我们会经常用到一些工具,比如判断是否有网络等,今天我总结一下我在开发中用到的一些工具

1、网络判断工具

public class NetUtils {
// 没有连接网络
public static final int NETWORN_NONE = 0;
// 无线网络
public static final int NETWORN_WIFI = 1;
// 移动网络
public static final int NETWORN_MOBILE = 2;

public static int getNetworkState(Context context) {
// 得到连接管理器对象
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo mNetworkInfo = connManager.getActiveNetworkInfo();
NetworkInfo mNetworkInfo = connManager.getActiveNetworkInfo();
if (mNetworkInfo != null && mNetworkInfo.isConnected()) {
// Wifi
if (mNetworkInfo.getType() == (connManager.TYPE_WIFI)) {
return NETWORN_WIFI;
} else if (mNetworkInfo.getType() == (connManager.TYPE_MOBILE)) {
return NETWORN_MOBILE;
}
} else {
return NETWORN_NONE;
}
return NETWORN_NONE;
}
}


2、点击空白处隐藏软键盘

/**
 * 点击空白区域,隐藏输入法软键盘
 *
 */
public class HideKeyBoardUtils {

/**
     * 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    public static boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                top = l[1],
                bottom = top + v.getHeight(),
                right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件,忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditText上,和用户用轨迹球选择其他的焦点
        return false;
    }
 
    /**
     * 获取InputMethodManager,隐藏软键盘
     * @param token
     */
    public static void hideKeyboard(IBinder token,Context context) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}

在Activity中的应用

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (HideKeyBoardUtils.isShouldHideKeyboard(v, ev)) {
HideKeyBoardUtils.hideKeyboard(v.getWindowToken(), this);
}
}
return super.dispatchTouchEvent(ev);
}


3、文件操作工具

package com.gsd.studytreasure.util;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;


import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;


public class FileUtil {
/**
* 删除文件

* @param context
*            程序上下文
* @param fileName
*            文件名,要在系统内保持唯一
* @return boolean 存储成功的标志
*/
public static boolean deleteFile(Context context, String fileName) {
return context.deleteFile(fileName);
}


/**
* 文件是否存在

* @param context
* @param fileName
* @return
*/
public static boolean exists(Context context, String fileName) {
return new File(context.getFilesDir(), fileName).exists();
}


/**
* 存储文本数据

* @param context
*            程序上下文
* @param fileName
*            文件名,要在系统内保持唯一
* @param content
*            文本内容
* @return boolean 存储成功的标志
*/
public static boolean writeFile(Context context, String fileName,
String content) {
boolean success = false;
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] byteContent = content.getBytes();
fos.write(byteContent);


success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}


return success;
}


/**
* 存储文本数据

* @param context
*            程序上下文
* @param fileName
*            文件名,要在系统内保持唯一
* @param content
*            文本内容
* @return boolean 存储成功的标志
*/
public static boolean writeFile(String filePath, String content) {
boolean success = false;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filePath);
byte[] byteContent = content.getBytes();
fos.write(byteContent);


success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}


return success;
}


/**
* 读取文本数据

* @param context
*            程序上下文
* @param fileName
*            文件名
* @return String, 读取到的文本内容,失败返回null
*/
public static String readFile(Context context, String fileName) {
if (!exists(context, fileName)) {
return null;
}
FileInputStream fis = null;
String content = null;
try {
fis = context.openFileInput(fileName);
if (fis != null) {


byte[] buffer = new byte[1024];
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
while (true) {
int readLength = fis.read(buffer);
if (readLength == -1)
break;
arrayOutputStream.write(buffer, 0, readLength);
}
fis.close();
arrayOutputStream.close();
content = new String(arrayOutputStream.toByteArray());


}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
content = null;
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return content;
}


/**
* 读取文本数据

* @param context
*            程序上下文
* @param fileName
*            文件名
* @return String, 读取到的文本内容,失败返回null
*/
public static String readFile(String filePath) {
if (filePath == null || !new File(filePath).exists()) {
return null;
}
FileInputStream fis = null;
String content = null;
try {
fis = new FileInputStream(filePath);
if (fis != null) {


byte[] buffer = new byte[1024];
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
while (true) {
int readLength = fis.read(buffer);
if (readLength == -1)
break;
arrayOutputStream.write(buffer, 0, readLength);
}
fis.close();
arrayOutputStream.close();
content = new String(arrayOutputStream.toByteArray());


}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
content = null;
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return content;
}


/**
* 读取文本数据

* @param context
*            程序上下文
* @param fileName
*            文件名
* @return String, 读取到的文本内容,失败返回null
*/
public static String readAssets(Context context, String fileName) {
InputStream is = null;
String content = null;
try {
is = context.getAssets().open(fileName);
if (is != null) {


byte[] buffer = new byte[1024];
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
while (true) {
int readLength = is.read(buffer);
if (readLength == -1)
break;
arrayOutputStream.write(buffer, 0, readLength);
}
is.close();
arrayOutputStream.close();
content = new String(arrayOutputStream.toByteArray());


}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
content = null;
} finally {
try {
if (is != null)
is.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return content;
}


/**
* 存储单个Parcelable对象

* @param context
*            程序上下文
* @param fileName
*            文件名,要在系统内保持唯一
* @param parcelObject
*            对象必须实现Parcelable
* @return boolean 存储成功的标志
*/
public static boolean writeParcelable(Context context, String fileName,
Parcelable parcelObject) {
boolean success = false;
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
Parcel parcel = Parcel.obtain();
parcel.writeParcelable(parcelObject,
Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
byte[] data = parcel.marshall();
fos.write(data);


success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}


return success;
}


/**
* 存储List对象

* @param context
*            程序上下文
* @param fileName
*            文件名,要在系统内保持唯一
* @param list
*            对象数组集合,对象必须实现Parcelable
* @return boolean 存储成功的标志
*/
public static boolean writeParcelableList(Context context, String fileName,
List<Parcelable> list) {
boolean success = false;
FileOutputStream fos = null;
try {
if (list instanceof List) {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
Parcel parcel = Parcel.obtain();
parcel.writeList(list);
byte[] data = parcel.marshall();
fos.write(data);


success = true;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}


return success;
}


/**
* 读取单个数据对象

* @param context
*            程序上下文
* @param fileName
*            文件名
* @return Parcelable, 读取到的Parcelable对象,失败返回null
*/
@SuppressWarnings("unchecked")
public static Parcelable readParcelable(Context context, String fileName,
ClassLoader classLoader) {
Parcelable parcelable = null;
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = context.openFileInput(fileName);
if (fis != null) {
bos = new ByteArrayOutputStream();
byte[] b = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}


byte[] data = bos.toByteArray();


Parcel parcel = Parcel.obtain();
parcel.unmarshall(data, 0, data.length);
parcel.setDataPosition(0);
parcelable = parcel.readParcelable(classLoader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
parcelable = null;
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}


return parcelable;
}


/**
* 读取数据对象列表

* @param context
*            程序上下文
* @param fileName
*            文件名
* @return List, 读取到的对象数组,失败返回null
*/
@SuppressWarnings("unchecked")
public static List<Parcelable> readParcelableList(Context context,
String fileName, ClassLoader classLoader) {
List<Parcelable> results = null;
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = context.openFileInput(fileName);
if (fis != null) {
bos = new ByteArrayOutputStream();
byte[] b = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}


byte[] data = bos.toByteArray();


Parcel parcel = Parcel.obtain();
parcel.unmarshall(data, 0, data.length);
parcel.setDataPosition(0);
results = parcel.readArrayList(classLoader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
results = null;
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}


return results;
}


public static boolean saveSerializable(Context context, String fileName,
Serializable data) {
boolean success = false;
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(context.openFileOutput(fileName,
Context.MODE_PRIVATE));
oos.writeObject(data);
success = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return success;
}


public static Serializable readSerialLizable(Context context,
String fileName) {
Serializable data = null;
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(context.openFileInput(fileName));
data = (Serializable) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


return data;
}


/**
* 从assets里边读取字符串

* @param context
* @param fileName
* @return
*/
public static String getFromAssets(Context context, String fileName) {
try {
InputStreamReader inputReader = new InputStreamReader(context
.getResources().getAssets().open(fileName));
BufferedReader bufReader = new BufferedReader(inputReader);
String line = "";
String Result = "";
while ((line = bufReader.readLine()) != null)
Result += line;
return Result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}


/**
* 复制文件

* @param srcFile
* @param dstFile
* @return
*/
public static boolean copy(String srcFile, String dstFile) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {


File dst = new File(dstFile);
if (!dst.getParentFile().exists()) {
dst.getParentFile().mkdirs();
}


fis = new FileInputStream(srcFile);
fos = new FileOutputStream(dstFile);


byte[] buffer = new byte[1024];
int len = 0;


while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}


} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}


}
return true;
}

/**
*  删除指定文件
* @param filePath
* @return
*/
public static boolean delete(String filePath) {
File file = new File(filePath);
if(file.exists()){
file.delete();
return true;
}
return false;
}
}

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

public class ScreenUtils {
/**
* 获得屏幕宽度

* @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;


}
}


5、像素转化

public class DisplayUtil {

public static final String TAG = "DisplayUtil";

/**
* 根据手机的分辨率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 static float sp2px(Context context, float sp){
       final float scale = context.getResources().getDisplayMetrics().scaledDensity;
       return sp * scale;
 }
 
public static int px2sp(Context context, float pxValue) {
       float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
       return (int)(pxValue / fontScale + 0.5F);
}
}

6、倒计时工具类

public class CountDownTimerUtils extends CountDownTimer{

private Button mBtn;

public CountDownTimerUtils(Button btn,long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.mBtn = btn;
}


    //计时完毕的方法
@Override
public void onFinish() {
mBtn.setEnabled(true);
mBtn.setText("重新获取验证码");
}

//计时过程
@Override
public void onTick(long arg0) {
//防止计时过程中重复点击
mBtn.setEnabled(false);
mBtn.setText("重新获取"+arg0/1000+"s");
}
}


7、管理栈中的activity

public class ActivityManagerUtils {
private static final String TAG = "ActivityManager";
private static Stack<Activity> activityStack;
private static ActivityManagerUtils instance;
private Activity currActivity;


private ActivityManagerUtils() {
}


public static ActivityManagerUtils getActivityManager() {
if (instance == null) {
instance = new ActivityManagerUtils();
}
return instance;
}


// 退出栈顶Activity
public void popActivity(Activity activity) {
if (activity == null || activityStack == null) {
return;
}
if (activityStack.contains(activity)) {
activityStack.remove(activity);
}
currActivity = activity;
// activity.finish();


// activity = null;
}


public void destoryActivity(Activity activity) {
if (activity == null) {
return;
}
activity.finish();
if (activityStack.contains(activity)) {
activityStack.remove(activity);
}
activity = null;
}


// 获得当前栈顶Activity
public Activity currentActivity() {
if (activityStack == null || activityStack.empty()) {
return null;
}
return activityStack.lastElement();
}


// 将当前Activity推入栈中
public void pushActivity(Activity activity) {
if (activityStack == null) {
activityStack = new Stack<Activity>();
}
activityStack.add(activity);
}


// 退出栈中除指定的Activity外的所有
@SuppressWarnings("rawtypes")
public void popAllActivityExceptOne(Class cls) {
while (true) {
Activity activity = currentActivity();
if (activity == null) {
break;
}
if (activity.getClass().equals(cls)) {
break;
}
destoryActivity(activity);
}
}


// 退出栈中所有Activity
public void popAllActivity() {
popAllActivityExceptOne(null);
}


public Activity getCurrentActivity() {
return currActivity;
}


public int getActivityStackSize() {
int size = 0;
if (activityStack != null) {
size = activityStack.size();
}
return size;
}
}

8、Log统一管理工具 

public class LogUtil {
    /**
     * 是否开启debug
     */
    public static boolean isDebug=true;


    public static void e(String TAG,String msg){
        if(isDebug){
            Log.e(TAG, msg );
        }
    }


    public static void i(String TAG,String msg){
        if(isDebug){
            Log.i(TAG, msg );
        }
    }


    public static void w(String TAG,String msg){
        if(isDebug){
            Log.w(TAG, msg );
        }
    }


    public static void d(String TAG,String msg){
        if(isDebug){
            Log.d(TAG, msg );
        }
    }


    public static void v(String TAG,String msg){
        if(isDebug){
            Log.v(TAG, msg );
        }
    }
}

9、SharedPreferences相关工具类,可用于方便的向SharedPreferences中读取和写入相关类型数据

public class PreferencesUtils {
    private static final String TAG = "PreferencesUtils";
    private PreferencesUtils() {
        throw new AssertionError();
    }


    /**
     * put String preferences
     * @param context 上下文对象
     * @param xmlName 保存数据的文件名
     * @param key 保存数据的key名称
     * @param value 保存数据的值
     * @return
     */
    public static boolean putString(Context context,String xmlName, String key, String value){
        SharedPreferences settings = context.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        return editor.commit();
    }


    /**
     * get string preferences
     * @param context
     * @param xmlName
     * @param key
     * @return
     */
    public static String getString(Context context,String xmlName,String key) {
        return getString(context,xmlName,key, null);
    }


    /**
     * get string preferences
     * @param context
     * @param xmlName
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getString(Context context,String xmlName, String key, String defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        return settings.getString(key, defaultValue);
    }


    /**
     * put int preferences
     * @param context
     * @param xmlName 保存文件名
     * @param key
     * @param value
     * @return
     */
    public static boolean putInt(Context context,String xmlName, String key, int value) {
        SharedPreferences settings = context.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(key, value);
        return editor.commit();
    }


    /**
     * get int preferences
     * @param context
     * @param xmlName
     * @param key
     * @return
     */
    public static int getInt(Context context,String xmlName, String key) {
        return getInt(context,xmlName, key, -1);
    }


    /**
     * get int preferences
     * @param context
     * @param xmlName
     * @param key
     * @param defaultValue
     * @return
     */
    private static int getInt(Context context, String xmlName, String key, int defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        return settings.getInt(key, defaultValue);
    }


    /**
     * put long preferences
     * @param context
     * @param key
     * @param value
     * @return
     */
    public static boolean putLong(Context context, String xmlName, String key, long value) {
        SharedPreferences settings = context.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong(key, value);
        return editor.commit();
    }


    /**
     * get long preferences
     * @param context
     * @param xmlName
     * @param key
     * @return
     */
    public static long getLong(Context context, String xmlName,String key) {
        return getLong(context,xmlName, key, -1);
    }


    /**
     * get long preferences
     * @param context
     * @param xmlName
     * @param key
     * @param defaultValue
     * @return
     */
    private static long getLong(Context context, String xmlName, String key, int defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        return settings.getLong(key, defaultValue);
    }


    /**
     * put float preferences
     * @param context
     * @param xmlName
     * @param key
     * @param value
     * @return
     */
    public static boolean putFloat(Context context,String xmlName, String key, float value) {
        SharedPreferences settings = context.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putFloat(key, value);
        return editor.commit();
    }


    /**
     * get float preferences
     * @param context
     * @param xmlName
     * @param key
     * @return
     */
    public static float getFloat(Context context,String xmlName, String key) {
        return getFloat(context,xmlName, key, -1);
    }


    /**
     * get float preferences
     * @param context
     * @param xmlName
     * @param key
     * @param defaultValue
     * @return
     */
    public static float getFloat(Context context,String xmlName, String key, float defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        return settings.getFloat(key, defaultValue);
    }


    /**
     * put boolean preferences
     * @param context
     * @param xmlName
     * @param key
     * @param value
     * @return
     */
    public static boolean putBoolean(Context context,String xmlName, String key, boolean value) {
        SharedPreferences settings = context.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(key, value);
        return editor.commit();
    }


    /**
     * get boolean preferences, default is false
     * @param context
     * @param xmlName
     * @param key
     * @return
     */
    public static boolean getBoolean(Context context,String xmlName, String key) {
        return getBoolean(context,xmlName, key, false);
    }


    /**
     * get boolean preferences
     * @param context
     * @param xmlName
     * @param key
     * @param defaultValue
     * @return
     */
    public static boolean getBoolean(Context context,String xmlName, String key, boolean defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        return settings.getBoolean(key, defaultValue);
    }
}