一些常用的android工具类及使用方法介绍
程序员文章站
2022-05-02 23:03:25
本篇文章为大家分享一些常用的android工具类,通过这些工具类可以更加方便高效,提高大家的工作效率,如果大家看了这篇文章,觉得有什么不足或是其他的一些工具方法,欢迎在评论提出
第一个工具类封装了s...
本篇文章为大家分享一些常用的android工具类,通过这些工具类可以更加方便高效,提高大家的工作效率,如果大家看了这篇文章,觉得有什么不足或是其他的一些工具方法,欢迎在评论提出
第一个工具类封装了sharedpreferences,代码和具体的使用方法如下所示
public class sharedpreferencesutils { /** * 保存在手机里面的文件名 */ private static final string file_name = "share_date"; /** * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 * @param context * @param key * @param object */ public static void setparam(context context , string key, object object){ string type = object.getclass().getsimplename(); sharedpreferences sp = context.getsharedpreferences(file_name, context.mode_private); sharedpreferences.editor editor = sp.edit(); if("string".equals(type)){ editor.putstring(key, (string)object); } else if("integer".equals(type)){ editor.putint(key, (integer)object); } else if("boolean".equals(type)){ editor.putboolean(key, (boolean)object); } else if("float".equals(type)){ editor.putfloat(key, (float)object); } else if("long".equals(type)){ editor.putlong(key, (long)object); } editor.commit(); } /** * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 * @param context * @param key * @param defaultobject * @return */ public static object getparam(context context , string key, object defaultobject){ string type = defaultobject.getclass().getsimplename(); sharedpreferences sp = context.getsharedpreferences(file_name, context.mode_private); if("string".equals(type)){ return sp.getstring(key, (string)defaultobject); } else if("integer".equals(type)){ return sp.getint(key, (integer)defaultobject); } else if("boolean".equals(type)){ return sp.getboolean(key, (boolean)defaultobject); } else if("float".equals(type)){ return sp.getfloat(key, (float)defaultobject); } else if("long".equals(type)){ return sp.getlong(key, (long)defaultobject); } return null; } }
使用方法如下
保存一个string数据:sharedpreferencesutils.setparam(mcontext, "fruit", "apple");
获取数据:sharedpreferencesutils.getparam(mcontext, "fruit", "");
第二个工具类是一个单位转换工具类,如下
public class displayutils { /** * convert px to its equivalent dp * * 将px转换为与之相等的dp */ public static int px2dp(context context, float pxvalue) { final float scale = context.getresources().getdisplaymetrics().density; return (int) (pxvalue / scale + 0.5f); } /** * convert dp to its equivalent px * * 将dp转换为与之相等的px */ public static int dp2px(context context, float dipvalue) { final float scale = context.getresources().getdisplaymetrics().density; return (int) (dipvalue * scale + 0.5f); } /** * convert px to its equivalent sp * * 将px转换为sp */ public static int px2sp(context context, float pxvalue) { final float fontscale = context.getresources().getdisplaymetrics().scaleddensity; return (int) (pxvalue / fontscale + 0.5f); } /** * convert sp to its equivalent px * * 将sp转换为px */ public static int sp2px(context context, float spvalue) { final float fontscale = context.getresources().getdisplaymetrics().scaleddensity; return (int) (spvalue * fontscale + 0.5f); } }
第三个方法是一个获取app信息工具类,代码如下
import java.util.arraylist; import java.util.list; import android.content.pm.launcheractivityinfo; import android.content.pm.launcherapps; import android.os.userhandle; import com.magcomm.datausage.mainactivity; public class appinfoutils { private appinfoutils() { /* cannot be instantiated */ throw new unsupportedoperationexception("cannot be instantiated"); } /** * 获取应用程序名称 * * @param context * @return */ public static string getappname(context context) { try { packagemanager packagemanager = context.getpackagemanager(); packageinfo packageinfo = packagemanager.getpackageinfo( context.getpackagename(), 0); int labelres = packageinfo.applicationinfo.labelres; return context.getresources().getstring(labelres); } catch (namenotfoundexception e) { e.printstacktrace(); } return null; } /** * 获取应用程序版本名称信息 * * @param context * [url=home.php?mod=space&uid=309376]@return[/url] 当前应用的版本名称 */ public static string getversionname(context context) { try { packagemanager packagemanager = context.getpackagemanager(); packageinfo packageinfo = packagemanager.getpackageinfo( context.getpackagename(), 0); return packageinfo.versionname; } catch (namenotfoundexception e) { e.printstacktrace(); } return null; } /** * 获取application节点下的meta信息 * * @param context * @param params * 想要获取的参数 * @return */ public static string getmetainfo(context context, string params) { string packagename = context.getpackagename(); // 获取application里面的meta信息 try { applicationinfo appinfo = context.getpackagemanager() .getapplicationinfo(packagename, packagemanager.get_meta_data); return appinfo.metadata.getstring(params); } catch (exception e) { system.out.println("获取渠道失败:" + e); e.printstacktrace(); } return null; } /** * 获取启动activity的intent * * @param context * @return */ public static intent getlaunchintent(context context) { string packagename = context.getpackagename(); packagemanager pm = context.getpackagemanager(); intent intent = pm.getlaunchintentforpackage(packagename); return intent; } public static list getlauncherapppackagename(context context){ launcherapps apps = (launcherapps)context.getsystemservice("launcherapps"); userhandle muserhandle = android.os.process.myuserhandle(); list activityinfos = apps.getactivitylist(null, muserhandle); list launcherpackagenameslist = new arraylist(); for (launcheractivityinfo activityinfo : activityinfos) { string name = activityinfo.getapplicationinfo().packagename; launcherpackagenameslist.add(name); } return launcherpackagenameslist; } }
获取当前手机的相关信息
public class phoneinfoutils { private context context; private string deviceid; private string imei; private string imsi; private string manufacture; private string model; private int screenwidth; private int screenheight; private string version_release; private string phonenumber; public phoneinfoutils(context context) { this.context = context; } public void getphoneinfo() { telephonymanager tm = (telephonymanager) context .getsystemservice(context.telephony_service); deviceid = settings.secure.getstring(context.getcontentresolver(), settings.secure.android_id); imsi = tm.getsubscriberid(); imei = tm.getdeviceid(); // 手机制造商 manufacture = build.manufacturer; model = build.model; // 手机型号 displaymetrics dm = context.getresources().getdisplaymetrics(); screenwidth = dm.widthpixels; screenheight = dm.heightpixels; version_release = build.version.release; // 系统版本号 phonenumber = tm.getline1number(); // 获取手机号码 } @override public string tostring() { return "phoneinfoutils [deviceid=" + deviceid + ", imei=" + imei + ", imsi=" + imsi + ", manufacture=" + manufacture + ", model=" + model + ", screenwidth=" + screenwidth + ", screenheight=" + screenheight + ", version_release=" + version_release + ", phonenumber=" + phonenumber + "]"; } }
toast显示工具类
public class t { private final static boolean isshow = true; private t(){ throw new unsupportedoperationexception("t cannot be instantiated"); } public static void showshort(context context,charsequence text) { if(isshow)toast.maketext(context,text,toast.length_short).show(); } public static void showlong(context context,charsequence text) { if(isshow)toast.maketext(context,text,toast.length_long).show(); } }
跟网络相关的工具类
public class networkutil { private networkutil() { throw new unsupportedoperationexception("networkutil cannot be instantiated"); } /** * 判断网络是否连接 * */ 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 connectivity = (connectivitymanager) context.getsystemservice(context.connectivity_service); if (connectivity == null) return false; return connectivity.getactivenetworkinfo().gettype() == connectivitymanager.type_wifi; } /** * 打开网络设置界面 */ public static void opensetting(activity activity) { intent intent = new intent("/"); componentname componentname = new componentname("com.android.settings","com.android.settings.wirelesssettings"); intent.setcomponent(componentname); intent.setaction("android.intent.action.view"); activity.startactivityforresult(intent, 0); } /** * 使用ssl不信任的证书 */ public static void useuntrustedcertificate() { // create a trust manager that does not validate certificate chains trustmanager[] trustallcerts = new trustmanager[]{ new x509trustmanager() { public java.security.cert.x509certificate[] getacceptedissuers() { return null; } public void checkclienttrusted( java.security.cert.x509certificate[] certs, string authtype) { } public void checkservertrusted( java.security.cert.x509certificate[] certs, string authtype) { } } }; // install the all-trusting trust manager try { sslcontext sc = sslcontext.getinstance("ssl"); sc.init(null, trustallcerts, new java.security.securerandom()); httpsurlconnection.setdefaultsslsocketfactory(sc.getsocketfactory()); } catch (exception e) { e.printstacktrace(); } } }
log的统一管理工具类
public class l { private l() { /* cannot be instantiated */ throw new unsupportedoperationexception("cannot be instantiated"); } public static boolean isdebug = true;// 是否需要打印bug,可以在application的oncreate函数里面初始化 private static final string tag = "mytag"; // 下面四个是默认tag的函数 public static void i(string msg) { if (isdebug) log.i(tag, msg); } public static void d(string msg) { if (isdebug) log.d(tag, msg); } public static void e(string msg) { if (isdebug) log.e(tag, msg); } public static void v(string msg) { if (isdebug) log.v(tag, msg); } // 下面是传入自定义tag的函数 public static void i(string tag, string msg) { if (isdebug) log.i(tag, msg); } public static void d(string tag, string msg) { if (isdebug) log.i(tag, msg); } public static void e(string tag, string msg) { if (isdebug) log.i(tag, msg); } public static void v(string tag, string msg) { if (isdebug) log.i(tag, msg); } }
sd卡存储相关工具类
public class sdcardutils { private sdcardutils() { /* cannot be instantiated */ throw new unsupportedoperationexception("cannot be instantiated"); } /** * 判断sdcard是否可用 * * @return */ public static boolean issdcardenable() { return environment.getexternalstoragestate().equals( environment.media_mounted); } /** * 获取sd卡路径 * * @return */ public static string getsdcardpath() { return environment.getexternalstoragedirectory().getabsolutepath() + file.separator; } /** * 获取sd卡的剩余容量 单位byte * * @return */ public static long getsdcardallsize() { if (issdcardenable()) { statfs stat = new statfs(getsdcardpath()); // 获取空闲的数据块的数量 long availableblocks = (long) stat.getavailableblocks() - 4; // 获取单个数据块的大小(byte) long freeblocks = stat.getavailableblocks(); return freeblocks * availableblocks; } return 0; } /** * 获取指定路径所在空间的剩余可用容量字节数,单位byte * * @param filepath * @return 容量字节 sdcard可用空间,内部存储可用空间 */ public static long getfreebytes(string filepath) { // 如果是sd卡的下的路径,则获取sd卡可用容量 if (filepath.startswith(getsdcardpath())) { filepath = getsdcardpath(); } else {// 如果是内部存储的路径,则获取内存存储的可用容量 filepath = environment.getdatadirectory().getabsolutepath(); } statfs stat = new statfs(filepath); long availableblocks = (long) stat.getavailableblocks() - 4; return stat.getblocksize() * availableblocks; } /** * 获取系统存储路径 * * @return */ public static string getrootdirectorypath() { return environment.getrootdirectory().getabsolutepath(); } /** * 获取sd卡空余存储 * * @return */ public string getsdcardstorage() { return formetfilesize(getsdcardallsize()); } /** * 获得sd卡总存储 * * @return */ private string getsdtotalsize() { file path = environment.getexternalstoragedirectory(); statfs stat = new statfs(path.getpath()); long blocksize = stat.getblocksize(); long totalblocks = stat.getblockcount(); return formetfilesize(blocksize * totalblocks); } /** * 转换文件大小 * * @param blocksize * @return */ public string formetfilesize(long blocksize) { decimalformat df = new decimalformat("#.00"); string blocksizestring = ""; if (blocksize < 1024) { blocksizestring = df.format((double) blocksize) + "b"; } else if (blocksize < 1048576) { blocksizestring = df.format((double) blocksize / 1024) + "k"; } else if (blocksize < 1073741824) { blocksizestring = df.format((double) blocksize / 1048576) + "m"; } else { blocksizestring = df.format((double) blocksize / 1073741824) + "g"; } return blocksizestring; } }文章中的大部分的工具类都是从网上收集而来,做了一些筛选,保留了一些平常大多能用到的工具类,后续发现有其它的好的工具方法,会补充上来
上一篇: python中文件操作的其他方法
下一篇: oracle增加日志组和日志文件的代码
推荐阅读
-
Android开发实现的获取sdcard大小及内存大小工具类
-
Android开发中4个常用的工具类【Toast、SharedPreferences、网络及屏幕操作】
-
mysql数据库表的创建以及字段的增删改查操作及一些常用的查询命令介绍
-
基于StringUtils工具类的常用方法介绍(必看篇)
-
一些常用的android工具类及使用方法介绍
-
Android开发中常用到的工具类整理
-
cdr图纸及螺纹工具的使用方法介绍
-
SQLite数据库常用语句及MAC上的SQLite可视化工具MeasSQLlite使用方法
-
超详细的Android开发调试工具ADB命令及安装介绍
-
mysql数据库表的创建以及字段的增删改查操作及一些常用的查询命令介绍