您的位置:首页 > 移动开发 > Android开发

整理Android项目开发中使用频率很高的小方法

2015-03-20 09:48 330 查看
转载:原地址http://blog.csdn.net/metis100/article/details/44101237

感觉这些东西都很常用,转过来收藏一下
public class Common {

/**
* 判断网络连接是否打开
*/
public static boolean CheckNetwork(Context ctx) {
boolean flag = false;
ConnectivityManager netManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
if (netManager.getActiveNetworkInfo() != null) {
flag = netManager.getActiveNetworkInfo().isAvailable();
}
return flag;
}

/**
* 获取Manifest中的meta-data值
* @param context
* @param metaKey
* @return
*/
public static String getMetaValue(Context context, String metaKey) {
Bundle metaData = null;
String values = null;
if (context == null || metaKey == null) {
return null;
}
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
if (null != ai) {
metaData = ai.metaData;
}
if (null != metaData) {
values = metaData.getString(metaKey);
}
} catch (NameNotFoundException e) {

}
return values;
}

/**
* 获取软件版本
*/
public static String thisVersion(Context context) {
final String unknown = "Unknown";
if (context == null)
return unknown;
try {
String ret = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
if (ret.contains(" + "))
ret = ret.substring(0, ret.indexOf(" + ")) + "b";
return ret;
} catch (NameNotFoundException ex) {
}
return unknown;
}

/**
* 判断是否装有SD卡、是否可读写、是否有空间
*
* @param size 需存入的文件大小,SD剩余空间必须大于该值
* @return true可用,false不可用
*/
public static boolean checkSDStatus(long size) {
try {
/* 读取SD卡大小 */
File storage = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(storage.getPath());
long blocks = stat.getAvailableBlocks();
long blocksize = stat.getBlockSize();

/* 判断 */
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && (blocks * blocksize) > size) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* 字节的大小,转成口头语
* @param size
* @return
*/
public static String byte2Oral(double size) {
DecimalFormat df = new DecimalFormat("0.0");
StringBuffer datas = new StringBuffer();
if (size < 1048576) {
datas.append((int) (size / 1024)).append("KB");
} else if (size > 1048576) {
datas.append(df.format((size / 1048576))).append("MB");
} else if (size < 1024) {
datas.append(size).append("B");
}
return datas.toString();
}

/**
* dip转px
*
* @param dipValue
* @return
*/
public static int getPixels(Context ctx, int dipValue) {
Resources r = ctx.getResources();
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, r.getDisplayMetrics());
return px;
}

/**
* 判断当前应用程序是否处于后台,通过getRunningTasks的方式
* @return true 在后台; false 在前台
*/
public static boolean isApplicationBroughtToBackgroundByTask(String packageName, Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = activityManager.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(packageName)) {
return true;
}
}
return false;
}

/**
* 获取包名
* @param ctx
* @return
*/
public static String getPackageName(Context ctx) {
try {
PackageInfo info = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
return info.packageName;
} catch (NameNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 取缓存的路径,存储卡的话,至少得1M空间
*
* @return
*/
public static File getCachePath(Context ctx, String uniqueName) {
if (Common.checkSDStatus(1)) {
// 有存储卡的情况下,存入应用本身的缓存目录
// 路径为:/storage/emulated/0/Android/data/com.example.roamtest/cache
return new File(ctx.getExternalCacheDir().getPath(), uniqueName);
} else {
// 无存储卡的情况下,存入内置空间
// 路径为:/data/data/com.example.roamtest/cache
return new File(ctx.getCacheDir().getPath(), uniqueName);
}
}

/**
* 判断字符串是否有空
* @param str
* @return
*/
public static String doNullStr(String str) {
return TextUtils.isEmpty(str) ? "" : str;
}

/**
* 获取设备信息
* @param context
* @return
*/
public static Map<String, String> getDeviceInfo(Context context) {
Map<String, String> map = new HashMap<String, String>();
android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);

String device_id = tm.getDeviceId();
String msisdn = tm.getLine1Number(); // 手机号码
String iccid = tm.getSimSerialNumber(); // sim卡号ICCID
String imsi = tm.getSubscriberId(); // imsi

android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context
.getSystemService(Context.WIFI_SERVICE);

int i = wifi.getConnectionInfo().getIpAddress();
String ip = ((i & 0xff) + "." + (i >> 8 & 0xff) + "." + (i >> 16 & 0xff) + "." + (i >> 24 & 0xff));
String mac = wifi.getConnectionInfo().getMacAddress();

if (TextUtils.isEmpty(device_id)) {
device_id = mac;
}

if (TextUtils.isEmpty(device_id)) {
device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);
}

map.put("ip", doNullStr(ip));
map.put("mac", doNullStr(mac));
map.put("device_id", doNullStr(device_id));
map.put("msisdn", doNullStr(msisdn));
map.put("iccid", doNullStr(iccid));
map.put("imsi", doNullStr(imsi));

return map;
}

