Android 常用方法代碼集合

jopen 11年前發布 | 21K 次閱讀 Android Android開發 移動開發

 private static Contextcontext;

privatestatic Displaydisplay;

private static String TAG = "MyTools";

public MyTools(Context context) {

MyTools.context = context;

}

public static int getScreenHeight() // 獲取屏幕高度

{

if (context ==null) {

Log.e("hck",TAG +" getScreenHeight: " +"context 不能為空");

return 0;

}

display = ((Activity)context).getWindowManager().getDefaultDisplay();

return display.getHeight();

}

public static int getScreenWidth() // 獲取屏幕寬度

{

if (context ==null) {

Log.e("hck",TAG +" getScreenHeight: " +"context 不能為空");

return 0;

}

display = ((Activity)context).getWindowManager().getDefaultDisplay();

return display.getWidth();

}

public static String getSDK() {

return android.os.Build.VERSION.SDK;// SDK號

}

public static String getModel() // 手機型號

{

return android.os.Build.MODEL;

}

public static String getRelease() // android系統版本號

{

return android.os.Build.VERSION.RELEASE;

}

public static String getImei(Context context) // 獲取手機身份證imei

{

TelephonyManager telephonyManager = (TelephonyManager) context

.getSystemService(Context.TELEPHONY_SERVICE);

return telephonyManager.getDeviceId();

}

public static String getVerName(Context context) { // 獲取版本名字

try {

String pkName = context.getPackageName();

String versionName = context.getPackageManager().getPackageInfo(

pkName, 0).versionName;

return versionName;

} catch (Exception e) {

}

returnnull;

}

public static int getVerCode(Context context) {// 獲取版本號

String pkName = context.getPackageName();

try {

int versionCode = context.getPackageManager().getPackageInfo(

pkName, 0).versionCode;

return versionCode;

} catch (NameNotFoundException e) {

e.printStackTrace();

}

return 0;

}

public static boolean isNetworkAvailable(Context context) {// 判斷網絡連接是否可用

// 獲取手機所有連接管理對象(包括對wi-fi,net等連接的管理)

ConnectivityManager connectivity = (ConnectivityManager) context

.getSystemService(Context.CONNECTIVITY_SERVICE);

if (connectivity ==null)

returnfalse;

// 獲取網絡連接管理的對象

NetworkInfo info = connectivity.getActiveNetworkInfo();

if (info ==null || !info.isConnected())

returnfalse;

// 判斷當前網絡是否已經連接

return (info.getState() == NetworkInfo.State.CONNECTED);

}

public static String trim(String str, int limit) {// 字符串超出給定文字則截取

String mStr = str.trim();

return mStr.length() > limit ? mStr.substring(0, limit) : mStr;

}

public static String getTel(Context context) { // 獲取手機號碼,很多手機獲取不到

TelephonyManager telManager = (TelephonyManager) context

.getSystemService(Context.TELEPHONY_SERVICE);

return telManager.getLine1Number();

}

public static String getMac(Context context) { // 獲取時機mac地址

final WifiManager wifi = (WifiManager) context

.getSystemService(Context.WIFI_SERVICE);

if (wifi !=null) {

WifiInfo info = wifi.getConnectionInfo();

if (info.getMacAddress() !=null) {

return info.getMacAddress().toLowerCase(Locale.ENGLISH)

.replace(":","");

}

return"";

}

return"";

}

/**

  • 將 像素 轉換成 dp

  • @param pxValue

  • 像素

  • @returndp

*/

public static int px2dip(int pxValue) {

final float scale = context.getResources().getDisplayMetrics().density;

return (int) (pxValue / scale + 0.5f);

}

/**

  • 將 畫素 轉換成 sp

  • @param pixel

  • @returnsp

*/

publicstaticint px2sp(int px) {

float scaledDensity =context.getResources().getDisplayMetrics().scaledDensity;

return (int) (px / scaledDensity);

}

/**

  • 將 dip 轉換成畫素 px

  • @param dipValue

  • dip 像素的值

  • @return 畫素px

*/

public static int dip2px(float dipValue) {

final float scale = context.getResources().getDisplayMetrics().density;

return (int) (dipValue * scale + 0.5f);

}

public static int[][] getViewsPosition(List<View> views) {

int[][] location =newint[views.size()][2];

for (int index = 0; index < views.size(); index++) {

views.get(index).getLocationOnScreen(location[index]);

}

return location;

}

/**

  • 傳入一個view,返回一個int數組來存放 view在手機屏幕上左上角的絕對坐標

  • @param views

  • 傳入的view

  • @return 返回int型數組,location[0]表示x,location[1]表示y

*/

public static int[] getViewPosition(View view) {

int[] location =newint[2];

view.getLocationOnScreen(location);

return location;

}

/**

  • onTouch界面時指尖在views中的哪個view當中

  • @param event

  • ontouch事件

  • @param views

  • view list

  • @return view

*/

