Android开发中4个常用的工具类【Toast、SharedPreferences、网络及屏幕操作】
本文实例讲述了Android开发中4个常用的工具类。分享给大家供大家参考,具体如下:
1、土司工具类(Toast管理)
/**
*Toast统一管理类
*
*@ProjectApp_ZXing
*@Packagecom.android.scan
*@authorchenlin
*@version1.0
*@Date2013年7月6日
*@NoteTODO
*/
publicclassToastUtil{
privateToastUtil(){
/*cannotbeinstantiated*/
thrownewUnsupportedOperationException("cannotbeinstantiated");
}
publicstaticbooleanisShow=true;
/**
*短时间显示Toast
*
*@paramcontext
*@parammessage
*/
publicstaticvoidshow(Contextcontext,CharSequencemessage){
if(isShow)
Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
}
/**
*短时间显示Toast
*
*@paramcontext
*@parammessage
*/
publicstaticvoidshowShort(Contextcontext,intmessage){
if(isShow)
Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
}
/**
*长时间显示Toast
*
*@paramcontext
*@parammessage
*/
publicstaticvoidshowLong(Contextcontext,CharSequencemessage){
if(isShow)
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
/**
*长时间显示Toast
*
*@paramcontext
*@parammessage
*/
publicstaticvoidshowLong(Contextcontext,intmessage){
if(isShow)
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
/**
*自定义显示Toast时间
*
*@paramcontext
*@parammessage
*@paramduration
*/
publicstaticvoidshow(Contextcontext,CharSequencemessage,intduration){
if(isShow)
Toast.makeText(context,message,duration).show();
}
/**
*自定义显示Toast时间
*
*@paramcontext
*@parammessage
*@paramduration
*/
publicstaticvoidshow(Contextcontext,intmessage,intduration){
if(isShow)
Toast.makeText(context,message,duration).show();
}
}
2、SharedPreferences工具类
/**
*SharedPreferences封装类SPUtils
*@ProjectApp_ZXing
*@Packagecom.android.scan
*@authorchenlin
*@version1.0
*@Date2013年6月6日
*@NoteTODO
*/
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
*/
publicstaticMapgetAll(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();
}
}
}
3、网络工具类
/**
*跟网络相关的工具类
*@ProjectApp_ZXing
*@Packagecom.android.scan
*@authorchenlin
*@version1.0
*@Date2013年6月8日
*@NoteTODO
*/
publicclassNetUtils{
privateNetUtils(){
/*cannotbeinstantiated*/
thrownewUnsupportedOperationException("cannotbeinstantiated");
}
/**
*判断网络是否连接
*
*@paramcontext
*@return
*/
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,0);
}
}
4、获得屏幕相关的辅助类
/**
*获得屏幕相关的辅助类
*@ProjectApp_ZXing
*@Packagecom.android.scan
*@authorchenlin
*@version1.0
*@Date2013年6月6日
*/
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=-1;
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,0,0,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,0,statusBarHeight,width,height-statusBarHeight);
view.destroyDrawingCache();
returnbp;
}
}
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android视图View技巧总结》、《Android编程之activity操作技巧总结》、《Android操作SQLite数据库技巧总结》、《Android操作json格式数据技巧总结》、《Android资源操作技巧汇总》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。