/**
* 复制文件至某个文件夹
* @param srcFileName 源文件完整路径
* @param destDirName 目的目录完整路径,包含文件名
* @return
*/
public static boolean copyFileToFile(String srcFileName, String destDirName) {
try {
int byteread = 0;
File oldfile = new File(srcFileName);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(oldfile);
FileOutputStream fs = new FileOutputStream(destDirName);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
fs.write(buffer, 0, byteread);
}
inStream.close();
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 判断是否是身份证
*
* @param identifyCard
*/
public static boolean isIdentifyCard(String identifyCard){
Pattern p = Pattern.compile("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])");
Matcher m = p.matcher(identifyCard);
return m.matches();
}
/**
* 判断电话号码是否有效
* 移动:134、135、136、137、138、139、147、150、151、152、157、158、159、182、183、187、188
* 联通:130、131、132、145、155、156、185、186
* 电信:133、153、180、181、189
* 虚拟运营商:17x
*/
public static boolean isMobileNO(String number) {
if (number.startsWith("+86")) {
number = number.substring(3);
}

if (number.startsWith("+") || number.startsWith("0")) {
number = number.substring(1);
}

number = number.replace(" ", "").replace("-", "");
System.out.print("号码:" + number);

Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-3,5-9])|(17[0-9]))\\d{8}$");
Matcher m = p.matcher(number);

return m.matches();
}

/**
* 号码的运营商类型
*
* @param number
* @return
*/
public static String getMobileType(String number) {
String type = "未知用户";
Pattern p = Pattern.compile("^(([4,8]00))\\d{7}$");
if (p.matcher(number).matches())
return "企业电话";

if (number.startsWith("+86")) {
number = number.substring(3);
}

if (number.startsWith("+") || number.startsWith("0")) {
number = number.substring(1);
}

number = number.replace(" ", "").replace("-", "");
System.out.print("号码:" + number);

p = Pattern.compile("^((13[4-9])|(147)|(15[0-2,7-9])|(18[2,3,7,8]))\\d{8}$");
if (p.matcher(number).matches())
return "移动用户";

p = Pattern.compile("^((13[0-2])|(145)|(15[5,6])|(18[5,6]))\\d{8}$");
if (p.matcher(number).matches())
return "联通用户";

p = Pattern.compile("^((1[3,5]3)|(18[0,1,9]))\\d{8}$");
if (p.matcher(number).matches())
return "电信用户";

p = Pattern.compile("^((17[0-9]))\\d{8}$");
if (p.matcher(number).matches())
return "虚拟运营端";

if (number.length() >= 7 && number.length() <= 12)
return "固话用户";

return type;
}

/**
* 获取随机数
* @param iRdLength
* @return
*/
public static String getRandom(int iRdLength) {
Random rd = new Random();
int iRd = rd.nextInt();
if (iRd < 0) { // 负数时转换为正数
iRd *= -1;
}
String sRd = String.valueOf(iRd);
int iLgth = sRd.length();
if (iRdLength > iLgth) { // 获取数长度超过随机数长度
return digitToString(iRd, iRdLength);
} else {
return sRd.substring(iLgth - iRdLength, iLgth);
}
}

/**
* 把一个整数转化为一个n位的字符串
* @param digit
* @param n
* @return
*/
public static String digitToString(int digit, int n) {
String result = "";
for (int i = 0; i < n - String.valueOf(digit).length(); i++) {
result = result + "0";
}
result = result + String.valueOf(digit);
return result;
}

/**
* 计算MD5
* @param str
* @return
*/
public static String MD5(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes("utf-8"));
byte[] result = md.digest();
StringBuffer sb = new StringBuffer(32);
for (int i = 0; i < result.length; i++) {
int val = result[i] & 0xff;
if (val <= 0xf) {
sb.append("0");
}
sb.append(Integer.toHexString(val));
}
return sb.toString();//.toUpperCase();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
public static String double_convert(double value) {
long l1 = Math.round(value * 100);//四舍五入
double ret = l1 / 100.0;//注意:使用100.0,而不是 100
if (ret - (int) ret == 0) {
return (int) ret + "";
} else {
return ret + "";
}
}

/**
* 根据字符串,计算出其占用的宽度
* @param str
* @param textsize
* @return
*/
public static float getTextWidthFontPx(String str, float textsize) {
Paint mPaint = new Paint();
mPaint.setTextSize(textsize);
return str.length() * mPaint.getFontSpacing();
}
private static final double EARTH_RADIUS =6378137.0;
// 返回单位是米
public static double getDistance(double longitude1, double latitude1,
double longitude2, double latitude2) {
double Lat1 = rad(latitude1);
double Lat2 = rad(latitude2);
double a = Lat1 - Lat2;
double b = rad(longitude1) - rad(longitude2);
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
+ Math.cos(Lat1) * Math.cos(Lat2)
* Math.pow(Math.sin(b / 2), 2)));
s = s * EARTH_RADIUS;
s = Math.round(s * 10000) / 10000;
return s;
}
private static double rad(double d) {
return d * Math.PI / 180.0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: