36个Android开发常用经典代码大全
程序员文章站
2024-03-03 20:31:04
本文汇集36个android开发常用经典代码片段,包括拨打电话、发送短信、唤醒屏幕并解锁、是否有网络连接、动态显示或者是隐藏软键盘等,希望对您有所帮助。
//...
本文汇集36个android开发常用经典代码片段,包括拨打电话、发送短信、唤醒屏幕并解锁、是否有网络连接、动态显示或者是隐藏软键盘等,希望对您有所帮助。
//36个android开发常用代码片段 //拨打电话 public static void call(context context, string phonenumber) { context.startactivity( new intent(intent.action_call, uri.parse( "tel:" + phonenumber))); } //跳转至拨号界面 public static void calldial(context context, string phonenumber) { context.startactivity( new intent(intent.action_dial, uri.parse( "tel:" + phonenumber))); } //发送短信 public static void sendsms(context context, string phonenumber, string content) { uri uri = uri.parse( "smsto:" + (textutils.isempty(phonenumber) ? "" : phonenumber)); intent intent = new intent(intent.action_sendto, uri); intent.putextra( "sms_body" , textutils.isempty(content) ? "" : content); context.startactivity(intent); } //唤醒屏幕并解锁 public static void wakeupandunlock(context context){ keyguardmanager km= (keyguardmanager) context.getsystemservice(context.keyguard_service); keyguardmanager.keyguardlock kl = km.newkeyguardlock( "unlock" ); //解锁 kl.disablekeyguard(); //获取电源管理器对象 powermanager pm=(powermanager) context.getsystemservice(context.power_service); //获取powermanager.wakelock对象,后面的参数|表示同时传入两个值,最后的是logcat里用的tag powermanager.wakelock wl = pm.newwakelock(powermanager.acquire_causes_wakeup | powermanager.screen_dim_wake_lock, "bright" ); //点亮屏幕 wl.acquire(); //释放 wl.release(); } //需要添加权限 <uses-permission android:name= "android.permission.wake_lock" /> <uses-permission android:name= "android.permission.disable_keyguard" /> //判断当前app处于前台还是后台状态 public static boolean isapplicationbackground( final context context) { activitymanager am = (activitymanager) context .getsystemservice(context.activity_service); @suppresswarnings ( "deprecation" ) list<activitymanager.runningtaskinfo> tasks = am.getrunningtasks( 1 ); if (!tasks.isempty()) { componentname topactivity = tasks.get( 0 ).topactivity; if (!topactivity.getpackagename().equals(context.getpackagename())) { return true ; } } return false ; } //需要添加权限 <uses-permission android:name= "android.permission.get_tasks" /> //判断当前手机是否处于锁屏(睡眠)状态 public static boolean issleeping(context context) { keyguardmanager kgmgr = (keyguardmanager) context .getsystemservice(context.keyguard_service); boolean issleeping = kgmgr.inkeyguardrestrictedinputmode(); return issleeping; } //判断当前是否有网络连接 public static boolean isonline(context context) { connectivitymanager manager = (connectivitymanager) context .getsystemservice(activity.connectivity_service); networkinfo info = manager.getactivenetworkinfo(); if (info != null && info.isconnected()) { return true ; } return false ; } //判断当前是否是wifi连接状态 public static boolean iswificonnected(context context) { connectivitymanager connectivitymanager = (connectivitymanager) context .getsystemservice(context.connectivity_service); networkinfo wifinetworkinfo = connectivitymanager .getnetworkinfo(connectivitymanager.type_wifi); if (wifinetworkinfo.isconnected()) { return true ; } return false ; } //安装apk public static void installapk(context context, file file) { intent intent = new intent(); intent.setaction( "android.intent.action.view" ); intent.addcategory( "android.intent.category.default" ); intent.settype( "application/vnd.android.package-archive" ); intent.setdataandtype(uri.fromfile(file), "application/vnd.android.package-archive" ); intent.setflags(intent.flag_activity_new_task); context.startactivity(intent); } //判断当前设备是否为手机 public static boolean isphone(context context) { telephonymanager telephony = (telephonymanager) context .getsystemservice(context.telephony_service); if (telephony.getphonetype() == telephonymanager.phone_type_none) { return false ; } else { return true ; } } //获取当前设备宽高,单位px @suppresswarnings ( "deprecation" ) public static int getdevicewidth(context context) { windowmanager manager = (windowmanager) context .getsystemservice(context.window_service); return manager.getdefaultdisplay().getwidth(); } @suppresswarnings ( "deprecation" ) public static int getdeviceheight(context context) { windowmanager manager = (windowmanager) context .getsystemservice(context.window_service); return manager.getdefaultdisplay().getheight(); } //获取当前设备的imei,需要与上面的isphone()一起使用 @targetapi (build.version_codes.cupcake) public static string getdeviceimei(context context) { string deviceid; if (isphone(context)) { telephonymanager telephony = (telephonymanager) context .getsystemservice(context.telephony_service); deviceid = telephony.getdeviceid(); } else { deviceid = settings.secure.getstring(context.getcontentresolver(), settings.secure.android_id); } return deviceid; } //获取当前设备的mac地址 public static string getmacaddress(context context) { string macaddress; wifimanager wifi = (wifimanager) context .getsystemservice(context.wifi_service); wifiinfo info = wifi.getconnectioninfo(); macaddress = info.getmacaddress(); if ( null == macaddress) { return "" ; } macaddress = macaddress.replace( ":" , "" ); return macaddress; } //获取当前程序的版本号 public static string getappversion(context context) { string version = "0" ; try { version = context.getpackagemanager().getpackageinfo( context.getpackagename(), 0 ).versionname; } catch (packagemanager.namenotfoundexception e) { e.printstacktrace(); } return version; } //收集设备信息,用于信息统计分析 public static properties collectdeviceinfo(context context) { properties mdevicecrashinfo = new properties(); try { packagemanager pm = context.getpackagemanager(); packageinfo pi = pm.getpackageinfo(context.getpackagename(), packagemanager.get_activities); if (pi != null ) { mdevicecrashinfo.put(version_name, pi.versionname == null ? "not set" : pi.versionname); mdevicecrashinfo.put(version_code, pi.versioncode); } } catch (packagemanager.namenotfoundexception e) { log.e(tag, "error while collect package info" , e); } field[] fields = build. class .getdeclaredfields(); for (field field : fields) { try { field.setaccessible( true ); mdevicecrashinfo.put(field.getname(), field.get( null )); } catch (exception e) { log.e(tag, "error while collect crash info" , e); } } return mdevicecrashinfo; } public static string collectdeviceinfostr(context context) { properties prop = collectdeviceinfo(context); set deviceinfos = prop.keyset(); stringbuilder deviceinfostr = new stringbuilder( "{\n" ); for (iterator iter = deviceinfos.iterator(); iter.hasnext();) { object item = iter.next(); deviceinfostr.append( "\t\t\t" + item + ":" + prop.get(item) + ", \n" ); } deviceinfostr.append( "}" ); return deviceinfostr.tostring(); } //是否有sd卡 public static boolean havesdcard() { return android.os.environment.getexternalstoragestate().equals( android.os.environment.media_mounted); } //动态隐藏软键盘 @targetapi (build.version_codes.cupcake) public static void hidesoftinput(activity activity) { view view = activity.getwindow().peekdecorview(); if (view != null ) { inputmethodmanager inputmanger = (inputmethodmanager) activity .getsystemservice(context.input_method_service); inputmanger.hidesoftinputfromwindow(view.getwindowtoken(), 0 ); } } @targetapi (build.version_codes.cupcake) public static void hidesoftinput(context context, edittext edit) { edit.clearfocus(); inputmethodmanager inputmanger = (inputmethodmanager) context .getsystemservice(context.input_method_service); inputmanger.hidesoftinputfromwindow(edit.getwindowtoken(), 0 ); } //动态显示软键盘 @targetapi (build.version_codes.cupcake) public static void showsoftinput(context context, edittext edit) { edit.setfocusable( true ); edit.setfocusableintouchmode( true ); edit.requestfocus(); inputmethodmanager inputmanager = (inputmethodmanager) context .getsystemservice(context.input_method_service); inputmanager.showsoftinput(edit, 0 ); } //动态显示或者是隐藏软键盘 @targetapi (build.version_codes.cupcake) public static void togglesoftinput(context context, edittext edit) { edit.setfocusable( true ); edit.setfocusableintouchmode( true ); edit.requestfocus(); inputmethodmanager inputmanager = (inputmethodmanager) context .getsystemservice(context.input_method_service); inputmanager.togglesoftinput(inputmethodmanager.show_forced, 0 ); } //主动回到home,后台运行 public static void gohome(context context) { intent mhomeintent = new intent(intent.action_main); mhomeintent.addcategory(intent.category_home); mhomeintent.addflags(intent.flag_activity_new_task | intent.flag_activity_reset_task_if_needed); context.startactivity(mhomeintent); } //获取状态栏高度 //注意,要在onwindowfocuschanged中调用,在oncreate中获取高度为0 @targetapi (build.version_codes.cupcake) public static int getstatusbarheight(activity activity) { rect frame = new rect(); activity.getwindow().getdecorview().getwindowvisibledisplayframe(frame); return frame.top; } //获取状态栏高度+标题栏(actionbar)高度 //(注意,如果没有actionbar,那么获取的高度将和上面的是一样的,只有状态栏的高度) public static int gettopbarheight(activity activity) { return activity.getwindow().findviewbyid(window.id_android_content) .gettop(); } //获取mcc+mnc代码 (sim卡运营商国家代码和运营商网络代码) //仅当用户已在网络注册时有效, cdma 可能会无效(中国移动:46000 //46002, 中国联通:46001,中国电信:46003) public static string getnetworkoperator(context context) { telephonymanager telephonymanager = (telephonymanager) context .getsystemservice(context.telephony_service); return telephonymanager.getnetworkoperator(); } //返回移动网络运营商的名字 //(例:中国联通、中国移动、中国电信) 仅当用户已在网络注册时有效, //cdma 可能会无效) public static string getnetworkoperatorname(context context) { telephonymanager telephonymanager = (telephonymanager) context .getsystemservice(context.telephony_service); return telephonymanager.getnetworkoperatorname(); } //返回移动终端类型 phone_type_none :0 手机制式未知 phone_type_gsm :1 手机制式为gsm,移动和联通 phone_type_cdma :2 手机制式为cdma,电信 phone_type_sip:3 public static int getphonetype(context context) { telephonymanager telephonymanager = (telephonymanager) context .getsystemservice(context.telephony_service); return telephonymanager.getphonetype(); } //判断手机连接的网络类型(2g,3g,4g) //联通的3g为umts或hsdpa,移动和联通的2g为gprs或egde,电信的2g为cdma,电信的3g为evdo public class constants { /** * unknown network class */ public static final int network_class_unknown = 0 ; /** * wifi net work */ public static final int network_wifi = 1 ; /** * "2g" networks */ public static final int network_class_2_g = 2 ; /** * "3g" networks */ public static final int network_class_3_g = 3 ; /** * "4g" networks */ public static final int network_class_4_g = 4 ; } public static int getnetworkclass(context context) { telephonymanager telephonymanager = (telephonymanager) context .getsystemservice(context.telephony_service); switch (telephonymanager.getnetworktype()) { case telephonymanager.network_type_gprs: case telephonymanager.network_type_edge: case telephonymanager.network_type_cdma: case telephonymanager.network_type_1xrtt: case telephonymanager.network_type_iden: return constants.network_class_2_g; case telephonymanager.network_type_umts: case telephonymanager.network_type_evdo_0: case telephonymanager.network_type_evdo_a: case telephonymanager.network_type_hsdpa: case telephonymanager.network_type_hsupa: case telephonymanager.network_type_hspa: case telephonymanager.network_type_evdo_b: case telephonymanager.network_type_ehrpd: case telephonymanager.network_type_hspap: return constants.network_class_3_g; case telephonymanager.network_type_lte: return constants.network_class_4_g; default : return constants.network_class_unknown; } } //判断当前手机的网络类型(wifi还是2,3,4g) //需要用到上面的方法 public static int getnetworkstatus(context context) { int networktype = constants.network_class_unknown; connectivitymanager connectivitymanager = (connectivitymanager) context .getsystemservice(context.connectivity_service); networkinfo networkinfo = connectivitymanager.getactivenetworkinfo(); if (networkinfo != null && networkinfo.isconnected()) { int type = networkinfo.gettype(); if (type == connectivitymanager.type_wifi) { networktype = constants.network_wifi; } else if (type == connectivitymanager.type_mobile) { networktype = getnetworkclass(context); } } return networktype; } //px-dp转换 public static int dip2px(context context, float dpvalue) { final float scale = context.getresources().getdisplaymetrics().density; return ( int ) (dpvalue * scale + 0 .5f); } public static int px2dip(context context, float pxvalue) { final float scale = context.getresources().getdisplaymetrics().density; return ( int ) (pxvalue / scale + 0 .5f); } //px-sp转换 public static int px2sp(context context, float pxvalue) { final float fontscale = context.getresources().getdisplaymetrics().scaleddensity; return ( int ) (pxvalue / fontscale + 0 .5f); } public static int sp2px(context context, float spvalue) { final float fontscale = context.getresources().getdisplaymetrics().scaleddensity; return ( int ) (spvalue * fontscale + 0 .5f); } //把一个毫秒数转化成时间字符串 //格式为小时/分/秒/毫秒(如:24903600 –> 06小时55分03秒600毫秒) /** * @param millis * 要转化的毫秒数。 * @param iswhole * 是否强制全部显示小时/分/秒/毫秒。 * @param isformat * 时间数字是否要格式化,如果true:少位数前面补全;如果false:少位数前面不补全。 * @return 返回时间字符串:小时/分/秒/毫秒的格式(如:24903600 --> 06小时55分03秒600毫秒)。 */ public static string millistostring( long millis, boolean iswhole, boolean isformat) { string h = "" ; string m = "" ; string s = "" ; string mi = "" ; if (iswhole) { h = isformat ? "00小时" : "0小时" ; m = isformat ? "00分" : "0分" ; s = isformat ? "00秒" : "0秒" ; mi = isformat ? "00毫秒" : "0毫秒" ; } long temp = millis; long hper = 60 * 60 * 1000 ; long mper = 60 * 1000 ; long sper = 1000 ; if (temp / hper > 0 ) { if (isformat) { h = temp / hper < 10 ? "0" + temp / hper : temp / hper + "" ; } else { h = temp / hper + "" ; } h += "小时" ; } temp = temp % hper; if (temp / mper > 0 ) { if (isformat) { m = temp / mper < 10 ? "0" + temp / mper : temp / mper + "" ; } else { m = temp / mper + "" ; } m += "分" ; } temp = temp % mper; if (temp / sper > 0 ) { if (isformat) { s = temp / sper < 10 ? "0" + temp / sper : temp / sper + "" ; } else { s = temp / sper + "" ; } s += "秒" ; } temp = temp % sper; mi = temp + "" ; if (isformat) { if (temp < 100 && temp >= 10 ) { mi = "0" + temp; } if (temp < 10 ) { mi = "00" + temp; } } mi += "毫秒" ; return h + m + s + mi; } 格式为小时/分/秒/毫秒(如:24903600 –> 06小时55分03秒)。 /** * * @param millis * 要转化的毫秒数。 * @param iswhole * 是否强制全部显示小时/分/秒/毫秒。 * @param isformat * 时间数字是否要格式化,如果true:少位数前面补全;如果false:少位数前面不补全。 * @return 返回时间字符串:小时/分/秒/毫秒的格式(如:24903600 --> 06小时55分03秒)。 */ public static string millistostringmiddle( long millis, boolean iswhole, boolean isformat) { return millistostringmiddle(millis, iswhole, isformat, "小时" , "分钟" , "秒" ); } public static string millistostringmiddle( long millis, boolean iswhole, boolean isformat, string hunit, string munit, string sunit) { string h = "" ; string m = "" ; string s = "" ; if (iswhole) { h = isformat ? "00" + hunit : "0" + hunit; m = isformat ? "00" + munit : "0" + munit; s = isformat ? "00" + sunit : "0" + sunit; } long temp = millis; long hper = 60 * 60 * 1000 ; long mper = 60 * 1000 ; long sper = 1000 ; if (temp / hper > 0 ) { if (isformat) { h = temp / hper < 10 ? "0" + temp / hper : temp / hper + "" ; } else { h = temp / hper + "" ; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。