android 常用方法集合
发布日期:2021-06-30 21:49:34 浏览次数:2 分类:技术文章

本文共 14415 字,大约阅读时间需要 48 分钟。

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

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

转载地址:https://loongembedded.blog.csdn.net/article/details/40947949 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:JNI设置C++与java的结合(2)
下一篇:在android C/C++ native编程(ndk)中使用logcat

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年05月01日 12时32分59秒