public static View getOnTouchedView(MotionEvent event, List<View> views) {

int[][] location = getViewsPosition(views);

for (int index = 0; index < views.size(); index++) {

if (event.getRawX() > location[index][0]

&& event.getRawX() < location[index][0]

  • views.get(index).getWidth()

&& event.getRawY() > location[index][1]

&& event.getRawY() < location[index][1]

  • views.get(index).getHeight()) {

return views.get(index);

}

}

returnnull;

}

/**

  • 將傳進的圖片存儲在手機上,并返回存儲路徑

  • @param photo

  • Bitmap 類型,傳進的圖片

  • @return String 返回存儲路徑

*/

public static String savePic(Bitmap photo, String name, String path) {

ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 創建一個

// outputstream

// 來讀取文件流

photo.compress(Bitmap.CompressFormat.PNG, 100, baos);// 把 bitmap 的圖片轉換成

// jpge

// 的格式放入輸出流中

byte[] byteArray = baos.toByteArray();

String saveDir = Environment.getExternalStorageDirectory()

.getAbsolutePath();

File dir = new File(saveDir +"/" + path);// 定義一個路徑

if (!dir.exists()) {// 如果路徑不存在,創建路徑

dir.mkdir();

}

File file = new File(saveDir, name +".png");// 定義一個文件

if (file.exists())

file.delete(); // 刪除原來有此名字文件,刪除

try {

file.createNewFile();

FileOutputStream fos;

fos = new FileOutputStream(file);// 通過 FileOutputStream 關聯文件

BufferedOutputStream bos = new BufferedOutputStream(fos); // 通過 bos

// 往文件里寫東西

bos.write(byteArray);

bos.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return file.getPath();

}

/**

  • 回收 bitmap 減小系統占用的資源消耗

*/

public static void destoryBimap(Bitmap photo) {

if (photo !=null && !photo.isRecycled()) {

photo.recycle();

photo = null;

}

}

/**

  • 將輸入字串做 md5 編碼

  • @param s

  • : 欲編碼的字串

  • @return 編碼後的字串, 如失敗, 返回 ""

*/

public static String md5(String s) {

try {

// Create MD5 Hash

MessageDigest digest = java.security.MessageDigest

.getInstance("MD5");

digest.update(s.getBytes("UTF-8"));

byte messageDigest[] = digest.digest();

// Create Hex String

StringBuffer hexString = new StringBuffer();

for (byte b : messageDigest) {

if ((b & 0xFF) < 0x10)

hexString.append("0");

hexString.append(Integer.toHexString(b & 0xFF));

}

return hexString.toString();

} catch (NoSuchAlgorithmException e) {

return"";

} catch (UnsupportedEncodingException e) {

return"";

}

}

publicstaticboolean isNumber(char c) {// 是否是數字

boolean isNumer =false;

if (c >= '0' && c <= '9') {

isNumer = true;

}

return isNumer;

}

public static boolean isEmail(String strEmail) {// 是否是正確的郵箱地址

String checkemail ="^([a-z0-9A-Z]+[-|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$";

Pattern pattern = Pattern.compile(checkemail);

Matcher matcher = pattern.matcher(strEmail);

return matcher.matches();

}

public static boolean isNull(String string) // 字符串是否為空

{

if (null == string ||"".equals(string)) {

returnfalse;

}

returntrue;

}

public static boolean isLenghtOk(String string,int max,int min)// 字符串長度檢測

{

if (null != string) {

if (string.length() > max || string.length() < min) {

returnfalse;

}

}

returntrue;

}

public static boolean isLenghtOk(String string,int max)// 字符串長度是否

{

if (null != string) {

if (string.length() > max) {

returnfalse;

}

}

returntrue;

}

//用一種外部格式的字體,字體文件放在assets下面的fonts下面,名字叫whsn.ttf

獲取字體樣式:Typeface tencentTypeface=Typeface.createFromAsset(this.getAssets(), "fonts/whsn.ttf")

使用

textView.setTypeface(tencentTypeface);

/**

*activity管理類,保證應用退出后,銷毀所有創建的activity

**/

/**

  • 應用程序Activity管理類:用于Activity管理和應用程序退出

  • @author liux (http://my.oschina.net/liux)

  • @version 1.0

  • @created 2012-3-21

    */

public class AppManager {

private static Stack<Activity> activityStack;

private static AppManager instance;

private AppManager(){}

/**

  • 單一實例

*/

public static AppManager getAppManager(){

if(instance==null){

instance=new AppManager();

}

returninstance;

}

/**

  • 添加Activity到堆棧

*/

public void addActivity(Activity activity){

if(activityStack==null){

activityStack=new Stack<Activity>();

}

activityStack.add(activity);

}

/**

  • 獲取當前Activity(堆棧中最后一個壓入的)

*/

public Activity currentActivity(){

Activity activity=activityStack.lastElement();

return activity;

}

/**

  • 結束當前Activity(堆棧中最后一個壓入的)

*/

public void finishActivity(){

Activity activity=activityStack.lastElement();

finishActivity(activity);

}

/**

  • 結束指定的Activity

*/

public void finishActivity(Activity activity){

if(activity!=null){

activityStack.remove(activity);

activity.finish();

activity=null;

}

}

/**

  • 結束指定類名的Activity

*/

public void finishActivity(Class<?> cls){

for (Activity activity :activityStack) {

if(activity.getClass().equals(cls) ){

finishActivity(activity);

}

}

}

/**

  • 結束所有Activity

*/

public void finishAllActivity(){

for (int i = 0, size =activityStack.size(); i < size; i++){

        if (null !=activityStack.get(i)){

        activityStack.get(i).finish();

        }

}

activityStack.clear();

}

/**

  • 退出應用程序

*/

public void AppExit(Context context) {

try {

finishAllActivity();

ActivityManager activityMgr= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

activityMgr.restartPackage(context.getPackageName());

System.exit(0);

} catch (Exception e) {}

}

}

//字符串相關工具類

private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {

@Override

protected SimpleDateFormat initialValue() {

return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

}

};

private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {

@Override

protected SimpleDateFormat initialValue() {

return new SimpleDateFormat("yyyy-MM-dd");

}

};

/**

  • 將字符串轉位日期類型

  • @param sdate

  • @return

*/

public static Date toDate(String sdate) {

try {

return dateFormater.get().parse(sdate);

} catch (ParseException e) {

return null;

}

}

/**

  • 以友好的方式顯示時間

  • @param sdate

  • @return

*/

public static String friendly_time(String sdate) {

Date time = toDate(sdate);

if(time == null) {

return "Unknown";

}

String ftime = "";

Calendar cal = Calendar.getInstance();

//判斷是否是同一天

String curDate = dateFormater2.get().format(cal.getTime());

String paramDate = dateFormater2.get().format(time);

if(curDate.equals(paramDate)){

int hour = (int)((cal.getTimeInMillis() - time.getTime())/3600000);

if(hour == 0)

ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000,1)+"分鐘前";

else

ftime = hour+"小時前";

return ftime;

}

long lt = time.getTime()/86400000;

long ct = cal.getTimeInMillis()/86400000;

int days = (int)(ct - lt);

if(days == 0){

int hour = (int)((cal.getTimeInMillis() - time.getTime())/3600000);

if(hour == 0)

ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000,1)+"分鐘前";

else

ftime = hour+"小時前";

}

