Android開(kāi)發(fā)中4個(gè)常用的工具類(lèi)【Toast、SharedPreferences、網(wǎng)絡(luò)及屏幕操作】
本文實(shí)例講述了Android開(kāi)發(fā)中4個(gè)常用的工具類(lèi)。分享給大家供大家參考,具體如下:
1、土司工具類(lèi)(Toast管理)
/**
* Toast統(tǒng)一管理類(lèi)
*
* @Project App_ZXing
* @Package com.android.scan
* @author chenlin
* @version 1.0
* @Date 2013年7月6日
* @Note TODO
*/
public class ToastUtil {
private ToastUtil() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
public static boolean isShow = true;
/**
* 短時(shí)間顯示Toast
*
* @param context
* @param message
*/
public static void show(Context context, CharSequence message) {
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
/**
* 短時(shí)間顯示Toast
*
* @param context
* @param message
*/
public static void showShort(Context context, int message) {
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
/**
* 長(zhǎng)時(shí)間顯示Toast
*
* @param context
* @param message
*/
public static void showLong(Context context, CharSequence message) {
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
/**
* 長(zhǎng)時(shí)間顯示Toast
*
* @param context
* @param message
*/
public static void showLong(Context context, int message) {
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
/**
* 自定義顯示Toast時(shí)間
*
* @param context
* @param message
* @param duration
*/
public static void show(Context context, CharSequence message, int duration) {
if (isShow)
Toast.makeText(context, message, duration).show();
}
/**
* 自定義顯示Toast時(shí)間
*
* @param context
* @param message
* @param duration
*/
public static void show(Context context, int message, int duration) {
if (isShow)
Toast.makeText(context, message, duration).show();
}
}
2、SharedPreferences工具類(lèi)
/**
* SharedPreferences封裝類(lèi)SPUtils
* @Project App_ZXing
* @Package com.android.scan
* @author chenlin
* @version 1.0
* @Date 2013年6月6日
* @Note TODO
*/
public class SPUtils {
/**
* 保存在手機(jī)里面的文件名
*/
public static final String FILE_NAME = "share_data";
/**
* 保存數(shù)據(jù)的方法,我們需要拿到保存數(shù)據(jù)的具體類(lèi)型,然后根據(jù)類(lèi)型調(diào)用不同的保存方法
*
* @param context
* @param key
* @param object
*/
public static void put(Context context, 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);
}
/**
* 得到保存數(shù)據(jù)的方法,我們根據(jù)默認(rèn)值得到保存的數(shù)據(jù)的具體類(lèi)型,然后調(diào)用相對(duì)于的方法獲取值
*
* @param context
* @param key
* @param defaultObject
* @return
*/
public static Object get(Context context, 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;
}
/**
* 移除某個(gè)key值已經(jīng)對(duì)應(yīng)的值
*
* @param context
* @param key
*/
public static void remove(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
SharedPreferencesCompat.apply(editor);
}
/**
* 清除所有數(shù)據(jù)
*
* @param context
*/
public static void clear(Context context) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
SharedPreferencesCompat.apply(editor);
}
/**
* 查詢某個(gè)key是否已經(jīng)存在
*
* @param context
* @param key
* @return
*/
public static boolean contains(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
return sp.contains(key);
}
/**
* 返回所有的鍵值對(duì)
*
* @param context
* @return
*/
public static Map<String, ?> getAll(Context context) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
return sp.getAll();
}
/**
* 創(chuàng)建一個(gè)解決SharedPreferencesCompat.apply方法的一個(gè)兼容類(lèi)
*
* @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執(zhí)行,否則使用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();
}
}
}
3、網(wǎng)絡(luò)工具類(lèi)
/**
* 跟網(wǎng)絡(luò)相關(guān)的工具類(lèi)
* @Project App_ZXing
* @Package com.android.scan
* @author chenlin
* @version 1.0
* @Date 2013年6月8日
* @Note TODO
*/
public class NetUtils {
private NetUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 判斷網(wǎng)絡(luò)是否連接
*
* @param context
* @return
*/
public static boolean isConnected(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != connectivity) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (null != info && info.isConnected()) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
/**
* 判斷是否是wifi連接
*/
public static boolean isWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return false;
return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
}
/**
* 打開(kāi)網(wǎng)絡(luò)設(shè)置界面
*/
public static void openSetting(Activity activity) {
Intent intent = new Intent("/");
ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
intent.setComponent(cm);
intent.setAction("android.intent.action.VIEW");
activity.startActivityForResult(intent, 0);
}
}
4、獲得屏幕相關(guān)的輔助類(lèi)
/**
* 獲得屏幕相關(guān)的輔助類(lèi)
* @Project App_ZXing
* @Package com.android.scan
* @author chenlin
* @version 1.0
* @Date 2013年6月6日
*/
public class ScreenUtils {
private ScreenUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 獲得屏幕高度
*
* @param context
* @return
*/
public static int getScreenWidth(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
/**
* 獲得屏幕寬度
*
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
/**
* 獲得狀態(tài)欄的高度
*
* @param context
* @return
*/
public static int getStatusHeight(Context context) {
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
/**
* 獲取當(dāng)前屏幕截圖,包含狀態(tài)欄
*
* @param activity
* @return
*/
public static Bitmap snapShotWithStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
view.destroyDrawingCache();
return bp;
}
/**
* 獲取當(dāng)前屏幕截圖,不包含狀態(tài)欄
*
* @param activity
* @return
*/
public static Bitmap snapShotWithoutStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return bp;
}
}
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android開(kāi)發(fā)入門(mén)與進(jìn)階教程》、《Android視圖View技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android操作SQLite數(shù)據(jù)庫(kù)技巧總結(jié)》、《Android操作json格式數(shù)據(jù)技巧總結(jié)》、《Android資源操作技巧匯總》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
- Android SharedPreferences存取操作以及封裝詳解
- Android 文件存儲(chǔ)與SharedPreferences存儲(chǔ)方式詳解用法
- Android 使用 SharedPreferences 保存少量數(shù)據(jù)的實(shí)現(xiàn)代碼
- Android SharedPreferences實(shí)現(xiàn)記住密碼和自動(dòng)登錄
- Android SharedPreferences實(shí)現(xiàn)保存登錄數(shù)據(jù)功能
- Android數(shù)據(jù)共享 sharedPreferences 的使用方法
- Android中SharedPreferences簡(jiǎn)單使用實(shí)例
- Android中使用SharedPreferences完成記住賬號(hào)密碼的功能
- Android SharedPreferences四種操作模式使用詳解
- 使用SharedPreferences在Android存儲(chǔ)對(duì)象詳細(xì)代碼
相關(guān)文章
Flutter倒計(jì)時(shí)/計(jì)時(shí)器的實(shí)現(xiàn)代碼
這篇文章主要介紹了Flutter倒計(jì)時(shí)/計(jì)時(shí)器的實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
利用Android設(shè)計(jì)一個(gè)倒計(jì)時(shí)組件
在很多電商工作項(xiàng)目中經(jīng)常有倒計(jì)時(shí)的場(chǎng)景,比如活動(dòng)倒計(jì)時(shí)、搶紅包倒計(jì)時(shí)等等,今天小編就帶大家來(lái)學(xué)習(xí)如何利用Android設(shè)計(jì)倒計(jì)時(shí)組件,感興趣的小伙伴一起奧2021-09-09
Android自定義ViewGroup嵌套與交互實(shí)現(xiàn)幕布全屏滾動(dòng)
這篇文章主要為大家介紹了Android自定義ViewGroup嵌套與交互實(shí)現(xiàn)幕布全屏滾動(dòng)效果示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
Android技巧一之啟動(dòng)屏+新功能左右導(dǎo)航邏輯
這篇文章主要介紹了Android技巧一之啟動(dòng)屏+新功能左右導(dǎo)航邏輯的相關(guān)資料,需要的朋友可以參考下2016-01-01
Android Studio 3.5格式化布局代碼時(shí)錯(cuò)位、錯(cuò)亂bug的解決
這篇文章主要介紹了Android Studio 3.5格式化布局代碼時(shí)錯(cuò)位、錯(cuò)亂bug的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03
kotlin 注解 @Parcelize 使用示例和步驟詳解
Parcelable 接口是 Android 中用于在組件之間傳遞對(duì)象的一種方式,在 Kotlin 中,@Parcelize 注解用于簡(jiǎn)化實(shí)現(xiàn) Android Parcelable 接口的過(guò)程,本文給大家分享kotlin 注解 @Parcelize 使用示例,感興趣的朋友一起看看吧2024-06-06
android webview中使用Java調(diào)用JavaScript方法并獲取返回值
這篇文章主要介紹了android webview中使用Java調(diào)用JavaScript方法并獲取返回值,本文直接給出代碼示例,需要的朋友可以參考下2015-03-03

