Android 各种工
生活随笔
收集整理的這篇文章主要介紹了
Android 各种工
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
新項目,自己整理了一些工具類,
1.首選項
public class SpUtils {/** * 保存在手機里面的文件名 */ public static final String FILE_NAME ="123"; static Context context = BaseApplication.getmContext(); /** * 保存數據的方法,我們需要拿到保存數據的具體類型,然后根據類型調用不同的保存方法 * * @param key * @param object */ public static void put(String key, Object object) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); if (object instanceof String) {editor.putString(key, (String) object); } else if (object instanceof Integer) {editor.putInt(key, (Integer) object); } else if (object instanceof Boolean) {editor.putBoolean(key, (Boolean) object); } else if (object instanceof Float) {editor.putFloat(key, (Float) object); } else if (object instanceof Long) {editor.putLong(key, (Long) object); } else {editor.putString(key, object.toString()); }SharedPreferencesCompat.apply(editor); }/** * 得到保存數據的方法,我們根據默認值得到保存的數據的具體類型,然后調用相對于的方法獲取值 * * @param key * @param defaultObject * @return */ public static Object get(String key, Object defaultObject) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); if (defaultObject instanceof String) {return sp.getString(key, (String) defaultObject); } else if (defaultObject instanceof Integer) {return sp.getInt(key, (Integer) defaultObject); } else if (defaultObject instanceof Boolean) {return sp.getBoolean(key, (Boolean) defaultObject); } else if (defaultObject instanceof Float) {return sp.getFloat(key, (Float) defaultObject); } else if (defaultObject instanceof Long) {return sp.getLong(key, (Long) defaultObject); }return null; }/** * 移除某個key值已經對應的值 */ public static void remove(String key) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); SharedPreferencesCompat.apply(editor); }/** * 清除所有數據 */ public static void clear() {SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.clear(); SharedPreferencesCompat.apply(editor); }public static void setObject(String key, Object object) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = null; try {out = new ObjectOutputStream(baos); out.writeObject(object); String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT)); SharedPreferences.Editor editor = sp.edit(); editor.putString(key, objectVal); editor.commit(); } catch (IOException e) {e.printStackTrace(); } finally {try {if (baos != null) {baos.close(); }if (out != null) {out.close(); }} catch (IOException e) {e.printStackTrace(); }}}@SuppressWarnings("unchecked")public static <T> T getObject(String key, Class<T> clazz) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); if (sp.contains(key)) {String objectVal = sp.getString(key, null); byte[] buffer = Base64.decode(objectVal, Base64.DEFAULT); ByteArrayInputStream bais = new ByteArrayInputStream(buffer); ObjectInputStream ois = null; try {ois = new ObjectInputStream(bais); T t = (T) ois.readObject(); return t; } catch (StreamCorruptedException e) {e.printStackTrace(); } catch (IOException e) {e.printStackTrace(); } catch (ClassNotFoundException e) {e.printStackTrace(); } finally {try {if (bais != null) {bais.close(); }if (ois != null) {ois.close(); }} catch (IOException e) {e.printStackTrace(); }}}return null; }/** * 返回所有的鍵值對 * * @return */ public static Map<String, ?> getAll() {SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); return sp.getAll(); }/** * 創建一個解決SharedPreferencesCompat.apply方法的一個兼容類 * * @author zhy */ private static class SharedPreferencesCompat {private static final Method sApplyMethod = findApplyMethod(); /** * 反射查找apply的方法 * * @return */ @SuppressWarnings({"unchecked", "rawtypes"})private static Method findApplyMethod() {try {Class clz = SharedPreferences.Editor.class; return clz.getMethod("apply"); } catch (NoSuchMethodException e) {}return null; }/** * 如果找到則使用apply執行,否則使用commit * * @param editor */ public static void apply(SharedPreferences.Editor editor) {try {if (sApplyMethod != null) {sApplyMethod.invoke(editor); return; }} catch (IllegalArgumentException e) {} catch (IllegalAccessException e) {} catch (InvocationTargetException e) {}editor.commit(); }}//返回String值 public static String getString(Context context, String key, String defaultStr){SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); return sp.getString(key,defaultStr); }
2.系統工具類
public static final String TAG = SystemTool.class.getSimpleName(); /** * 得到sdk 版本號 * @return */ public static int getSdkVersion() {return Build.VERSION.SDK_INT; }/** * 判斷網絡是否可用 * @param context 上下文 * @return */ public static boolean isNetworkAvailable(Context context) {try {ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netWorkInfo = cm.getActiveNetworkInfo(); return (netWorkInfo != null && netWorkInfo.isAvailable());// 檢測網絡是否可用 } catch (Exception e) {e.printStackTrace(); return false; }}/** * 得到版本號 * @param __context * @return */ public static int getAppVersionCode(Context __context) {try {PackageManager __packageManager = __context.getPackageManager(); PackageInfo __packInfo = __packageManager.getPackageInfo(__context.getPackageName(), 0); return __packInfo.versionCode; } catch (NameNotFoundException e) {return -1; }}public static String getProjectName(Context _context){PackageManager pm = _context.getPackageManager(); String appName = _context.getApplicationInfo().loadLabel(pm).toString(); return appName; }/** * 得到版本名稱 * @param __context * @return */ public static String getAppVersionName(Context __context) {try {PackageManager __packageManager = __context.getPackageManager(); PackageInfo __packInfo = __packageManager.getPackageInfo(__context.getPackageName(), 0); return __packInfo.versionName; } catch (NameNotFoundException e) {return null; }}public static String getPhoneNum(Context _context) {TelephonyManager phoneMgr = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE); return phoneMgr.getLine1Number(); }public static String getIMEI(Context _context) {TelephonyManager _manager = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE); String _imei = _manager.getDeviceId(); // 取出IMEI return _imei; }public static String getICCID(Context _context) {TelephonyManager _manager = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE); String _iccid = _manager.getSimSerialNumber(); // 取出ICCID return _iccid; }public static String getIMSI(Context _context) {TelephonyManager _manager = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE); String _imsi = _manager.getSubscriberId(); // 取出IMSI return _imsi; }public static boolean isPad(Context _context) {if (Build.VERSION.SDK_INT >= 11) {Configuration con = _context.getResources().getConfiguration(); try {Method mIsLayoutSizeAtLeast = con.getClass().getMethod("isLayoutSizeAtLeast", int.class); return (Boolean) mIsLayoutSizeAtLeast.invoke(con, 0x00000004); } catch (Exception e) {e.printStackTrace(); return false; }}return false; }public static Intent call_1(String _phoneNum) {return new Intent(Intent.ACTION_CALL_BUTTON, Uri.parse("tel:" + _phoneNum)); }public static Intent call_2(String _phoneNum) {return new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + _phoneNum)); }/** * 得到設備的唯一Id * @return */ public static String getInstallationId() {return Build.SERIAL; }/** * 得到設備屏幕的寬度 */ public static int getScreenWidth(Context context) {return context.getResources().getDisplayMetrics().widthPixels; }/** * 得到設備屏幕的高度 */ public static int getScreenHeight(Context context) {return context.getResources().getDisplayMetrics().heightPixels; }/** * 得到設備的密度 */ public static float getScreenDensity(Context context) {return context.getResources().getDisplayMetrics().density; }/** * 把密度轉換為像素 */ public static int dip2px(Context context, float px) {final float scale = getScreenDensity(context); return (int) (px * scale + 0.5); } 3.ToastUtil 工具類
public class ToastUtil {static String tag = ToastUtil.class.getSimpleName(); // /** // * 居中Toast // * // * @param str // */ // public static void centerToast(Context context, String str) { // Toast toast = Toast.makeText(context, str, Toast.LENGTH_LONG); // toast.setGravity(Gravity.CENTER, 0, 0); // toast.show(); // // } static Toast mToast; /** * 頂部Toast * 非隊列形式 * * @param str */ public static void topToast(Context context, String str) {if (context == null) {Log.e(tag, "topToast context == null"); return; }if (str == null || str.equals("")) {Log.e(tag, "topToast str == null"); return; }if (mToast == null) {mToast = Toast.makeText(context, str, Toast.LENGTH_LONG); } else {mToast.setText(str); mToast.setDuration(Toast.LENGTH_LONG); }int topHeight = (int) context.getResources().getDimension(R.dimen.top_hight); mToast.setGravity(Gravity.TOP, 0, dp2px(context, topHeight)); mToast.show(); }/** * 頂部Toast * 非隊列形式 * * @param str */ public static void syncToast(Context context, String str, Handler handler, final SyncToastCallback syncToastCallback) {if (context == null) {Log.e(tag, "topToast context == null"); return; }if (str == null || str.equals("")) {Log.e(tag, "topToast str == null"); return; }final Toast toast = Toast.makeText(context, str, Toast.LENGTH_LONG); int topHeight = (int) context.getResources().getDimension(R.dimen.top_hight); toast.setGravity(Gravity.TOP, 0, dp2px(context, topHeight)); toast.show(); handler.postDelayed(new Runnable() {@Override public void run() {toast.cancel(); syncToastCallback.onHide(); }}, 2000); }public static void cancel() {if (mToast != null) {mToast.cancel(); }}public interface SyncToastCallback {void onHide(); }public static int dp2px(Context context, float dpValue) {final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); }public int px2dp(Context context, float pxValue) {final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); }
4.網絡類
public class NetworkUtil {public static int NET_CNNT_BAIDU_OK = 1; // NetworkAvailable public static int NET_CNNT_BAIDU_TIMEOUT = 2; // no NetworkAvailable public static int NET_NOT_PREPARE = 3; // Net no ready public static int NET_ERROR = 4; //net error private static int TIMEOUT = 3000; // TIMEOUT /** * check NetworkAvailable * * @param context * @return */ public static boolean isNetworkAvailable(Context context) {ConnectivityManager manager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); if (null == manager)return false; NetworkInfo info = manager.getActiveNetworkInfo(); if (null == info || !info.isAvailable())return false; return true; }/** * 得到ip地址 * * @return */ public static String getLocalIpAddress() {String ret = ""; try {for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) {ret = inetAddress.getHostAddress().toString(); }}}} catch (SocketException ex) {ex.printStackTrace(); }return ret; }/** * 返回當前網絡狀態 * * @param context * @return */ public static int getNetState(Context context) {try {ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) {NetworkInfo networkinfo = connectivity.getActiveNetworkInfo(); if (networkinfo != null) {if (networkinfo.isAvailable() && networkinfo.isConnected()) {if (!connectionNetwork())return NET_CNNT_BAIDU_TIMEOUT; else return NET_CNNT_BAIDU_OK; } else {return NET_NOT_PREPARE; }}}} catch (Exception e) {e.printStackTrace(); }return NET_ERROR; }/** * ping "http://www.baidu.com" * * @return */ static private boolean connectionNetwork() {boolean result = false; HttpURLConnection httpUrl = null; try {httpUrl = (HttpURLConnection) new URL("http://www.baidu.com").openConnection(); httpUrl.setConnectTimeout(TIMEOUT); httpUrl.connect(); result = true; } catch (IOException e) {} finally {if (null != httpUrl) {httpUrl.disconnect(); }httpUrl = null; }return result; }/** * check is3G * * @param context * @return boolean */ public static boolean is3G(Context context) {ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {return true; }return false; }/** * isWifi * * @param context * @return boolean */ public static boolean isWifi(Context context) {ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {return true; }return false; }/** * is2G * * @param context * @return boolean */ public static boolean is2G(Context context) {ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null && (activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE || activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS || activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA)) {return true; }return false; }/** * is wifi on */ public static boolean isWifiEnabled(Context context) {ConnectivityManager mgrConn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); TelephonyManager mgrTel = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); return ((mgrConn.getActiveNetworkInfo() != null && mgrConn.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS); }}
5.文件操作類
public final class FileUtil {//格式化的模板 private static final String TIME_FORMAT = "_yyyyMMdd_HHmmss"; private static final String SDCARD_DIR =Environment.getExternalStorageDirectory().getPath(); //默認本地上傳圖片目錄 public static final String UPLOAD_PHOTO_DIR =Environment.getExternalStorageDirectory().getPath() + "/a_upload_photos/"; //網頁緩存地址 public static final String WEB_CACHE_DIR =Environment.getExternalStorageDirectory().getPath() + "/app_web_cache/"; //系統相機目錄 public static final String CAMERA_PHOTO_DIR =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/Camera/"; private static String getTimeFormatName(String timeFormatHeader) {final Date date = new Date(System.currentTimeMillis()); //必須要加上單引號 final SimpleDateFormat dateFormat = new SimpleDateFormat("'" + timeFormatHeader + "'" + TIME_FORMAT, Locale.getDefault()); return dateFormat.format(date); }/** * @param timeFormatHeader 格式化的頭(除去時間部分) * @param extension 后綴名 * @return 返回時間格式化后的文件名 */ public static String getFileNameByTime(String timeFormatHeader, String extension) {return getTimeFormatName(timeFormatHeader) + "." + extension; }@SuppressWarnings("ResultOfMethodCallIgnored")private static File createDir(String sdcardDirName) {//拼接成SD卡中完整的dir final String dir = SDCARD_DIR + "/" + sdcardDirName + "/"; final File fileDir = new File(dir); if (!fileDir.exists()) {fileDir.mkdirs(); }return fileDir; }@SuppressWarnings("ResultOfMethodCallIgnored")public static File createFile(String sdcardDirName, String fileName) {return new File(createDir(sdcardDirName), fileName); }private static File createFileByTime(String sdcardDirName, String timeFormatHeader, String extension) {final String fileName = getFileNameByTime(timeFormatHeader, extension); return createFile(sdcardDirName, fileName); }//獲取文件的MIME public static String getMimeType(String filePath) {final String extension = getExtension(filePath); return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); }//獲取文件的后綴名 public static String getExtension(String filePath) {String suffix = ""; final File file = new File(filePath); final String name = file.getName(); final int idx = name.lastIndexOf('.'); if (idx > 0) {suffix = name.substring(idx + 1); }return suffix; }/** * 保存Bitmap到SD卡中 * * @param dir 目錄名,只需要寫自己的相對目錄名即可 * @param compress 壓縮比例 100是不壓縮,值約小壓縮率越高 * @return 返回該文件 */ public static File saveBitmap(Bitmap mBitmap, String dir, int compress) {final String sdStatus = Environment.getExternalStorageState(); // 檢測sd是否可用 if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {return null; }FileOutputStream fos = null; BufferedOutputStream bos = null; File fileName = createFileByTime(dir, "DOWN_LOAD", "jpg"); try {fos = new FileOutputStream(fileName); bos = new BufferedOutputStream(fos); mBitmap.compress(Bitmap.CompressFormat.JPEG, compress, bos);// 把數據寫入文件 } catch (FileNotFoundException e) {e.printStackTrace(); } finally {try {if (bos != null) {bos.flush(); }if (bos != null) {bos.close(); }//關閉流 if (fos != null) {fos.flush(); }if (fos != null) {fos.close(); }} catch (IOException e) {e.printStackTrace(); }}refreshDCIM(); return fileName; }public static File writeToDisk(InputStream is, String dir, String name) {final File file = FileUtil.createFile(dir, name); BufferedInputStream bis = null; FileOutputStream fos = null; BufferedOutputStream bos = null; try {bis = new BufferedInputStream(is); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); byte data[] = new byte[1024 * 4]; int count; while ((count = bis.read(data)) != -1) {bos.write(data, 0, count); }bos.flush(); fos.flush(); } catch (IOException e) {e.printStackTrace(); } finally {try {if (bos != null) {bos.close(); }if (fos != null) {fos.close(); }if (bis != null) {bis.close(); }is.close(); } catch (IOException e) {e.printStackTrace(); }}return file; }public static File writeToDisk(InputStream is, String dir, String prefix, String extension) {final File file = FileUtil.createFileByTime(dir, prefix, extension); BufferedInputStream bis = null; FileOutputStream fos = null; BufferedOutputStream bos = null; try {bis = new BufferedInputStream(is); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); byte data[] = new byte[1024 * 4]; int count; while ((count = bis.read(data)) != -1) {bos.write(data, 0, count); }bos.flush(); fos.flush(); } catch (IOException e) {e.printStackTrace(); } finally {try {if (bos != null) {bos.close(); }if (fos != null) {fos.close(); }if (bis != null) {bis.close(); }is.close(); } catch (IOException e) {e.printStackTrace(); }}return file; }/** * 通知系統刷新系統相冊,使照片展現出來 */ private static void refreshDCIM() {if (Build.VERSION.SDK_INT >= 19) {//兼容android4.4版本,只掃描存放照片的目錄 MediaScannerConnection.scanFile(disanxue.getApplicationContext(), new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()}, null, null); } else {//掃描整個SD卡來更新系統圖庫,當文件很多時用戶體驗不佳,且不適合4.4以上版本 disanxue.getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" +Environment.getExternalStorageDirectory()))); }}/** * 讀取raw目錄中的文件,并返回為字符串 */ public static String getRawFile(int id) {final InputStream is = disanxue.getApplicationContext().getResources().openRawResource(id); final BufferedInputStream bis = new BufferedInputStream(is); final InputStreamReader isr = new InputStreamReader(bis); final BufferedReader br = new BufferedReader(isr); final StringBuilder stringBuilder = new StringBuilder(); String str; try {while ((str = br.readLine()) != null) {stringBuilder.append(str); }} catch (IOException e) {e.printStackTrace(); } finally {try {br.close(); isr.close(); bis.close(); is.close(); } catch (IOException e) {e.printStackTrace(); }}return stringBuilder.toString(); }public static void setIconFont(String path, TextView textView) {final Typeface typeface = Typeface.createFromAsset(disanxue.getApplicationContext().getAssets(), path); textView.setTypeface(typeface); }/** * 讀取assets目錄下的文件,并返回字符串 */ public static String getAssetsFile(String name) {InputStream is = null; BufferedInputStream bis = null; InputStreamReader isr = null; BufferedReader br = null; StringBuilder stringBuilder = null; final AssetManager assetManager = disanxue.getApplicationContext().getAssets(); try {is = assetManager.open(name); bis = new BufferedInputStream(is); isr = new InputStreamReader(bis); br = new BufferedReader(isr); stringBuilder = new StringBuilder(); String str; while ((str = br.readLine()) != null) {stringBuilder.append(str); }} catch (IOException e) {e.printStackTrace(); } finally {try {if (br != null) {br.close(); }if (isr != null) {isr.close(); }if (bis != null) {bis.close(); }if (is != null) {is.close(); }assetManager.close(); } catch (IOException e) {e.printStackTrace(); }}if (stringBuilder != null) {return stringBuilder.toString(); } else {return null; }}public static String getRealFilePath(final Context context, final Uri uri) {if (null == uri) return null; final String scheme = uri.getScheme(); String data = null; if (scheme == null)data = uri.getPath(); else if (ContentResolver.SCHEME_FILE.equals(scheme)) {data = uri.getPath(); } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {final Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); if (null != cursor) {if (cursor.moveToFirst()) {final int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); if (index > -1) {data = cursor.getString(index); }}cursor.close(); }}return data; } }
總結
以上是生活随笔為你收集整理的Android 各种工的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 炒鸭蛋为什么不脆?
- 下一篇: 软键盘挡住EditText