摘要常用code片段
来源:互联网 发布:新还珠格格知乎 编辑:程序博客网 时间:2024/05/21 17:31
显示规则
1分钟以内:刚刚
1小时以内:N分钟前
24小时内:N小时前
7天内:N天前
7天以外当年以内:N月N日
超出一年:N年N月N日
public static String getDanceCircleShowTime(long date) {
String retTime = null;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date);
long curMil = System.currentTimeMillis();
if (curMil < date) {
//这种情况是非法时间,服务器时间比手机的晚
if (date - curMil < Constants.MINUTE_MILLIS) {
retTime = "刚刚";
} else {
if (date - curMil < Constants.DAY_MILLIS) {
retTime = "今天";
} else {
retTime = getMonthDay(date);
}
}
} else {
long deltaMillis = curMil - date;
Calendar curCal = Calendar.getInstance();
curCal.setTimeInMillis(curMil);
int curD1 = curCal.get(Calendar.DAY_OF_YEAR);
int dataD2 = cal.get(Calendar.DAY_OF_YEAR);
int dDay = curD1 - dataD2;
int curYear = curCal.get(Calendar.YEAR);
int year = cal.get(Calendar.YEAR);
if(curYear == year){
if(dDay == 0){
if (deltaMillis < Constants.MINUTE_MILLIS) {
retTime = "刚刚";
} else if (deltaMillis < Constants.HOUR_MILLIS) {
//1小时以内
long minute = deltaMillis / Constants.MINUTE_MILLIS;
retTime = minute + "分钟前";
} else if (deltaMillis < Constants.DAY_MILLIS) {
//1天以内
long hour = deltaMillis / Constants.HOUR_MILLIS;
retTime = hour + "小时前";
}
}else{
if (dDay < 7 ) {
//7天以内
retTime = dDay + "天前";
} else {
//同年
retTime = getMonthDay(date);
}
}
}else{
//不同年
retTime = getYearMonthDay(date);
}
}
return retTime;
}
1分钟以内:刚刚
1小时以内:N分钟前
24小时内:N小时前
7天内:N天前
7天以外当年以内:N月N日
超出一年:N年N月N日
public static String getDanceCircleShowTime(long date) {
String retTime = null;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date);
long curMil = System.currentTimeMillis();
if (curMil < date) {
//这种情况是非法时间,服务器时间比手机的晚
if (date - curMil < Constants.MINUTE_MILLIS) {
retTime = "刚刚";
} else {
if (date - curMil < Constants.DAY_MILLIS) {
retTime = "今天";
} else {
retTime = getMonthDay(date);
}
}
} else {
long deltaMillis = curMil - date;
Calendar curCal = Calendar.getInstance();
curCal.setTimeInMillis(curMil);
int curD1 = curCal.get(Calendar.DAY_OF_YEAR);
int dataD2 = cal.get(Calendar.DAY_OF_YEAR);
int dDay = curD1 - dataD2;
int curYear = curCal.get(Calendar.YEAR);
int year = cal.get(Calendar.YEAR);
if(curYear == year){
if(dDay == 0){
if (deltaMillis < Constants.MINUTE_MILLIS) {
retTime = "刚刚";
} else if (deltaMillis < Constants.HOUR_MILLIS) {
//1小时以内
long minute = deltaMillis / Constants.MINUTE_MILLIS;
retTime = minute + "分钟前";
} else if (deltaMillis < Constants.DAY_MILLIS) {
//1天以内
long hour = deltaMillis / Constants.HOUR_MILLIS;
retTime = hour + "小时前";
}
}else{
if (dDay < 7 ) {
//7天以内
retTime = dDay + "天前";
} else {
//同年
retTime = getMonthDay(date);
}
}
}else{
//不同年
retTime = getYearMonthDay(date);
}
}
return retTime;
}
系统
安装APK
public
void
installApk(Context context, String strFileAllName) {
File file =
new
File(strFileAllName);
Intent intent =
new
Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
String type =
"application/vnd.android.package-archive"
;
intent.setDataAndType(Uri.fromFile(file), type);
context.startActivity(intent);
}
卸载APK
public
void
UninstallApk(Context context, String strPackageName) {
Uri packageURI = Uri.parse(
"package:"
+ strPackageName);
Intent uninstallIntent =
new
Intent(Intent.ACTION_DELETE, packageURI);
context.startActivity(uninstallIntent);
}
判断是否APK是否安装过
public
boolean
checkApkExist(Context context, String packageName) {
if
(packageName ==
null
||
""
.equals(packageName))
return
false
;
try
{
ApplicationInfo info = context.getPackageManager()
.getApplicationInfo(packageName,
PackageManager.GET_UNINSTALLED_PACKAGES);
return
true
;
}
catch
(NameNotFoundException e) {
return
false
;
}
catch
(NullPointerException e) {
return
false
;
}
}
根据包名打开一个应用程序
public
boolean
openApp(String packageName) {
PackageInfo pi =
null
;
try
{
pi = mPM.getPackageInfo(packageName,
0
);
}
catch
(NameNotFoundException e) {
e.printStackTrace();
return
false
;
}
if
(pi ==
null
) {
return
false
;
}
Intent resolveIntent =
new
Intent(Intent.ACTION_MAIN,
null
);
resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resolveIntent.setPackage(pi.packageName);
List<ResolveInfo> apps = mPM.queryIntentActivities(resolveIntent,
0
);
ResolveInfo ri =
null
;
try
{
ri = apps.iterator().next();
}
catch
(Exception e) {
return
true
;
}
if
(ri !=
null
) {
String tmpPackageName = ri.activityInfo.packageName;
String className = ri.activityInfo.name;
Intent intent =
new
Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn =
new
ComponentName(tmpPackageName, className);
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MarketApplication.getMarketApplicationContext().startActivity(
intent);
}
else
{
return
false
;
}
return
true
;
}
图片
保存图片到SD卡public
void
saveBitmapToFile(String url, String filePath) {
File iconFile =
new
File(filePath);
if
(!iconFile.getParentFile().exists()) {
iconFile.getParentFile().mkdirs();
}
if
(iconFile.exists() && iconFile.length() >
0
) {
return
;
}
FileOutputStream fos =
null
;
InputStream is =
null
;
try
{
fos =
new
FileOutputStream(filePath);
is =
new
URL(url).openStream();
int
data = is.read();
while
(data != -
1
) {
fos.write(data);
data = is.read();
}
}
catch
(IOException e) {
e.printStackTrace();
}
finally
{
try
{
if
(is !=
null
) {
is.close();
}
if
(fos !=
null
) {
fos.close();
}
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
public
Bitmap loadBitmap(Resources res,
int
id) {
BitmapFactory.Options opt =
new
BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable =
true
;
opt.inInputShareable =
true
;
InputStream is = res.openRawResource(id);
// 获取资源图片
return
BitmapFactory.decodeStream(is,
null
, opt);
}
bitmap转Byte数组
public
byte
[] bmpToByteArray(
final
Bitmap bmp,
final
boolean
needRecycle) {
ByteArrayOutputStream output =
new
ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG,
100
, output);
if
(needRecycle) {
bmp.recycle();
}
byte
[] result = output.toByteArray();
try
{
output.close();
}
catch
(Exception e) {
e.printStackTrace();
}
return
result;
}
获取下载文件的真实名字
public
String getReallyFileName(String url) {
StrictMode.setThreadPolicy(
new
StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
// 这里可以替换为detectAll()
// 就包括了磁盘读写和网络I/O
.penaltyLog()
// 打印logcat,当然也可以定位到dropbox,通过文件保存相应的log
.build());
StrictMode.setVmPolicy(
new
StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
// 探测SQLite数据库操作
.penaltyLog()
// 打印logcat
.penaltyDeath().build());
String filename =
""
;
URL myURL;
HttpURLConnection conn =
null
;
if
(url ==
null
|| url.length() <
1
) {
return
null
;
}
try
{
myURL =
new
URL(url);
conn = (HttpURLConnection) myURL.openConnection();
conn.connect();
conn.getResponseCode();
URL absUrl = conn.getURL();
// 获得真实Url
// 打印输出服务器Header信息
// Map<String, List<String>> map = conn.getHeaderFields();
// for (String str : map.keySet()) {
// if (str != null) {
// Log.e("H3c", str + map.get(str));
// }
// }
filename = conn.getHeaderField(
"Content-Disposition"
);
// 通过Content-Disposition获取文件名,这点跟服务器有关,需要灵活变通
if
(filename ==
null
|| filename.length() <
1
) {
filename = URLDecoder.decode(absUrl.getFile(),
"UTF-8"
);
}
}
catch
(MalformedURLException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
finally
{
if
(conn !=
null
) {
conn.disconnect();
conn =
null
;
}
}
return
filename;
}
网络
/**
* 网络是否可用
*
* @param context
* @return
*/
public
static
boolean
isNetworkAvailable(Context context) {
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info = mgr.getAllNetworkInfo();
if
(info !=
null
) {
for
(
int
i =
0
; i < info.length; i++) {
if
(info[i].getState() == NetworkInfo.State.CONNECTED) {
return
true
;
}
}
}
return
false
;
}
/*
* 判断网络连接是否已开 2012-08-20true 已打开 false 未打开
*/
public
static
boolean
isConn(Context context) {
boolean
bisConnFlag =
false
;
ConnectivityManager conManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = conManager.getActiveNetworkInfo();
if
(network !=
null
) {
bisConnFlag = conManager.getActiveNetworkInfo().isAvailable();
}
return
bisConnFlag;
}
判断是不是Wifi连接
public
static
boolean
isWifiActive(Context icontext) {
Context context = icontext.getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info;
if
(connectivity !=
null
) {
info = connectivity.getAllNetworkInfo();
if
(info !=
null
) {
for
(
int
i =
0
; i < info.length; i++) {
if
(info[i].getTypeName().equals(
"WIFI"
)
&& info[i].isConnected()) {
return
true
;
}
}
}
}
return
false
;
}
判断当前网络类型
/**
* 网络方式检查
*/
private
static
int
netCheck(Context context) {
ConnectivityManager conMan = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState();
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
if
(wifi.equals(State.CONNECTED)) {
return
DO_WIFI;
}
else
if
(mobile.equals(State.CONNECTED)) {
return
DO_3G;
}
else
{
return
NO_CONNECTION;
}
}
获取当前窗体,并添加自定义view
getWindowManager()
.addView(overlay,
new
WindowManager.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT));
dip转px
public
int
convertDipOrPx(
int
dip) {
float
scale = MarketApplication.getMarketApplicationContext()
.getResources().getDisplayMetrics().density;
return
(
int
) (dip * scale +
0
.5f * (dip >=
0
?
1
: -
1
));
}
判断SD卡是否可用
public
boolean
CheckSD() {
if
(android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
return
true
;
}
else
{
return
false
;
}
}
过滤特殊字符
private
String StringFilter(String str)
throws
PatternSyntaxException {
// 只允许字母和数字
// String regEx = "[^a-zA-Z0-9]";
// 清除掉所有特殊字符
String regEx =
"[`~!@#$%^&*()+=|{}':;',//[//].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]"
;
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return
m.replaceAll(
""
).trim();
}
获得文件MD5值
public
String getFileMD5(File file) {
if
(!file.isFile()) {
return
null
;
}
MessageDigest digest =
null
;
FileInputStream in =
null
;
byte
buffer[] =
new
byte
[
1024
];
int
len;
try
{
digest = MessageDigest.getInstance(
"MD5"
);
in =
new
FileInputStream(file);
while
((len = in.read(buffer,
0
,
1024
)) != -
1
) {
digest.update(buffer,
0
, len);
}
}
catch
(Exception e) {
e.printStackTrace();
return
null
;
}
finally
{
if
(in !=
null
) {
try
{
in.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
BigInteger bigInt =
new
BigInteger(
1
, digest.digest());
return
bigInt.toString(
16
);
}
拨打电话
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
;
}
判断当前设备是否为手机
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);
}
获取状态栏高度
@TargetApi
(Build.VERSION_CODES.CUPCAKE)
public
static
int
getStatusBarHeight(Activity activity) {
Rect frame =
new
Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
return
frame.top;
}
获取状态栏高度+标题栏(ActionBar)高度
public
static
int
getTopBarHeight(Activity activity) {
return
activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT)
.getTop();
}
获取MCC+MNC代码 (SIM卡运营商国家代码和运营商网络代码
public
static
String getNetworkOperator(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return
telephonyManager.getNetworkOperator();
}
返回移动网络运营商的名字
public
static
String getNetworkOperatorName(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return
telephonyManager.getNetworkOperatorName();
}
返回移动终端类型
public
static
int
getPhoneType(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return
telephonyManager.getPhoneType();
}
- PHONE_TYPE_NONE :0 手机制式未知
- PHONE_TYPE_GSM :1 手机制式为GSM,移动和联通
- PHONE_TYPE_CDMA :2 手机制式为CDMA,电信
- PHONE_TYPE_SIP:3
判断手机连接的网络类型(2G,3G,4G)
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);
}
把一个毫秒数转化成时间字符串
/**
* @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 +
""
;
}
h += hUnit;
}
temp = temp % hper;
if
(temp / mper >
0
) {
if
(isFormat) {
m = temp / mper <
10
?
"0"
+ temp / mper : temp / mper +
""
;
}
else
{
m = temp / mper +
""
;
}
m += mUnit;
}
temp = temp % mper;
if
(temp / sper >
0
) {
if
(isFormat) {
s = temp / sper <
10
?
"0"
+ temp / sper : temp / sper +
""
;
}
else
{
s = temp / sper +
""
;
}
s += sUnit;
}
return
h + m + s;
}
把一个毫秒数转化成时间字符串。格式为小时/分/秒/毫秒(如:24903600 –> 06小时55分钟)
/**
*
* @param millis
* 要转化的毫秒数。
* @param isWhole
* 是否强制全部显示小时/分。
* @param isFormat
* 时间数字是否要格式化,如果true:少位数前面补全;如果false:少位数前面不补全。
* @return 返回时间字符串:小时/分/秒/毫秒的格式(如:24903600 --> 06小时55分钟)。
*/
public
static
String millisToStringShort(
long
millis,
boolean
isWhole,
boolean
isFormat) {
String h =
""
;
String m =
""
;
if
(isWhole) {
h = isFormat ?
"00小时"
:
"0小时"
;
m = 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 +=
"分钟"
;
}
return
h + m;
}
把日期毫秒转化为字符串
/**
* @param millis
* 要转化的日期毫秒数。
* @param pattern
* 要转化为的字符串格式(如:yyyy-MM-dd HH:mm:ss)。
* @return 返回日期字符串。
*/
public
static
String millisToStringDate(
long
millis, String pattern) {
SimpleDateFormat format =
new
SimpleDateFormat(pattern,
Locale.getDefault());
return
format.format(
new
Date(millis));
}
把日期毫秒转化为字符串(文件名)
/**
* @param millis
* 要转化的日期毫秒数。
* @param pattern
* 要转化为的字符串格式(如:yyyy-MM-dd HH:mm:ss)。
* @return 返回日期字符串(yyyy_MM_dd_HH_mm_ss)。
*/
public
static
String millisToStringFilename(
long
millis, String pattern) {
String dateStr = millisToStringDate(millis, pattern);
return
dateStr.replaceAll(
"[- :]"
,
"_"
);
转换当前时间为易用时间格式
1小时内用,多少分钟前; 超过1小时,显示时间而无日期; 如果是昨天,则显示昨天 超过昨天再显示日期; 超过1年再显示年。public
static
long
oneHourMillis =
60
*
60
*
1000
;
// 一小时的毫秒数
public
static
long
oneDayMillis =
24
* oneHourMillis;
// 一天的毫秒数
public
static
long
oneYearMillis =
365
* oneDayMillis;
// 一年的毫秒数
public
static
String millisToLifeString(
long
millis) {
long
now = System.currentTimeMillis();
long
todayStart = string2Millis(millisToStringDate(now,
"yyyy-MM-dd"
),
"yyyy-MM-dd"
);
// 一小时内
if
(now - millis <= oneHourMillis && now - millis > 0l) {
String m = millisToStringShort(now - millis,
false
,
false
);
return
""
.equals(m) ?
"1分钟内"
: m +
"前"
;
}
// 大于今天开始开始值,小于今天开始值加一天(即今天结束值)
if
(millis >= todayStart && millis <= oneDayMillis + todayStart) {
return
"今天 "
+ millisToStringDate(millis,
"HH:mm"
);
}
// 大于(今天开始值减一天,即昨天开始值)
if
(millis > todayStart - oneDayMillis) {
return
"昨天 "
+ millisToStringDate(millis,
"HH:mm"
);
}
long
thisYearStart = string2Millis(millisToStringDate(now,
"yyyy"
),
"yyyy"
);
// 大于今天小于今年
if
(millis > thisYearStart) {
return
millisToStringDate(millis,
"MM月dd日 HH:mm"
);
}
return
millisToStringDate(millis,
"yyyy年MM月dd日 HH:mm"
);
}
字符串解析成毫秒数
public
static
long
string2Millis(String str, String pattern) {
SimpleDateFormat format =
new
SimpleDateFormat(pattern,
Locale.getDefault());
long
millis =
0
;
try
{
millis = format.parse(str).getTime();
}
catch
(ParseException e) {
Log.e(
"TAG"
, e.getMessage());
}
return
millis;
}
手机号码正则
public
static
final
String REG_PHONE_CHINA =
"^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$"
;
邮箱正则
public
static
final
String REG_EMAIL =
"\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"
;
0 0
- 摘要常用code片段
- Objective C 常用代码片段制作(code snippet library)
- Xcode添加常用的代码片段 (code sinppets)
- PHP-常用代码片段
- JS_常用代码片段
- android常用代码片段
- LaTeX常用代码片段
- jquery常用代码片段
- android常用代码片段
- 常用函数片段
- jquery常用代码片段
- Python 常用代码片段
- Java 常用代码片段
- android常用代码片段
- Android常用代码片段
- JQuery常用代码片段
- Python 常用代码片段
- Android 常用代码片段
- angular项目流程功能实现
- Codeforences 23E Tree
- 记两例程序问题排查
- 互联网运营、产品岗一定要看的面试题(一线二线互联网企业面试题整理)
- 异步复位同步释放
- 摘要常用code片段
- Meta标签详解
- RabbitMQ之任务分发篇
- Android学习24
- SHELL的语法和结构
- 网易互联网产品运营管培生面试经历--从群面到终面面试经验分享
- <学习笔记>Android使用Loader加载sqlite数据到ListView
- Hello World程序背后的故事解密(一)—— 编译器的选项和C运行时库
- pg数据库在Linux中安装失败,提示the database cluster initialisation failed