首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

android 惯用方法集合

2013-10-10 
android 常用方法集合private static Contextcontextprivatestatic Displaydisplayprivate static Strin

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) {}

}

}



热点排行