36个Android开发常用经典代码大全
本文汇集36个Android开发常用经典代码片段,包括拨打电话、发送短信、唤醒屏幕并解锁、是否有网络连接、动态显示或者是隐藏软键盘等,希望对您有所帮助。
//36个Android开发常用代码片段
//拨打电话
publicstaticvoidcall(Contextcontext,StringphoneNumber){
context.startActivity(newIntent(Intent.ACTION_CALL,Uri.parse("tel:"+phoneNumber)));
}
//跳转至拨号界面
publicstaticvoidcallDial(Contextcontext,StringphoneNumber){
context.startActivity(newIntent(Intent.ACTION_DIAL,Uri.parse("tel:"+phoneNumber)));
}
//发送短信
publicstaticvoidsendSms(Contextcontext,StringphoneNumber,
Stringcontent){
Uriuri=Uri.parse("smsto:"
+(TextUtils.isEmpty(phoneNumber)?"":phoneNumber));
Intentintent=newIntent(Intent.ACTION_SENDTO,uri);
intent.putExtra("sms_body",TextUtils.isEmpty(content)?"":content);
context.startActivity(intent);
}
//唤醒屏幕并解锁
publicstaticvoidwakeUpAndUnlock(Contextcontext){
KeyguardManagerkm=(KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLockkl=km.newKeyguardLock("unLock");
//解锁
kl.disableKeyguard();
//获取电源管理器对象
PowerManagerpm=(PowerManager)context.getSystemService(Context.POWER_SERVICE);
//获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
PowerManager.WakeLockwl=pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP|PowerManager.SCREEN_DIM_WAKE_LOCK,"bright");
//点亮屏幕
wl.acquire();
//释放
wl.release();
}
//需要添加权限
<uses-permissionandroid:name="android.permission.WAKE_LOCK"/>
<uses-permissionandroid:name="android.permission.DISABLE_KEYGUARD"/>
//判断当前App处于前台还是后台状态
publicstaticbooleanisApplicationBackground(finalContextcontext){
ActivityManageram=(ActivityManager)context
.getSystemService(Context.ACTIVITY_SERVICE);
@SuppressWarnings("deprecation")
List<ActivityManager.RunningTaskInfo>tasks=am.getRunningTasks(1);
if(!tasks.isEmpty()){
ComponentNametopActivity=tasks.get(0).topActivity;
if(!topActivity.getPackageName().equals(context.getPackageName())){
returntrue;
}
}
returnfalse;
}
//需要添加权限
<uses-permission
android:name="android.permission.GET_TASKS"/>
//判断当前手机是否处于锁屏(睡眠)状态
publicstaticbooleanisSleeping(Contextcontext){
KeyguardManagerkgMgr=(KeyguardManager)context
.getSystemService(Context.KEYGUARD_SERVICE);
booleanisSleeping=kgMgr.inKeyguardRestrictedInputMode();
returnisSleeping;
}
//判断当前是否有网络连接
publicstaticbooleanisOnline(Contextcontext){
ConnectivityManagermanager=(ConnectivityManager)context
.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfoinfo=manager.getActiveNetworkInfo();
if(info!=null&&info.isConnected()){
returntrue;
}
returnfalse;
}
//判断当前是否是WIFI连接状态
publicstaticbooleanisWifiConnected(Contextcontext){
ConnectivityManagerconnectivityManager=(ConnectivityManager)context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfowifiNetworkInfo=connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifiNetworkInfo.isConnected()){
returntrue;
}
returnfalse;
}
//安装APK
publicstaticvoidinstallApk(Contextcontext,Filefile){
Intentintent=newIntent();
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);
}
//判断当前设备是否为手机
publicstaticbooleanisPhone(Contextcontext){
TelephonyManagertelephony=(TelephonyManager)context
.getSystemService(Context.TELEPHONY_SERVICE);
if(telephony.getPhoneType()==TelephonyManager.PHONE_TYPE_NONE){
returnfalse;
}else{
returntrue;
}
}
//获取当前设备宽高,单位px
@SuppressWarnings("deprecation")
publicstaticintgetDeviceWidth(Contextcontext){
WindowManagermanager=(WindowManager)context
.getSystemService(Context.WINDOW_SERVICE);
returnmanager.getDefaultDisplay().getWidth();
}
@SuppressWarnings("deprecation")
publicstaticintgetDeviceHeight(Contextcontext){
WindowManagermanager=(WindowManager)context
.getSystemService(Context.WINDOW_SERVICE);
returnmanager.getDefaultDisplay().getHeight();
}
//获取当前设备的IMEI,需要与上面的isPhone()一起使用
@TargetApi(Build.VERSION_CODES.CUPCAKE)
publicstaticStringgetDeviceIMEI(Contextcontext){
StringdeviceId;
if(isPhone(context)){
TelephonyManagertelephony=(TelephonyManager)context
.getSystemService(Context.TELEPHONY_SERVICE);
deviceId=telephony.getDeviceId();
}else{
deviceId=Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ANDROID_ID);
}
returndeviceId;
}
//获取当前设备的MAC地址
publicstaticStringgetMacAddress(Contextcontext){
StringmacAddress;
WifiManagerwifi=(WifiManager)context
.getSystemService(Context.WIFI_SERVICE);
WifiInfoinfo=wifi.getConnectionInfo();
macAddress=info.getMacAddress();
if(null==macAddress){
return"";
}
macAddress=macAddress.replace(":","");
returnmacAddress;
}
//获取当前程序的版本号
publicstaticStringgetAppVersion(Contextcontext){
Stringversion="0";
try{
version=context.getPackageManager().getPackageInfo(
context.getPackageName(),0).versionName;
}catch(PackageManager.NameNotFoundExceptione){
e.printStackTrace();
}
returnversion;
}
//收集设备信息,用于信息统计分析
publicstaticPropertiescollectDeviceInfo(Contextcontext){
PropertiesmDeviceCrashInfo=newProperties();
try{
PackageManagerpm=context.getPackageManager();
PackageInfopi=pm.getPackageInfo(context.getPackageName(),
PackageManager.GET_ACTIVITIES);
if(pi!=null){
mDeviceCrashInfo.put(VERSION_NAME,
pi.versionName==null?"notset":pi.versionName);
mDeviceCrashInfo.put(VERSION_CODE,pi.versionCode);
}
}catch(PackageManager.NameNotFoundExceptione){
Log.e(TAG,"Errorwhilecollectpackageinfo",e);
}
Field[]fields=Build.class.getDeclaredFields();
for(Fieldfield:fields){
try{
field.setAccessible(true);
mDeviceCrashInfo.put(field.getName(),field.get(null));
}catch(Exceptione){
Log.e(TAG,"Errorwhilecollectcrashinfo",e);
}
}
returnmDeviceCrashInfo;
}
publicstaticStringcollectDeviceInfoStr(Contextcontext){
Propertiesprop=collectDeviceInfo(context);
SetdeviceInfos=prop.keySet();
StringBuilderdeviceInfoStr=newStringBuilder("{\n");
for(Iteratoriter=deviceInfos.iterator();iter.hasNext();){
Objectitem=iter.next();
deviceInfoStr.append("\t\t\t"+item+":"+prop.get(item)
+",\n");
}
deviceInfoStr.append("}");
returndeviceInfoStr.toString();
}
//是否有SD卡
publicstaticbooleanhaveSDCard(){
returnandroid.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
//动态隐藏软键盘
@TargetApi(Build.VERSION_CODES.CUPCAKE)
publicstaticvoidhideSoftInput(Activityactivity){
Viewview=activity.getWindow().peekDecorView();
if(view!=null){
InputMethodManagerinputmanger=(InputMethodManager)activity
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputmanger.hideSoftInputFromWindow(view.getWindowToken(),0);
}
}
@TargetApi(Build.VERSION_CODES.CUPCAKE)
publicstaticvoidhideSoftInput(Contextcontext,EditTextedit){
edit.clearFocus();
InputMethodManagerinputmanger=(InputMethodManager)context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputmanger.hideSoftInputFromWindow(edit.getWindowToken(),0);
}
//动态显示软键盘
@TargetApi(Build.VERSION_CODES.CUPCAKE)
publicstaticvoidshowSoftInput(Contextcontext,EditTextedit){
edit.setFocusable(true);
edit.setFocusableInTouchMode(true);
edit.requestFocus();
InputMethodManagerinputManager=(InputMethodManager)context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(edit,0);
}
//动态显示或者是隐藏软键盘
@TargetApi(Build.VERSION_CODES.CUPCAKE)
publicstaticvoidtoggleSoftInput(Contextcontext,EditTextedit){
edit.setFocusable(true);
edit.setFocusableInTouchMode(true);
edit.requestFocus();
InputMethodManagerinputManager=(InputMethodManager)context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
}
//主动回到Home,后台运行
publicstaticvoidgoHome(Contextcontext){
IntentmHomeIntent=newIntent(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)
publicstaticintgetStatusBarHeight(Activityactivity){
Rectframe=newRect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
returnframe.top;
}
//获取状态栏高度+标题栏(ActionBar)高度
//(注意,如果没有ActionBar,那么获取的高度将和上面的是一样的,只有状态栏的高度)
publicstaticintgetTopBarHeight(Activityactivity){
returnactivity.getWindow().findViewById(Window.ID_ANDROID_CONTENT)
.getTop();
}
//获取MCC+MNC代码(SIM卡运营商国家代码和运营商网络代码)
//仅当用户已在网络注册时有效,CDMA可能会无效(中国移动:46000//46002,中国联通:46001,中国电信:46003)
publicstaticStringgetNetworkOperator(Contextcontext){
TelephonyManagertelephonyManager=(TelephonyManager)context
.getSystemService(Context.TELEPHONY_SERVICE);
returntelephonyManager.getNetworkOperator();
}
//返回移动网络运营商的名字
//(例:中国联通、中国移动、中国电信)仅当用户已在网络注册时有效,//CDMA可能会无效)
publicstaticStringgetNetworkOperatorName(Contextcontext){
TelephonyManagertelephonyManager=(TelephonyManager)context
.getSystemService(Context.TELEPHONY_SERVICE);
returntelephonyManager.getNetworkOperatorName();
}
//返回移动终端类型
PHONE_TYPE_NONE:0手机制式未知
PHONE_TYPE_GSM:1手机制式为GSM,移动和联通
PHONE_TYPE_CDMA:2手机制式为CDMA,电信
PHONE_TYPE_SIP:3
publicstaticintgetPhoneType(Contextcontext){
TelephonyManagertelephonyManager=(TelephonyManager)context
.getSystemService(Context.TELEPHONY_SERVICE);
returntelephonyManager.getPhoneType();
}
//判断手机连接的网络类型(2G,3G,4G)
//联通的3G为UMTS或HSDPA,移动和联通的2G为GPRS或EGDE,电信的2G为CDMA,电信的3G为EVDO
publicclassConstants{
/**
*Unknownnetworkclass
*/
publicstaticfinalintNETWORK_CLASS_UNKNOWN=0;
/**
*wifinetwork
*/
publicstaticfinalintNETWORK_WIFI=1;
/**
*"2G"networks
*/
publicstaticfinalintNETWORK_CLASS_2_G=2;
/**
*"3G"networks
*/
publicstaticfinalintNETWORK_CLASS_3_G=3;
/**
*"4G"networks
*/
publicstaticfinalintNETWORK_CLASS_4_G=4;
}
publicstaticintgetNetWorkClass(Contextcontext){
TelephonyManagertelephonyManager=(TelephonyManager)context
.getSystemService(Context.TELEPHONY_SERVICE);
switch(telephonyManager.getNetworkType()){
caseTelephonyManager.NETWORK_TYPE_GPRS:
caseTelephonyManager.NETWORK_TYPE_EDGE:
caseTelephonyManager.NETWORK_TYPE_CDMA:
caseTelephonyManager.NETWORK_TYPE_1xRTT:
caseTelephonyManager.NETWORK_TYPE_IDEN:
returnConstants.NETWORK_CLASS_2_G;
caseTelephonyManager.NETWORK_TYPE_UMTS:
caseTelephonyManager.NETWORK_TYPE_EVDO_0:
caseTelephonyManager.NETWORK_TYPE_EVDO_A:
caseTelephonyManager.NETWORK_TYPE_HSDPA:
caseTelephonyManager.NETWORK_TYPE_HSUPA:
caseTelephonyManager.NETWORK_TYPE_HSPA:
caseTelephonyManager.NETWORK_TYPE_EVDO_B:
caseTelephonyManager.NETWORK_TYPE_EHRPD:
caseTelephonyManager.NETWORK_TYPE_HSPAP:
returnConstants.NETWORK_CLASS_3_G;
caseTelephonyManager.NETWORK_TYPE_LTE:
returnConstants.NETWORK_CLASS_4_G;
default:
returnConstants.NETWORK_CLASS_UNKNOWN;
}
}
//判断当前手机的网络类型(WIFI还是2,3,4G)
//需要用到上面的方法
publicstaticintgetNetWorkStatus(Contextcontext){
intnetWorkType=Constants.NETWORK_CLASS_UNKNOWN;
ConnectivityManagerconnectivityManager=(ConnectivityManager)context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfonetworkInfo=connectivityManager.getActiveNetworkInfo();
if(networkInfo!=null&&networkInfo.isConnected()){
inttype=networkInfo.getType();
if(type==ConnectivityManager.TYPE_WIFI){
netWorkType=Constants.NETWORK_WIFI;
}elseif(type==ConnectivityManager.TYPE_MOBILE){
netWorkType=getNetWorkClass(context);
}
}
returnnetWorkType;
}
//px-dp转换
publicstaticintdip2px(Contextcontext,floatdpValue){
finalfloatscale=context.getResources().getDisplayMetrics().density;
return(int)(dpValue*scale+0.5f);
}
publicstaticintpx2dip(Contextcontext,floatpxValue){
finalfloatscale=context.getResources().getDisplayMetrics().density;
return(int)(pxValue/scale+0.5f);
}
//px-sp转换
publicstaticintpx2sp(Contextcontext,floatpxValue){
finalfloatfontScale=context.getResources().getDisplayMetrics().scaledDensity;
return(int)(pxValue/fontScale+0.5f);
}
publicstaticintsp2px(Contextcontext,floatspValue){
finalfloatfontScale=context.getResources().getDisplayMetrics().scaledDensity;
return(int)(spValue*fontScale+0.5f);
}
//把一个毫秒数转化成时间字符串
//格式为小时/分/秒/毫秒(如:24903600–>06小时55分03秒600毫秒)
/**
*@parammillis
*要转化的毫秒数。
*@paramisWhole
*是否强制全部显示小时/分/秒/毫秒。
*@paramisFormat
*时间数字是否要格式化,如果true:少位数前面补全;如果false:少位数前面不补全。
*@return返回时间字符串:小时/分/秒/毫秒的格式(如:24903600-->06小时55分03秒600毫秒)。
*/
publicstaticStringmillisToString(longmillis,booleanisWhole,
booleanisFormat){
Stringh="";
Stringm="";
Strings="";
Stringmi="";
if(isWhole){
h=isFormat?"00小时":"0小时";
m=isFormat?"00分":"0分";
s=isFormat?"00秒":"0秒";
mi=isFormat?"00毫秒":"0毫秒";
}
longtemp=millis;
longhper=60*60*1000;
longmper=60*1000;
longsper=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+="毫秒";
returnh+m+s+mi;
}
格式为小时/分/秒/毫秒(如:24903600–>06小时55分03秒)。
/**
*
*@parammillis
*要转化的毫秒数。
*@paramisWhole
*是否强制全部显示小时/分/秒/毫秒。
*@paramisFormat
*时间数字是否要格式化,如果true:少位数前面补全;如果false:少位数前面不补全。
*@return返回时间字符串:小时/分/秒/毫秒的格式(如:24903600-->06小时55分03秒)。
*/
publicstaticStringmillisToStringMiddle(longmillis,booleanisWhole,
booleanisFormat){
returnmillisToStringMiddle(millis,isWhole,isFormat,"小时","分钟","秒");
}
publicstaticStringmillisToStringMiddle(longmillis,booleanisWhole,
booleanisFormat,StringhUnit,StringmUnit,StringsUnit){
Stringh="";
Stringm="";
Strings="";
if(isWhole){
h=isFormat?"00"+hUnit:"0"+hUnit;
m=isFormat?"00"+mUnit:"0"+mUnit;
s=isFormat?"00"+sUnit:"0"+sUnit;
}
longtemp=millis;
longhper=60*60*1000;
longmper=60*1000;
longsper=1000;
if(temp/hper>0){
if(isFormat){
h=temp/hper<10?"0"+temp/hper:temp/hper+"";
}else{
h=temp/hper+"";
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。