else if(days == 1){

ftime = "昨天";

}

else if(days == 2){

ftime = "前天";

}

else if(days > 2 && days <= 10){

ftime = days+"天前";

}

else if(days > 10){

ftime = dateFormater2.get().format(time);

}

return ftime;

}

/**

  • 判斷給定字符串時間是否為今日

  • @param sdate

  • @return boolean

*/

public static boolean isToday(String sdate){

boolean b = false;

Date time = toDate(sdate);

Date today = new Date();

if(time != null){

String nowDate = dateFormater2.get().format(today);

String timeDate = dateFormater2.get().format(time);

if(nowDate.equals(timeDate)){

b = true;

}

}

return b;

}

/**

  • 判斷給定字符串是否空白串。

  • 空白串是指由空格、制表符、回車符、換行符組成的字符串

  • 若輸入字符串為null或空字符串,返回true

  • @param input

  • @return boolean

*/

public static boolean isEmpty( String input )

{

if ( input == null || "".equals( input ) )

return true;

for ( int i = 0; i < input.length(); i++ )

{

char c = input.charAt( i );

if ( c != ' ' && c != '\t' && c != '\r' && c != '\n' )

{

return false;

}

}

return true;

}

/**

  • 判斷是不是一個合法的電子郵件地址

  • @param email

  • @return

*/

public static boolean isEmail(String email){

if(email == null || email.trim().length()==0)

return false;

return emailer.matcher(email).matches();

}

/**

  • 字符串轉整數

  • @param str

  • @param defValue

  • @return

*/

public static int toInt(String str, int defValue) {

try{

return Integer.parseInt(str);

}catch(Exception e){}

return defValue;

}

/**

  • 對象轉整數

  • @param obj

  • @return 轉換異常返回 0

*/

public static int toInt(Object obj) {

if(obj==null) return 0;

return toInt(obj.toString(),0);

}

/**

  • 對象轉整數

  • @param obj

  • @return 轉換異常返回 0

*/

public static long toLong(String obj) {

try{

return Long.parseLong(obj);

}catch(Exception e){}

return 0;

}

/**

  • 字符串轉布爾值

  • @param b

  • @return 轉換異常返回 false

*/

public static boolean toBool(String b) {

try{

return Boolean.parseBoolean(b);

}catch(Exception e){}

return false;

}

/**

  • 獲取當前網絡類型

  • @return 0:沒有網絡 1:WIFI網絡 2:WAP網絡 3:NET網絡

*/

public int getNetworkType() {

int netType = 0;

ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

if (networkInfo == null) {

return netType;

}

int nType = networkInfo.getType();

if (nType == ConnectivityManager.TYPE_MOBILE) {

String extraInfo = networkInfo.getExtraInfo();

if(!StringUtils.isEmpty(extraInfo)){

if (extraInfo.toLowerCase().equals("cmnet")) {

netType = NETTYPE_CMNET;

} else {

netType = NETTYPE_CMWAP;

}

}

} else if (nType == ConnectivityManager.TYPE_WIFI) {

netType = NETTYPE_WIFI;

}

return netType;

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!