天天看點

Android開發當中常用的方法集錦

每次做一個功能的時候,或多或少都會遇到,很常見的一個方法,就是突然忘記了怎麼了去寫,不得不又去網上滿世界的去找,既耽誤了時間,也耽誤了精力,今天就為大家集錦了一些我們開發中常用我們卻又不常記的方法,更多Android文章,請關注我的微信公衆賬号(左邊最上邊二維碼)。

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.擷取gbs狀态:

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

}

}

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