private static Contextcontext;

privatestatic Displaydisplay;

private static String TAG = "MyTools";

public MyTools(Context context) {

MyTools.context = context;

}

publicstaticint getScreenHeight()// 获取屏幕高度

{

if (context ==null) {

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

return 0;

}

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

return display.getHeight();

}

publicstaticint 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号

}

publicstatic String getModel()// 手机型号

{

return android.os.Build.MODEL;

}

publicstatic String getRelease()// android系统版本号

{

return android.os.Build.VERSION.RELEASE;

}

publicstatic String getImei(Context context)// 获取手机身份证imei

{

TelephonyManager telephonyManager = (TelephonyManager) context

.getSystemService(Context.TELEPHONY_SERVICE);

return telephonyManager.getDeviceId();

}

publicstatic String getVerName(Context context) {// 获取版本名字

try {

String pkName = context.getPackageName();

String versionName = context.getPackageManager().getPackageInfo(

pkName, 0).versionName;

return versionName;

} catch (Exception e) {

}

returnnull;

}

publicstaticint 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;

}

publicstaticboolean 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);

}

publicstatic String trim(String str,int limit) {//
字符串超出给定文字则截取

String mStr = str.trim();

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

}

publicstatic String getTel(Context context) {// 获取手机号码,很多手机获取不到

TelephonyManager telManager = (TelephonyManager) context

.getSystemService(Context.TELEPHONY_SERVICE);

return telManager.getLine1Number();

}

publicstatic 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;

}

publicstaticboolean 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();

}

publicstaticboolean isNull(String string)//
字符串是否为空

{

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

returnfalse;

}

returntrue;

}

publicstaticboolean isLenghtOk(String string,int max,int min)//
字符串长度检测

{

if (null != string) {

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

returnfalse;

}

}

returntrue;

}

publicstaticboolean 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 finalstatic 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) {

returnnull;

}

}

/**

* 以友好的方式显示时间

* @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 ) )

returntrue;

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

{

char c = input.charAt( i );

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

{

returnfalse;

}

}

returntrue;

}

/**

* 判断是不是一个合法的电子邮件地址

* @param email

* @return

*/

public static boolean isEmail(String email){

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

returnfalse;

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

returnfalse;

}

