实例详解Android快速开发工具类总结
一、日志工具类Log.java
publicclassL
{
privateL()
{
/*不可被实例化*/
thrownewUnsupportedOperationException("Cannotbeinstantiated!");
}
//是否需要打印bug,可以在application的onCreate函数里面初始化
publicstaticbooleanisDebug=true;
privatestaticfinalStringTAG="DefaultTag";
//下面四个是默认tag的函数
publicstaticvoidi(Stringmsg)
{
if(isDebug)
Log.i(TAG,msg);
}
publicstaticvoidd(Stringmsg)
{
if(isDebug)
Log.d(TAG,msg);
}
publicstaticvoide(Stringmsg)
{
if(isDebug)
Log.e(TAG,msg);
}
publicstaticvoidv(Stringmsg)
{
if(isDebug)
Log.v(TAG,msg);
}
//下面是传入自定义tag的函数
publicstaticvoidi(Stringtag,Stringmsg)
{
if(isDebug)
Log.i(tag,msg);
}
publicstaticvoidd(Stringtag,Stringmsg)
{
if(isDebug)
Log.i(tag,msg);
}
publicstaticvoide(Stringtag,Stringmsg)
{
if(isDebug)
Log.i(tag,msg);
}
publicstaticvoidv(Stringtag,Stringmsg)
{
if(isDebug)
Log.i(tag,msg);
}
}
二、Toast统一管理类Tost.java
publicclassT
{
privateT()
{
/*cannotbeinstantiated*/
thrownewUnsupportedOperationException("cannotbeinstantiated");
}
publicstaticbooleanisShow=true;
/**
*短时间显示Toast
*/
publicstaticvoidshowShort(Contextcontext,CharSequencemessage)
{
if(isShow)
Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
}
/**
*短时间显示Toast
*@parammessage要显示的字符串资源的id
*/
publicstaticvoidshowShort(Contextcontext,intmessage)
{
if(isShow)
Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
}
/**
*长时间显示Toast
*/
publicstaticvoidshowLong(Contextcontext,CharSequencemessage)
{
if(isShow)
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
/**
*长时间显示Toast
*/
publicstaticvoidshowLong(Contextcontext,intmessage)
{
if(isShow)
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
/**
*自定义显示Toast时间
*/
publicstaticvoidshow(Contextcontext,CharSequencemessage,intduration)
{
if(isShow)
Toast.makeText(context,message,duration).show();
}
/**
*自定义显示Toast时间
*/
publicstaticvoidshow(Contextcontext,intmessage,intduration)
{
if(isShow)
Toast.makeText(context,message,duration).show();
}
}
三、SharedPreferences封装类SPUtils.java和PreferencesUtils.java
1.SPUtils.java
publicclassSPUtils
{
/**
*保存在手机里面的文件名
*/
publicstaticfinalStringFILE_NAME="share_data";
/**
*保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
*
*@paramcontext
*@paramkey
*@paramobject
*/
publicstaticvoidput(Contextcontext,Stringkey,Objectobject)
{
SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editoreditor=sp.edit();
if(objectinstanceofString)
{
editor.putString(key,(String)object);
}elseif(objectinstanceofInteger)
{
editor.putInt(key,(Integer)object);
}elseif(objectinstanceofBoolean)
{
editor.putBoolean(key,(Boolean)object);
}elseif(objectinstanceofFloat)
{
editor.putFloat(key,(Float)object);
}elseif(objectinstanceofLong)
{
editor.putLong(key,(Long)object);
}else
{
editor.putString(key,object.toString());
}
SharedPreferencesCompat.apply(editor);
}
/**
*得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*
*@paramcontext
*@paramkey
*@paramdefaultObject
*@return
*/
publicstaticObjectget(Contextcontext,Stringkey,ObjectdefaultObject)
{
SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
if(defaultObjectinstanceofString)
{
returnsp.getString(key,(String)defaultObject);
}elseif(defaultObjectinstanceofInteger)
{
returnsp.getInt(key,(Integer)defaultObject);
}elseif(defaultObjectinstanceofBoolean)
{
returnsp.getBoolean(key,(Boolean)defaultObject);
}elseif(defaultObjectinstanceofFloat)
{
returnsp.getFloat(key,(Float)defaultObject);
}elseif(defaultObjectinstanceofLong)
{
returnsp.getLong(key,(Long)defaultObject);
}
returnnull;
}
/**
*移除某个key值已经对应的值
*@paramcontext
*@paramkey
*/
publicstaticvoidremove(Contextcontext,Stringkey)
{
SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editoreditor=sp.edit();
editor.remove(key);
SharedPreferencesCompat.apply(editor);
}
/**
*清除所有数据
*@paramcontext
*/
publicstaticvoidclear(Contextcontext)
{
SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editoreditor=sp.edit();
editor.clear();
SharedPreferencesCompat.apply(editor);
}
/**
*查询某个key是否已经存在
*@paramcontext
*@paramkey
*@return
*/
publicstaticbooleancontains(Contextcontext,Stringkey)
{
SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
returnsp.contains(key);
}
/**
*返回所有的键值对
*
*@paramcontext
*@return
*/
publicstaticMap<String,?>getAll(Contextcontext)
{
SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
returnsp.getAll();
}
/**
*创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
*
*@authorzhy
*
*/
privatestaticclassSharedPreferencesCompat
{
privatestaticfinalMethodsApplyMethod=findApplyMethod();
/**
*反射查找apply的方法
*
*@return
*/
@SuppressWarnings({"unchecked","rawtypes"})
privatestaticMethodfindApplyMethod()
{
try
{
Classclz=SharedPreferences.Editor.class;
returnclz.getMethod("apply");
}catch(NoSuchMethodExceptione)
{
}
returnnull;
}
/**
*如果找到则使用apply执行,否则使用commit
*
*@parameditor
*/
publicstaticvoidapply(SharedPreferences.Editoreditor)
{
try
{
if(sApplyMethod!=null)
{
sApplyMethod.invoke(editor);
return;
}
}catch(IllegalArgumentExceptione)
{
}catch(IllegalAccessExceptione)
{
}catch(InvocationTargetExceptione)
{
}
editor.commit();
}
}
}
对SharedPreference的使用做了建议的封装,对外公布出put,get,remove,clear等等方法;
注意一点,里面所有的commit操作使用了SharedPreferencesCompat.apply进行了替代,目的是尽可能的使用apply代替commit.
首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是UI线程中,毕竟是IO操作,尽可能异步;
所以我们使用apply进行替代,apply异步的进行写入;
但是apply相当于commit来说是newAPI呢,为了更好的兼容,我们做了适配;
SharedPreferencesCompat也可以给大家创建兼容类提供了一定的参考
2.SPUtils.java
publicclassPreferencesUtils{
publicstaticStringPREFERENCE_NAME="TrineaAndroidCommon";
privatePreferencesUtils(){
thrownewAssertionError();
}
/**
*putstringpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetomodify
*@paramvalueThenewvalueforthepreference
*@returnTrueifthenewvaluesweresuccessfullywrittentopersistentstorage.
*/
publicstaticbooleanputString(Contextcontext,Stringkey,Stringvalue){
SharedPreferencessettings=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editoreditor=settings.edit();
editor.putString(key,value);
returneditor.commit();
}
/**
*getstringpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetoretrieve
*@returnThepreferencevalueifitexists,ornull.ThrowsClassCastExceptionifthereisapreferencewiththis
*namethatisnotastring
*@see#getString(Context,String,String)
*/
publicstaticStringgetString(Contextcontext,Stringkey){
returngetString(context,key,null);
}
/**
*getstringpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetoretrieve
*@paramdefaultValueValuetoreturnifthispreferencedoesnotexist
*@returnThepreferencevalueifitexists,ordefValue.ThrowsClassCastExceptionifthereisapreferencewith
*thisnamethatisnotastring
*/
publicstaticStringgetString(Contextcontext,Stringkey,StringdefaultValue){
SharedPreferencessettings=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
returnsettings.getString(key,defaultValue);
}
/**
*putintpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetomodify
*@paramvalueThenewvalueforthepreference
*@returnTrueifthenewvaluesweresuccessfullywrittentopersistentstorage.
*/
publicstaticbooleanputInt(Contextcontext,Stringkey,intvalue){
SharedPreferencessettings=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editoreditor=settings.edit();
editor.putInt(key,value);
returneditor.commit();
}
/**
*getintpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetoretrieve
*@returnThepreferencevalueifitexists,or-.ThrowsClassCastExceptionifthereisapreferencewiththis
*namethatisnotaint
*@see#getInt(Context,String,int)
*/
publicstaticintgetInt(Contextcontext,Stringkey){
returngetInt(context,key,-);
}
/**
*getintpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetoretrieve
*@paramdefaultValueValuetoreturnifthispreferencedoesnotexist
*@returnThepreferencevalueifitexists,ordefValue.ThrowsClassCastExceptionifthereisapreferencewith
*thisnamethatisnotaint
*/
publicstaticintgetInt(Contextcontext,Stringkey,intdefaultValue){
SharedPreferencessettings=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
returnsettings.getInt(key,defaultValue);
}
/**
*putlongpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetomodify
*@paramvalueThenewvalueforthepreference
*@returnTrueifthenewvaluesweresuccessfullywrittentopersistentstorage.
*/
publicstaticbooleanputLong(Contextcontext,Stringkey,longvalue){
SharedPreferencessettings=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editoreditor=settings.edit();
editor.putLong(key,value);
returneditor.commit();
}
/**
*getlongpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetoretrieve
*@returnThepreferencevalueifitexists,or-.ThrowsClassCastExceptionifthereisapreferencewiththis
*namethatisnotalong
*@see#getLong(Context,String,long)
*/
publicstaticlonggetLong(Contextcontext,Stringkey){
returngetLong(context,key,-);
}
/**
*getlongpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetoretrieve
*@paramdefaultValueValuetoreturnifthispreferencedoesnotexist
*@returnThepreferencevalueifitexists,ordefValue.ThrowsClassCastExceptionifthereisapreferencewith
*thisnamethatisnotalong
*/
publicstaticlonggetLong(Contextcontext,Stringkey,longdefaultValue){
SharedPreferencessettings=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
returnsettings.getLong(key,defaultValue);
}
/**
*putfloatpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetomodify
*@paramvalueThenewvalueforthepreference
*@returnTrueifthenewvaluesweresuccessfullywrittentopersistentstorage.
*/
publicstaticbooleanputFloat(Contextcontext,Stringkey,floatvalue){
SharedPreferencessettings=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editoreditor=settings.edit();
editor.putFloat(key,value);
returneditor.commit();
}
/**
*getfloatpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetoretrieve
*@returnThepreferencevalueifitexists,or-.ThrowsClassCastExceptionifthereisapreferencewiththis
*namethatisnotafloat
*@see#getFloat(Context,String,float)
*/
publicstaticfloatgetFloat(Contextcontext,Stringkey){
returngetFloat(context,key,-);
}
/**
*getfloatpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetoretrieve
*@paramdefaultValueValuetoreturnifthispreferencedoesnotexist
*@returnThepreferencevalueifitexists,ordefValue.ThrowsClassCastExceptionifthereisapreferencewith
*thisnamethatisnotafloat
*/
publicstaticfloatgetFloat(Contextcontext,Stringkey,floatdefaultValue){
SharedPreferencessettings=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
returnsettings.getFloat(key,defaultValue);
}
/**
*putbooleanpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetomodify
*@paramvalueThenewvalueforthepreference
*@returnTrueifthenewvaluesweresuccessfullywrittentopersistentstorage.
*/
publicstaticbooleanputBoolean(Contextcontext,Stringkey,booleanvalue){
SharedPreferencessettings=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editoreditor=settings.edit();
editor.putBoolean(key,value);
returneditor.commit();
}
/**
*getbooleanpreferences,defaultisfalse
*
*@paramcontext
*@paramkeyThenameofthepreferencetoretrieve
*@returnThepreferencevalueifitexists,orfalse.ThrowsClassCastExceptionifthereisapreferencewiththis
*namethatisnotaboolean
*@see#getBoolean(Context,String,boolean)
*/
publicstaticbooleangetBoolean(Contextcontext,Stringkey){
returngetBoolean(context,key,false);
}
/**
*getbooleanpreferences
*
*@paramcontext
*@paramkeyThenameofthepreferencetoretrieve
*@paramdefaultValueValuetoreturnifthispreferencedoesnotexist
*@returnThepreferencevalueifitexists,ordefValue.ThrowsClassCastExceptionifthereisapreferencewith
*thisnamethatisnotaboolean
*/
publicstaticbooleangetBoolean(Contextcontext,Stringkey,booleandefaultValue){
SharedPreferencessettings=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
returnsettings.getBoolean(key,defaultValue);
}
}
四、单位转换类DensityUtils.java
publicclassDensityUtils
{
privateDensityUtils()
{
/*cannotbeinstantiated*/
thrownewUnsupportedOperationException("cannotbeinstantiated");
}
/**
*dp转px
*
*@paramcontext
*@paramval
*@return
*/
publicstaticintdppx(Contextcontext,floatdpVal)
{
return(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal,context.getResources().getDisplayMetrics());
}
/**
*sp转px
*
*@paramcontext
*@paramval
*@return
*/
publicstaticintsppx(Contextcontext,floatspVal)
{
return(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal,context.getResources().getDisplayMetrics());
}
/**
*px转dp
*
*@paramcontext
*@parampxVal
*@return
*/
publicstaticfloatpxdp(Contextcontext,floatpxVal)
{
finalfloatscale=context.getResources().getDisplayMetrics().density;
return(pxVal/scale);
}
/**
*px转sp
*
*@paramfontScale
*@parampxVal
*@return
*/
publicstaticfloatpxsp(Contextcontext,floatpxVal)
{
return(pxVal/context.getResources().getDisplayMetrics().scaledDensity);
}
}
TypedValue:
Containerforadynamicallytypeddatavalue.PrimarilyusedwithResourcesforholdingresourcevalues.
applyDimension(intunit,floatvalue,DisplayMetricsmetrics):
Convertsanunpackedcomplexdatavalueholdingadimensiontoitsfinalfloatingpointvalue.
五、SD卡相关辅助类SDCardUtils.java
publicclassSDCardUtils
{
privateSDCardUtils()
{
/*cannotbeinstantiated*/
thrownewUnsupportedOperationException("cannotbeinstantiated");
}
/**
*判断SDCard是否可用
*
*@return
*/
publicstaticbooleanisSDCardEnable()
{
returnEnvironment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
*获取SD卡路径
*
*@return
*/
publicstaticStringgetSDCardPath()
{
returnEnvironment.getExternalStorageDirectory().getAbsolutePath()
+File.separator;
}
/**
*获取SD卡的剩余容量单位byte
*
*@return
*/
publicstaticlonggetSDCardAllSize()
{
if(isSDCardEnable())
{
StatFsstat=newStatFs(getSDCardPath());
//获取空闲的数据块的数量
longavailableBlocks=(long)stat.getAvailableBlocks()-;
//获取单个数据块的大小(byte)
longfreeBlocks=stat.getAvailableBlocks();
returnfreeBlocks*availableBlocks;
}
return;
}
/**
*获取指定路径所在空间的剩余可用容量字节数,单位byte
*
*@paramfilePath
*@return容量字节SDCard可用空间,内部存储可用空间
*/
publicstaticlonggetFreeBytes(StringfilePath)
{
//如果是sd卡的下的路径,则获取sd卡可用容量
if(filePath.startsWith(getSDCardPath()))
{
filePath=getSDCardPath();
}else
{//如果是内部存储的路径,则获取内存存储的可用容量
filePath=Environment.getDataDirectory().getAbsolutePath();
}
StatFsstat=newStatFs(filePath);
longavailableBlocks=(long)stat.getAvailableBlocks()-;
returnstat.getBlockSize()*availableBlocks;
}
/**
*获取系统存储路径
*
*@return
*/
publicstaticStringgetRootDirectoryPath()
{
returnEnvironment.getRootDirectory().getAbsolutePath();
}
}
StatFs是Android提供的一个类:
Retrieveoverallinformationaboutthespaceonafilesystem.ThisisawrapperforUnixstatvfs().
检索一个文件系统的整体信息空间。这是一个Unixstatvfs()包装器
六、屏幕相关辅助类ScreenUtils.java
publicclassScreenUtils
{
privateScreenUtils()
{
/*cannotbeinstantiated*/
thrownewUnsupportedOperationException("cannotbeinstantiated");
}
/**
*获得屏幕高度
*
*@paramcontext
*@return
*/
publicstaticintgetScreenWidth(Contextcontext)
{
WindowManagerwm=(WindowManager)context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetricsoutMetrics=newDisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
returnoutMetrics.widthPixels;
}
/**
*获得屏幕宽度
*
*@paramcontext
*@return
*/
publicstaticintgetScreenHeight(Contextcontext)
{
WindowManagerwm=(WindowManager)context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetricsoutMetrics=newDisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
returnoutMetrics.heightPixels;
}
/**
*获得状态栏的高度
*
*@paramcontext
*@return
*/
publicstaticintgetStatusHeight(Contextcontext)
{
intstatusHeight=-;
try
{
Class<?>clazz=Class.forName("com.android.internal.R$dimen");
Objectobject=clazz.newInstance();
intheight=Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight=context.getResources().getDimensionPixelSize(height);
}catch(Exceptione)
{
e.printStackTrace();
}
returnstatusHeight;
}
/**
*获取当前屏幕截图,包含状态栏
*
*@paramactivity
*@return
*/
publicstaticBitmapsnapShotWithStatusBar(Activityactivity)
{
Viewview=activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmapbmp=view.getDrawingCache();
intwidth=getScreenWidth(activity);
intheight=getScreenHeight(activity);
Bitmapbp=null;
bp=Bitmap.createBitmap(bmp,,,width,height);
view.destroyDrawingCache();
returnbp;
}
/**
*获取当前屏幕截图,不包含状态栏
*
*@paramactivity
*@return
*/
publicstaticBitmapsnapShotWithoutStatusBar(Activityactivity)
{
Viewview=activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmapbmp=view.getDrawingCache();
Rectframe=newRect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
intstatusBarHeight=frame.top;
intwidth=getScreenWidth(activity);
intheight=getScreenHeight(activity);
Bitmapbp=null;
bp=Bitmap.createBitmap(bmp,,statusBarHeight,width,height
-statusBarHeight);
view.destroyDrawingCache();
returnbp;
}
}
七、App相关辅助类APPUtils.java
publicclassAppUtils
{
privateAppUtils()
{
/*cannotbeinstantiated*/
thrownewUnsupportedOperationException("cannotbeinstantiated");
}
/**
*获取应用程序名称
*/
publicstaticStringgetAppName(Contextcontext)
{
try
{
PackageManagerpackageManager=context.getPackageManager();
PackageInfopackageInfo=packageManager.getPackageInfo(
context.getPackageName(),);
intlabelRes=packageInfo.applicationInfo.labelRes;
returncontext.getResources().getString(labelRes);
}catch(NameNotFoundExceptione)
{
e.printStackTrace();
}
returnnull;
}
/**
*[获取应用程序版本名称信息]
*
*@paramcontext
*@return当前应用的版本名称
*/
publicstaticStringgetVersionName(Contextcontext)
{
try
{
PackageManagerpackageManager=context.getPackageManager();
PackageInfopackageInfo=packageManager.getPackageInfo(
context.getPackageName(),);
returnpackageInfo.versionName;
}catch(NameNotFoundExceptione)
{
e.printStackTrace();
}
returnnull;
}
}
八、软键盘相关辅助类KeyBoardUtils.java
/**
*打开或关闭软键盘
*/
publicclassKeyBoardUtils
{
/**
*打卡软键盘
*
*@parammEditText输入框
*@parammContext上下文
*/
publicstaticvoidopenKeybord(EditTextmEditText,ContextmContext)
{
InputMethodManagerimm=(InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditText,InputMethodManager.RESULT_SHOWN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
}
/**
*关闭软键盘
*
*@parammEditText输入框
*@parammContext上下文
*/
publicstaticvoidcloseKeybord(EditTextmEditText,ContextmContext)
{
InputMethodManagerimm=(InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditText.getWindowToken(),);
}
}
九、网络相关辅助类NetUtils.java
publicclassNetUtils
{
privateNetUtils()
{
/*cannotbeinstantiated*/
thrownewUnsupportedOperationException("cannotbeinstantiated");
}
/**
*判断网络是否连接
*/
publicstaticbooleanisConnected(Contextcontext)
{
ConnectivityManagerconnectivity=(ConnectivityManager)context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if(null!=connectivity)
{
NetworkInfoinfo=connectivity.getActiveNetworkInfo();
if(null!=info&&info.isConnected())
{
if(info.getState()==NetworkInfo.State.CONNECTED)
{
returntrue;
}
}
}
returnfalse;
}
/**
*判断是否是wifi连接
*/
publicstaticbooleanisWifi(Contextcontext)
{
ConnectivityManagercm=(ConnectivityManager)context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm==null)
returnfalse;
returncm.getActiveNetworkInfo().getType()==ConnectivityManager.TYPE_WIFI;
}
/**
*打开网络设置界面
*/
publicstaticvoidopenSetting(Activityactivity)
{
Intentintent=newIntent("/");
ComponentNamecm=newComponentName("com.android.settings",
"com.android.settings.WirelessSettings");
intent.setComponent(cm);
intent.setAction("android.intent.action.VIEW");
activity.startActivityForResult(intent,);
}
}
十、Http相关辅助类HttpUtils.java
/**
*Http请求的工具类
*/
publicclassHttpUtils
{
privatestaticfinalintTIMEOUT_IN_MILLIONS=;
publicinterfaceCallBack
{
voidonRequestComplete(Stringresult);
}
/**
*异步的Get请求
*
*@paramurlStr
*@paramcallBack
*/
publicstaticvoiddoGetAsyn(finalStringurlStr,finalCallBackcallBack)
{
newThread()
{
publicvoidrun()
{
try
{
Stringresult=doGet(urlStr);
if(callBack!=null)
{
callBack.onRequestComplete(result);
}
}catch(Exceptione)
{
e.printStackTrace();
}
};
}.start();
}
/**
*异步的Post请求
*@paramurlStr
*@paramparams
*@paramcallBack
*@throwsException
*/
publicstaticvoiddoPostAsyn(finalStringurlStr,finalStringparams,
finalCallBackcallBack)throwsException
{
newThread()
{
publicvoidrun()
{
try
{
Stringresult=doPost(urlStr,params);
if(callBack!=null)
{
callBack.onRequestComplete(result);
}
}catch(Exceptione)
{
e.printStackTrace();
}
};
}.start();
}
/**
*Get请求,获得返回数据
*
*@paramurlStr
*@return
*@throwsException
*/
publicstaticStringdoGet(StringurlStr)
{
URLurl=null;
HttpURLConnectionconn=null;
InputStreamis=null;
ByteArrayOutputStreambaos=null;
try
{
url=newURL(urlStr);
conn=(HttpURLConnection)url.openConnection();
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
conn.setRequestMethod("GET");
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
if(conn.getResponseCode()==)
{
is=conn.getInputStream();
baos=newByteArrayOutputStream();
intlen=-;
byte[]buf=newbyte[];
while((len=is.read(buf))!=-)
{
baos.write(buf,,len);
}
baos.flush();
returnbaos.toString();
}else
{
thrownewRuntimeException("responseCodeisnot...");
}
}catch(Exceptione)
{
e.printStackTrace();
}finally
{
try
{
if(is!=null)
is.close();
}catch(IOExceptione)
{
}
try
{
if(baos!=null)
baos.close();
}catch(IOExceptione)
{
}
conn.disconnect();
}
returnnull;
}
/**
*向指定URL发送POST方法的请求
*
*@paramurl
*发送请求的URL
*@paramparam
*请求参数,请求参数应该是name=value&name=value的形式。
*@return所代表远程资源的响应结果
*@throwsException
*/
publicstaticStringdoPost(Stringurl,Stringparam)
{
PrintWriterout=null;
BufferedReaderin=null;
Stringresult="";
try
{
URLrealUrl=newURL(url);
//打开和URL之间的连接
HttpURLConnectionconn=(HttpURLConnection)realUrl
.openConnection();
//设置通用的请求属性
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("charset","utf-");
conn.setUseCaches(false);
//发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
if(param!=null&&!param.trim().equals(""))
{
//获取URLConnection对象对应的输出流
out=newPrintWriter(conn.getOutputStream());
//发送请求参数
out.print(param);
//flush输出流的缓冲
out.flush();
}
//定义BufferedReader输入流来读取URL的响应
in=newBufferedReader(
newInputStreamReader(conn.getInputStream()));
Stringline;
while((line=in.readLine())!=null)
{
result+=line;
}
}catch(Exceptione)
{
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally
{
try
{
if(out!=null)
{
out.close();
}
if(in!=null)
{
in.close();
}
}catch(IOExceptionex)
{
ex.printStackTrace();
}
}
returnresult;
}
}
十一、时间工具类TimeUtils.java
publicclassTimeUtils{
publicstaticfinalSimpleDateFormatDEFAULT_DATE_FORMAT=
newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");
publicstaticfinalSimpleDateFormatDATE_FORMAT_DATE=
newSimpleDateFormat("yyyy-MM-dd");
privateTimeUtils(){
thrownewAssertionError();
}
/**
*longtimetostring
*
*@paramtimeInMillis
*@paramdateFormat
*@return
*/
publicstaticStringgetTime(longtimeInMillis,SimpleDateFormatdateFormat){
returndateFormat.format(newDate(timeInMillis));
}
/**
*longtimetostring,formatis{@link#DEFAULT_DATE_FORMAT}
*
*@paramtimeInMillis
*@return
*/
publicstaticStringgetTime(longtimeInMillis){
returngetTime(timeInMillis,DEFAULT_DATE_FORMAT);
}
/**
*getcurrenttimeinmilliseconds
*
*@return
*/
publicstaticlonggetCurrentTimeInLong(){
returnSystem.currentTimeMillis();
}
/**
*getcurrenttimeinmilliseconds,formatis{@link#DEFAULT_DATE_FORMAT}
*
*@return
*/
publicstaticStringgetCurrentTimeInString(){
returngetTime(getCurrentTimeInLong());
}
/**
*getcurrenttimeinmilliseconds
*
*@return
*/
publicstaticStringgetCurrentTimeInString(SimpleDateFormatdateFormat){
returngetTime(getCurrentTimeInLong(),dateFormat);
}
}
十二、文件工具类FileUtils.java
publicclassFileUtils{
publicfinalstaticStringFILE_EXTENSION_SEPARATOR=".";
privateFileUtils(){
thrownewAssertionError();
}
/**
*readfile
*
*@paramfilePath
*@paramcharsetNameThenameofasupported{@linkjava.nio.charset.Charset</code>charset<code>}
*@returniffilenotexist,returnnull,elsereturncontentoffile
*@throwsRuntimeExceptionifanerroroccurswhileoperatorBufferedReader
*/
publicstaticStringBuilderreadFile(StringfilePath,StringcharsetName){
Filefile=newFile(filePath);
StringBuilderfileContent=newStringBuilder("");
if(file==null||!file.isFile()){
returnnull;
}
BufferedReaderreader=null;
try{
InputStreamReaderis=newInputStreamReader(newFileInputStream(file),charsetName);
reader=newBufferedReader(is);
Stringline=null;
while((line=reader.readLine())!=null){
if(!fileContent.toString().equals("")){
fileContent.append("\r\n");
}
fileContent.append(line);
}
returnfileContent;
}catch(IOExceptione){
thrownewRuntimeException("IOExceptionoccurred.",e);
}finally{
IOUtils.close(reader);
}
}
/**
*writefile
*
*@paramfilePath
*@paramcontent
*@paramappendisappend,iftrue,writetotheendoffile,elseclearcontentoffileandwriteintoit
*@returnreturnfalseifcontentisempty,trueotherwise
*@throwsRuntimeExceptionifanerroroccurswhileoperatorFileWriter
*/
publicstaticbooleanwriteFile(StringfilePath,Stringcontent,booleanappend){
if(StringUtils.isEmpty(content)){
returnfalse;
}
FileWriterfileWriter=null;
try{
makeDirs(filePath);
fileWriter=newFileWriter(filePath,append);
fileWriter.write(content);
returntrue;
}catch(IOExceptione){
thrownewRuntimeException("IOExceptionoccurred.",e);
}finally{
IOUtils.close(fileWriter);
}
}
/**
*writefile
*
*@paramfilePath
*@paramcontentList
*@paramappendisappend,iftrue,writetotheendoffile,elseclearcontentoffileandwriteintoit
*@returnreturnfalseifcontentListisempty,trueotherwise
*@throwsRuntimeExceptionifanerroroccurswhileoperatorFileWriter
*/
publicstaticbooleanwriteFile(StringfilePath,List<String>contentList,booleanappend){
if(ListUtils.isEmpty(contentList)){
returnfalse;
}
FileWriterfileWriter=null;
try{
makeDirs(filePath);
fileWriter=newFileWriter(filePath,append);
inti=;
for(Stringline:contentList){
if(i++>){
fileWriter.write("\r\n");
}
fileWriter.write(line);
}
returntrue;
}catch(IOExceptione){
thrownewRuntimeException("IOExceptionoccurred.",e);
}finally{
IOUtils.close(fileWriter);
}
}
/**
*writefile,thestringwillbewrittentothebeginofthefile
*
*@paramfilePath
*@paramcontent
*@return
*/
publicstaticbooleanwriteFile(StringfilePath,Stringcontent){
returnwriteFile(filePath,content,false);
}
/**
*writefile,thestringlistwillbewrittentothebeginofthefile
*
*@paramfilePath
*@paramcontentList
*@return
*/
publicstaticbooleanwriteFile(StringfilePath,List<String>contentList){
returnwriteFile(filePath,contentList,false);
}
/**
*writefile,thebyteswillbewrittentothebeginofthefile
*
*@paramfilePath
*@paramstream
*@return
*@see{@link#writeFile(String,InputStream,boolean)}
*/
publicstaticbooleanwriteFile(StringfilePath,InputStreamstream){
returnwriteFile(filePath,stream,false);
}
/**
*writefile
*
*@paramfilethefiletobeopenedforwriting.
*@paramstreamtheinputstream
*@paramappendif<code>true</code>,thenbyteswillbewrittentotheendofthefileratherthanthebeginning
*@returnreturntrue
*@throwsRuntimeExceptionifanerroroccurswhileoperatorFileOutputStream
*/
publicstaticbooleanwriteFile(StringfilePath,InputStreamstream,booleanappend){
returnwriteFile(filePath!=null?newFile(filePath):null,stream,append);
}
/**
*writefile,thebyteswillbewrittentothebeginofthefile
*
*@paramfile
*@paramstream
*@return
*@see{@link#writeFile(File,InputStream,boolean)}
*/
publicstaticbooleanwriteFile(Filefile,InputStreamstream){
returnwriteFile(file,stream,false);
}
/**
*writefile
*
*@paramfilethefiletobeopenedforwriting.
*@paramstreamtheinputstream
*@paramappendif<code>true</code>,thenbyteswillbewrittentotheendofthefileratherthanthebeginning
*@returnreturntrue
*@throwsRuntimeExceptionifanerroroccurswhileoperatorFileOutputStream
*/
publicstaticbooleanwriteFile(Filefile,InputStreamstream,booleanappend){
OutputStreamo=null;
try{
makeDirs(file.getAbsolutePath());
o=newFileOutputStream(file,append);
bytedata[]=newbyte[];
intlength=-;
while((length=stream.read(data))!=-){
o.write(data,,length);
}
o.flush();
returntrue;
}catch(FileNotFoundExceptione){
thrownewRuntimeException("FileNotFoundExceptionoccurred.",e);
}catch(IOExceptione){
thrownewRuntimeException("IOExceptionoccurred.",e);
}finally{
IOUtils.close(o);
IOUtils.close(stream);
}
}
/**
*movefile
*
*@paramsourceFilePath
*@paramdestFilePath
*/
publicstaticvoidmoveFile(StringsourceFilePath,StringdestFilePath){
if(TextUtils.isEmpty(sourceFilePath)||TextUtils.isEmpty(destFilePath)){
thrownewRuntimeException("BothsourceFilePathanddestFilePathcannotbenull.");
}
moveFile(newFile(sourceFilePath),newFile(destFilePath));
}
/**
*movefile
*
*@paramsrcFile
*@paramdestFile
*/
publicstaticvoidmoveFile(FilesrcFile,FiledestFile){
booleanrename=srcFile.renameTo(destFile);
if(!rename){
copyFile(srcFile.getAbsolutePath(),destFile.getAbsolutePath());
deleteFile(srcFile.getAbsolutePath());
}
}
/**
*copyfile
*
*@paramsourceFilePath
*@paramdestFilePath
*@return
*@throwsRuntimeExceptionifanerroroccurswhileoperatorFileOutputStream
*/
publicstaticbooleancopyFile(StringsourceFilePath,StringdestFilePath){
InputStreaminputStream=null;
try{
inputStream=newFileInputStream(sourceFilePath);
}catch(FileNotFoundExceptione){
thrownewRuntimeException("FileNotFoundExceptionoccurred.",e);
}
returnwriteFile(destFilePath,inputStream);
}
/**
*readfiletostringlist,aelementoflistisaline
*
*@paramfilePath
*@paramcharsetNameThenameofasupported{@linkjava.nio.charset.Charset</code>charset<code>}
*@returniffilenotexist,returnnull,elsereturncontentoffile
*@throwsRuntimeExceptionifanerroroccurswhileoperatorBufferedReader
*/
publicstaticList<String>readFileToList(StringfilePath,StringcharsetName){
Filefile=newFile(filePath);
List<String>fileContent=newArrayList<String>();
if(file==null||!file.isFile()){
returnnull;
}
BufferedReaderreader=null;
try{
InputStreamReaderis=newInputStreamReader(newFileInputStream(file),charsetName);
reader=newBufferedReader(is);
Stringline=null;
while((line=reader.readLine())!=null){
fileContent.add(line);
}
returnfileContent;
}catch(IOExceptione){
thrownewRuntimeException("IOExceptionoccurred.",e);
}finally{
IOUtils.close(reader);
}
}
/**
*getfilenamefrompath,notincludesuffix
*
*<pre>
*getFileNameWithoutExtension(null)=null
*getFileNameWithoutExtension("")=""
*getFileNameWithoutExtension("")=""
*getFileNameWithoutExtension("abc")="abc"
*getFileNameWithoutExtension("a.mp")="a"
*getFileNameWithoutExtension("a.b.rmvb")="a.b"
*getFileNameWithoutExtension("c:\\")=""
*getFileNameWithoutExtension("c:\\a")="a"
*getFileNameWithoutExtension("c:\\a.b")="a"
*getFileNameWithoutExtension("c:a.txt\\a")="a"
*getFileNameWithoutExtension("/home/admin")="admin"
*getFileNameWithoutExtension("/home/admin/a.txt/b.mp")="b"
*</pre>
*
*@paramfilePath
*@returnfilenamefrompath,notincludesuffix
*@see
*/
publicstaticStringgetFileNameWithoutExtension(StringfilePath){
if(StringUtils.isEmpty(filePath)){
returnfilePath;
}
intextenPosi=filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
intfilePosi=filePath.lastIndexOf(File.separator);
if(filePosi==-){
return(extenPosi==-?filePath:filePath.substring(,extenPosi));
}
if(extenPosi==-){
returnfilePath.substring(filePosi+);
}
return(filePosi<extenPosi?filePath.substring(filePosi+,extenPosi):filePath.substring(filePosi+));
}
/**
*getfilenamefrompath,includesuffix
*
*<pre>
*getFileName(null)=null
*getFileName("")=""
*getFileName("")=""
*getFileName("a.mp")="a.mp"
*getFileName("a.b.rmvb")="a.b.rmvb"
*getFileName("abc")="abc"
*getFileName("c:\\")=""
*getFileName("c:\\a")="a"
*getFileName("c:\\a.b")="a.b"
*getFileName("c:a.txt\\a")="a"
*getFileName("/home/admin")="admin"
*getFileName("/home/admin/a.txt/b.mp")="b.mp"
*</pre>
*
*@paramfilePath
*@returnfilenamefrompath,includesuffix
*/
publicstaticStringgetFileName(StringfilePath){
if(StringUtils.isEmpty(filePath)){
returnfilePath;
}
intfilePosi=filePath.lastIndexOf(File.separator);
return(filePosi==-)?filePath:filePath.substring(filePosi+);
}
/**
*getfoldernamefrompath
*
*<pre>
*getFolderName(null)=null
*getFolderName("")=""
*getFolderName("")=""
*getFolderName("a.mp")=""
*getFolderName("a.b.rmvb")=""
*getFolderName("abc")=""
*getFolderName("c:\\")="c:"
*getFolderName("c:\\a")="c:"
*getFolderName("c:\\a.b")="c:"
*getFolderName("c:a.txt\\a")="c:a.txt"
*getFolderName("c:a\\b\\c\\d.txt")="c:a\\b\\c"
*getFolderName("/home/admin")="/home"
*getFolderName("/home/admin/a.txt/b.mp")="/home/admin/a.txt"
*</pre>
*
*@paramfilePath
*@return
*/
publicstaticStringgetFolderName(StringfilePath){
if(StringUtils.isEmpty(filePath)){
returnfilePath;
}
intfilePosi=filePath.lastIndexOf(File.separator);
return(filePosi==-)?"":filePath.substring(,filePosi);
}
/**
*getsuffixoffilefrompath
*
*<pre>
*getFileExtension(null)=""
*getFileExtension("")=""
*getFileExtension("")=""
*getFileExtension("a.mp")="mp"
*getFileExtension("a.b.rmvb")="rmvb"
*getFileExtension("abc")=""
*getFileExtension("c:\\")=""
*getFileExtension("c:\\a")=""
*getFileExtension("c:\\a.b")="b"
*getFileExtension("c:a.txt\\a")=""
*getFileExtension("/home/admin")=""
*getFileExtension("/home/admin/a.txt/b")=""
*getFileExtension("/home/admin/a.txt/b.mp")="mp"
*</pre>
*
*@paramfilePath
*@return
*/
publicstaticStringgetFileExtension(StringfilePath){
if(StringUtils.isBlank(filePath)){
returnfilePath;
}
intextenPosi=filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
intfilePosi=filePath.lastIndexOf(File.separator);
if(extenPosi==-){
return"";
}
return(filePosi>=extenPosi)?"":filePath.substring(extenPosi+);
}
/**
*Createsthedirectorynamedbythetrailingfilenameofthisfile,includingthecompletedirectorypathrequired
*tocreatethisdirectory.<br/>
*<br/>
*<ul>
*<strong>Attentions:</strong>
*<li>makeDirs("C:\\Users\\Trinea")canonlycreateusersfolder</li>
*<li>makeFolder("C:\\Users\\Trinea\\")cancreateTrineafolder</li>
*</ul>
*
*@paramfilePath
*@returntrueifthenecessarydirectorieshavebeencreatedorthetargetdirectoryalreadyexists,falseoneof
*thedirectoriescannotbecreated.
*<ul>
*<li>if{@linkFileUtils#getFolderName(String)}returnnull,returnfalse</li>
*<li>iftargetdirectoryalreadyexists,returntrue</li>
*<li>return{@linkjava.io.File#makeFolder}</li>
*</ul>
*/
publicstaticbooleanmakeDirs(StringfilePath){
StringfolderName=getFolderName(filePath);
if(StringUtils.isEmpty(folderName)){
returnfalse;
}
Filefolder=newFile(folderName);
return(folder.exists()&&folder.isDirectory())?true:folder.mkdirs();
}
/**
*@paramfilePath
*@return
*@see#makeDirs(String)
*/
publicstaticbooleanmakeFolders(StringfilePath){
returnmakeDirs(filePath);
}
/**
*Indicatesifthisfilerepresentsafileontheunderlyingfilesystem.
*
*@paramfilePath
*@return
*/
publicstaticbooleanisFileExist(StringfilePath){
if(StringUtils.isBlank(filePath)){
returnfalse;
}
Filefile=newFile(filePath);
return(file.exists()&&file.isFile());
}
/**
*Indicatesifthisfilerepresentsadirectoryontheunderlyingfilesystem.
*
*@paramdirectoryPath
*@return
*/
publicstaticbooleanisFolderExist(StringdirectoryPath){
if(StringUtils.isBlank(directoryPath)){
returnfalse;
}
Filedire=newFile(directoryPath);
return(dire.exists()&&dire.isDirectory());
}
/**
*deletefileordirectory
*<ul>
*<li>ifpathisnullorempty,returntrue</li>
*<li>ifpathnotexist,returntrue</li>
*<li>ifpathexist,deleterecursion.returntrue</li>
*<ul>
*
*@parampath
*@return
*/
publicstaticbooleandeleteFile(Stringpath){
if(StringUtils.isBlank(path)){
returntrue;
}
Filefile=newFile(path);
if(!file.exists()){
returntrue;
}
if(file.isFile()){
returnfile.delete();
}
if(!file.isDirectory()){
returnfalse;
}
for(Filef:file.listFiles()){
if(f.isFile()){
f.delete();
}elseif(f.isDirectory()){
deleteFile(f.getAbsolutePath());
}
}
returnfile.delete();
}
/**
*getfilesize
*<ul>
*<li>ifpathisnullorempty,return-</li>
*<li>ifpathexistanditisafile,returnfilesize,elsereturn-</li>
*<ul>
*
*@parampath
*@returnreturnsthelengthofthisfileinbytes.returns-ifthefiledoesnotexist.
*/
publicstaticlonggetFileSize(Stringpath){
if(StringUtils.isBlank(path)){
return-;
}
Filefile=newFile(path);
return(file.exists()&&file.isFile()?file.length():-);
}
}
十三、assets和raw资源工具类ResourceUtils.java
publicclassResourceUtils{
privateResourceUtils(){
thrownewAssertionError();
}
/**
*getanassetusingACCESS_STREAMINGmode.Thisprovidesaccesstofilesthathavebeenbundledwithan
*applicationasassets--thatis,filesplacedintothe"assets"directory.
*
*@paramcontext
*@paramfileNameThenameoftheassettoopen.Thisnamecanbehierarchical.
*@return
*/
publicstaticStringgeFileFromAssets(Contextcontext,StringfileName){
if(context==null||StringUtils.isEmpty(fileName)){
returnnull;
}
StringBuilders=newStringBuilder("");
try{
InputStreamReaderin=newInputStreamReader(context.getResources().getAssets().open(fileName));
BufferedReaderbr=newBufferedReader(in);
Stringline;
while((line=br.readLine())!=null){
s.append(line);
}
returns.toString();
}catch(IOExceptione){
e.printStackTrace();
returnnull;
}
}
/**
*getcontentfromarawresource.Thiscanonlybeusedwithresourceswhosevalueisthenameofanassetfiles
*--thatis,itcanbeusedtoopendrawable,sound,andrawresources;itwillfailonstringandcolor
*resources.
*
*@paramcontext
*@paramresIdTheresourceidentifiertoopen,asgeneratedbytheappttool.
*@return
*/
publicstaticStringgeFileFromRaw(Contextcontext,intresId){
if(context==null){
returnnull;
}
StringBuilders=newStringBuilder();
try{
InputStreamReaderin=newInputStreamReader(context.getResources().openRawResource(resId));
BufferedReaderbr=newBufferedReader(in);
Stringline;
while((line=br.readLine())!=null){
s.append(line);
}
returns.toString();
}catch(IOExceptione){
e.printStackTrace();
returnnull;
}
}
/**
*sameto{@linkResourceUtils#geFileFromAssets(Context,String)},butreturntypeisList<String>
*
*@paramcontext
*@paramfileName
*@return
*/
publicstaticList<String>geFileToListFromAssets(Contextcontext,StringfileName){
if(context==null||StringUtils.isEmpty(fileName)){
returnnull;
}
List<String>fileContent=newArrayList<String>();
try{
InputStreamReaderin=newInputStreamReader(context.getResources().getAssets().open(fileName));
BufferedReaderbr=newBufferedReader(in);
Stringline;
while((line=br.readLine())!=null){
fileContent.add(line);
}
br.close();
returnfileContent;
}catch(IOExceptione){
e.printStackTrace();
returnnull;
}
}
/**
*sameto{@linkResourceUtils#geFileFromRaw(Context,int)},butreturntypeisList<String>
*
*@paramcontext
*@paramresId
*@return
*/
publicstaticList<String>geFileToListFromRaw(Contextcontext,intresId){
if(context==null){
returnnull;
}
List<String>fileContent=newArrayList<String>();
BufferedReaderreader=null;
try{
InputStreamReaderin=newInputStreamReader(context.getResources().openRawResource(resId));
reader=newBufferedReader(in);
Stringline=null;
while((line=reader.readLine())!=null){
fileContent.add(line);
}
reader.close();
returnfileContent;
}catch(IOExceptione){
e.printStackTrace();
returnnull;
}
}
}
十四、单例工具类SingletonUtils.java
publicabstractclassSingletonUtils<T>{
privateTinstance;
protectedabstractTnewInstance();
publicfinalTgetInstance(){
if(instance==null){
synchronized(SingletonUtils.class){
if(instance==null){
instance=newInstance();
}
}
}
returninstance;
}
}
十五、数据库工具类SqliteUtils.java
publicclassSqliteUtils{
privatestaticvolatileSqliteUtilsinstance;
privateDbHelperdbHelper;
privateSQLiteDatabasedb;
privateSqliteUtils(Contextcontext){
dbHelper=newDbHelper(context);
db=dbHelper.getWritableDatabase();
}
publicstaticSqliteUtilsgetInstance(Contextcontext){
if(instance==null){
synchronized(SqliteUtils.class){
if(instance==null){
instance=newSqliteUtils(context);
}
}
}
returninstance;
}
publicSQLiteDatabasegetDb(){
returndb;
}
}