请选择 进入手机版 | 继续访问电脑版
每次做一个功能的时候,或多或少都会遇到,很常见的一个方法,就是突然忘记了怎么了去写,不得不又去网上满世界的去找,既耽误了时间,也耽误了精力,今天就为大家集锦了一些我们开发中常用我们却又不常记的方法1.根据手机的分辨率从 dip 的单位 转成为 px(像素)

public static int dip2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}

2.根据手机的分辨率从 px(像素) 的单位 转成为 dp

public static int px2dip(Context context, float pxValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (pxValue / scale + 0.5f);
}

3.隐藏键盘

public void hintInputMethodManager(){
   InputMethodManager imm = (InputMethodManager)
        getSystemService(ActivityLiveInteractive.this.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mEditMessage.getWindowToken(), 0);
        }

4.显示键盘

public void showInputMethodManager(){
            InputMethodManager inputManager =(InputMethodManager)mEditMessage.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(mEditMessage, 0);
        }

5.给TextView上下左右添加图片:

Drawable drawable = getResources().getDrawable(图片资源id);
  drawable.setBounds(0, 0, drawable.getMinimumWidth(),
        drawable.getMinimumHeight());
  youview.setCompoundDrawables(drawable, null, null, null);

6.获取手机屏幕宽度

public static int getScreenWidth(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
return display.getWidth();
}

7.获取手机屏幕高度

public static int getScreenHeight(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
return display.getHeight();
}

8.获取gps状态:

public static boolean getGPSState(Context context) {
final LocationManager lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
if (lm == null)
return false;
return lm.isProviderEnabled("gps");
}

9.获取应用名称:

public static String getAppName(Context context,String packageName){
String appName = null;
try {
ApplicationInfo applicationInfo = context.getPackageManager()
.getPackageInfo(packageName, 0).applicationInfo;
appName = (String) context.getPackageManager().getApplicationLabel(
applicationInfo);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return appName;
}

10.获取版本名称:

public static  String getVersionName(Context context,String packageName) {
String versionName = null;
try {
// 获取软件版本名称,对应AndroidManifest.xml下android:versionName
versionName = context.getPackageManager().getPackageInfo(
packageName, 0).versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}

11.获取版本号:

public static int getVersionCode(Context context,String packageName) {
int versionCode = 0;
try {
// 获取软件版本号,对应AndroidManifest.xml下android:versionCode
versionCode = context.getPackageManager().getPackageInfo(
packageName, 0).versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}

12.BitMap  转   inputStream

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
InputStream isBm = new ByteArrayInputStream(baos .toByteArray());

13.BitMap  转    byte[]

Bitmap defaultIcon = BitmapFactory.decodeStream(in);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();

14.Drawable 转    byte[]


Drawable d; // the drawable (Captain Obvious, to the rescue!!!)
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, bitmap);
byte[] bitmapdata = stream.toByteArray();

15.byte[]  转   Bitmap

Bitmap bitmap =BitmapFactory.decodeByteArray(byte[], 0,byte[].length);

16.获取存储卡路径

File sdcardDir=Environment.getExternalStorageDirectory();

17.StatFs 看文件系统空间使用情况

StatFs statFs=new StatFs(sdcardDir.getPath());

18.获取手机sdk版本:

int sdkInt=Build.VERSION.SDK_INT;

19.获取手机品牌:

String brand=android.os.Build.BRAND;

20.获取当前时间:

Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(date);

21.检查是否连接网络:

public static boolean isConnected(Context context) {
    ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
    NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (mobNetInfo != null && mobNetInfo.isConnected()) {
        return true;
    }
    if (wifiNetInfo != null && wifiNetInfo.isConnected()) {
        return true;
    }
    return false;
}

22.检查是否是Wi-Fi连接:

public static boolean isWifiConnected(Context paramContext) {
    NetworkInfo localNetworkInfo = ((ConnectivityManager) paramContext.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    return (localNetworkInfo != null) && (localNetworkInfo.getType() == 1);
}

23.退出程序三种方式:

public static void ExitApp(Context ctx) {

ActivityManager am = (ActivityManager)
ctx.getSystemService(Context.ACTIVITY_SERVICE);
am.restartPackage(ctx.getPackageName());

Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(startMain);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);

android.os.Process.killProcess(android.os.Process.myPid());
}

24.md5加密:

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"";
}
}

[code][/code]25.邮箱检验:

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

26.判断字符串是否为空

public static boolean isNull(String string)
{
if (null == string ||"".equals(string)) {
return false;
}
return true;
}

27.返回时间

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

28.判断是否是今天

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

29.按两次后退出应用

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;

30.代码添加布局:

AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                              ViewGroup.LayoutParams.FILL_PARENT, 64);

              TextView text = new TextView(activity);
              text.setLayoutParams(lp);
              text.setTextSize(20);
              text.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
              text.setPadding(36, 0, 0, 0);
              text.setText(s);
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|翁笔

Powered by Discuz! X3.3 © 2001-2018 Comsenz Inc.

返回顶部