/**

* 获取当前网络类型

* @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;

}

//启动一个已安装应用(知道包名和入口activity)

ComponentName componentName=new ComponentName("应用的包名","应用入口activity");

//ComponentName componentName=new ComponentName("com.hck.test", "com.hck.test.MainActivity");

Intent intent=new Intent();

intent.setComponent(componentName);

startActivity(intent);

// 获取系统内的所有程序信息

Intent mainintent = new Intent(Intent.ACTION_MAIN, null);

mainintent.addCategory(Intent.CATEGORY_LAUNCHER);

List<PackageInfo>   packageinfo = this.getPackageManager().getInstalledPackages(0);

//获取meta-data 里面的值

public static String getMetaValue(Context context, String metaKey) {

  Bundle metaData = null;

  String apiKey = 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) {

    apiKey = metaData.getString(metaKey);

   }

  } catch (NameNotFoundException e) {

}

  

  return apiKey;

 }

//  连续点击2次退出程序

if(event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {

    long currentTime = System.currentTimeMillis();

    if((currentTime-touchTime)>=waitTime) {

     Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();

     touchTime = currentTime;

     return true;

    }else {

     AppManager.getAppManager().appExit();

     finish();

     return false;

    }

    

   }

   return true;

//实现打电话

Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phoneNumber));  

        this.startActivity(intent);

android 常用方法集合的更多相关文章

  1. Android --资料集合

    google android 官方教程 http://hukai.me/android-training-course-in-chinese/basics/index.html android视频资料 ...

  2. Android icons集合

    Android icons集合: Be aware that the style changes occur fairly regularly with each major release, so ...

  3. android广播集合,intent,action

    android.permission.ACCESS_CHECKIN_PROPERTIES 同意读写訪问"properties"表在checkin数据库中,改值能够改动上传( All ...

  4. Android转换集合数据(ArrayList)为Json格式并上传服务器

    使用Gson上传集合数据到服务器,1.最外层用 ArrayMap<String, Object> 封装:2.通过  mRequestParam.put("cmdLineIds&q ...

  5. Android 错误集合

    1. Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 erro ...

  6. android 常用方法总结

    public class Toolkit { /** * * Role:Telecom service providers获取手机服务商信息 <BR> * * 需要加入权限<uses ...

  7. Android工具集合

    Drozer – Android APP安全评估工具(附测试案例) http://www.freebuf.com/sectool/26503.html

  8. 【汇总】Android 常用方法整理

    1.解决ActionBar OverFlow按钮不显示.(在oncreate中调用即可) private void setOverflowShowingAlways() { try { ViewCon ...

  9. C#常用方法集合

    public class Utility:Page { #region 数据转换 /// <summary> /// 返回对象obj的String值,obj为null时返回空值. /// ...

随机推荐

  1. Angular2的input和output(原先的properties和events)

    angular2学习笔记 本文地址:http://blog.csdn.net/sushengmiyan 本文作者:苏生米沿 文章来源:http://blog.ng-book.com/angular-2 ...

  2. iOS开源加密相册Agony的实现(一)

    简介 虽然目前市面上有一些不错的加密相册App,但不是内置广告,就是对上传的张数有所限制.本文介绍了一个加密相册的制作过程,该加密相册将包括多密码(输入不同的密码即可访问不同的空间,可掩人耳目).Wi ...

  3. 如何编写入门级redis客户端

    概述 Redis是开源的.基于内存的数据结构存储系统,可用作数据库.缓存以及消息代理方面.Redis支持许多种数据结构,并内置了丰富的诸如冗余.脚本.事务.持久化等功能,深受业界喜爱,被各种业务系统广 ...

  4. Retrofit2.0+RxJava+Dragger2实现不一样的Android网络架构搭建

    Tamic :csdn http://blog.csdn.net/sk719887916 众所周知,手机APP的核心就在于调用后台接口,展示相关信息,方便我们在手机上就能和外界交互.所以APP中网络框 ...

  5. Android中PropertyAnimation属性动画详解(一)

    在之前的文章中已经讲了帧动画frame-by-frame animation和补间动画tweened animation,其实这两种动画原理好简单,都是按照预先固定的动画模式来播放的,帧动画将一张张单 ...

  6. 单幅图像的深度学习,对NYU数据集进行划分

    针对分割问题,官方已经划分好了:http://cs.nyu.edu/~silberman/projects/indoor_scene_seg_sup.html import numpy as np i ...

  7. android插件化之路

    概论  插件式开发通俗的讲就是把一个很大的app分成n多个比较小的app,其中有一个app是主app.基本上可以理解为让一个apk不安装也可以被运行.只不过这个运行是有很多限制的运行,所以才叫插件. ...

  8. .so的封装调用

    .so的创建和调用有一个特点,我们要知道.so的调用并不一定必须在Activity中进行,那么制作时也并不一定要在Activity中,但是,一旦.so制作成功,那么再调用时,调用的java类就必须跟制 ...

  9. Android初级教程使用服务注册广播接收者监听手机解锁屏变化

    之前第七章广播与服务理论篇写到: 特殊的广播接收者(一般发广播次数频率很高) 安卓中有一些广播接收者,必须使用代码注册,清单文件注册是无效的 屏幕锁屏和解锁 电量改变 今天在这里就回顾一下,且用代码方 ...

  10. 学习笔记3-开发与运行(卸载)第一个ANDROID应用

    新建Android项目 1.      配置好Android坏境以后,新建项目选择Android Project. 2.      选择针对哪个平台开发的应用(Android2/Android4等) ...