Android開發(fā)之超實(shí)用的系統(tǒng)管理工具類【SD卡,網(wǎng)絡(luò),uri,屏幕,網(wǎng)絡(luò),軟鍵盤,文本,進(jìn)程等】
本文實(shí)例講述了Android開發(fā)之超實(shí)用的系統(tǒng)管理工具類。分享給大家供大家參考,具體如下:
這是一個(gè)系統(tǒng)管理工具類,管理sd卡,判斷網(wǎng)絡(luò),uri轉(zhuǎn)換,獲取屏幕寬高,獲取網(wǎng)絡(luò)類型,隱藏軟鍵盤,復(fù)制文本到粘貼板,獲取狀態(tài)欄高度,獲取當(dāng)前進(jìn)程等。
上代碼
import java.io.File;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
@SuppressWarnings("deprecation")
public class SystemUtil {
public static final int NETTYPE_WIFI = 0x01;
public static final int NETTYPE_CMWAP = 0x02;
public static final int NETTYPE_CMNET = 0x03;
/** 判斷是否手機(jī)插入Sd卡 */
public static boolean sdCardUseable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
/**
* 獲取Sd卡的總?cè)萘?
*
* @return
*/
@SuppressLint("NewApi") public static long getSdCardTotalSize() {
if(!sdCardUseable()){
return 0;
}
// 取得SD卡文件路徑
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
// 獲取單個(gè)數(shù)據(jù)塊的大小(Byte)
long blockSize = sf.getBlockSizeLong();
// 獲取所有數(shù)據(jù)塊數(shù)
long allBlocks = sf.getBlockCountLong();
// 返回SD卡大小
// return allBlocks * blockSize; //單位Byte
// return (allBlocks * blockSize)/1024; //單位KB
return (allBlocks * blockSize) / 1024 / 1024; // 單位MB
}
/**
* 獲取Sd卡的可用容量
*
* @return
*/
@SuppressLint("NewApi") public static long getSdCardFreeSize() {
if(!sdCardUseable()){
return 0;
}
// 取得SD卡文件路徑
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
// 獲取單個(gè)數(shù)據(jù)塊的大小(Byte)
long blockSize = sf.getBlockSizeLong();
// 空閑的數(shù)據(jù)塊的數(shù)量
long freeBlocks = sf.getAvailableBlocksLong();
// 返回SD卡空閑大小
// return freeBlocks * blockSize; //單位Byte
// return (freeBlocks * blockSize)/1024; //單位KB
return (freeBlocks * blockSize) / 1024 / 1024; // 單位MB
}
/**
* 判斷是否聯(lián)網(wǎng)或者漫游
*
* @param context
* @return boolean
*/
public static boolean hasNet(Context context) {
// 獲得ConnectivityManager的管理器
NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) { // 漫游判斷
return true;
}
return true;
}
/** 獲得The data stream for the file */
public static String getUrlPath(Activity context, Uri uri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.managedQuery(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/** 從傳入U(xiǎn)ri獲得真實(shí)的path */
public String getRealPathFromURI(Activity context, Uri contentUri) {
// can post image
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.managedQuery(contentUri, proj, // Which columns
// to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/** 獲得屏幕的寬度 */
public static int getScreenWidth(Activity context) {
DisplayMetrics outMetrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
/** 獲取屏幕的高度 */
public static int getScreenHeight(Activity context) {
DisplayMetrics outMetrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
/** 獲得網(wǎng)絡(luò)的類型 */
public static int getNetworkType(Context context) {
int netType = 0;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null) { // 判斷是否聯(lián)網(wǎng)
return netType;
}
int nType = networkInfo.getType(); // 獲得
if (nType == ConnectivityManager.TYPE_MOBILE) {
String extraInfo = networkInfo.getExtraInfo();
if (!TextUtils.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;
}
/** 隱藏軟件盤 */
public static void hideSoftKeyborad(Activity context) {
final View v = context.getWindow().peekDecorView(); // Retrieve the
// current decor
// view
if (v != null && v.getWindowToken() != null) {
InputMethodManager imm = (InputMethodManager) context // 獲得輸入方法的Manager
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
/**
* 復(fù)制文本到剪切板
*
* @param context
* @param text
*/
@TargetApi(value = 11)
@SuppressLint({ "NewApi", "NewApi" })
public static void copyText(Context context, String text) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("label", text);
clipboardManager.setPrimaryClip(clipData);
} else {
android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(text);
}
}
/**
* 獲取狀態(tài)欄高度
*
* @return
*/
public static int getStatusBarHeight(Context context) {
Class<?> c = null;
Object obj = null;
java.lang.reflect.Field field = null;
int x = 0;
int statusBarHeight = 0;
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(x);
return statusBarHeight;
} catch (Exception e) {
e.printStackTrace();
}
return statusBarHeight;
}
/**
* 獲取當(dāng)前進(jìn)程名
* @param context
* @return 進(jìn)程名
*/
public static final String getProcessName(Context context) {
String processName = null;
// ActivityManager
ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
while (true) {
for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
if (info.pid == android.os.Process.myPid()) {
processName = info.processName;
break;
}
}
// go home
if (!TextUtils.isEmpty(processName)) {
return processName;
}
// take a rest and again
try {
Thread.sleep(100L);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android開發(fā)入門與進(jìn)階教程》、《Android調(diào)試技巧與常見問題解決方法匯總》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
相關(guān)文章
Android面試Intent采用了什么設(shè)計(jì)模式解析
這篇文章主要為大家介紹了Android面試Intent采用了什么設(shè)計(jì)模式解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
Android實(shí)現(xiàn)多點(diǎn)觸控功能
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)多點(diǎn)觸控功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05
Android8.0適配前臺(tái)定位服務(wù)service的示例代碼
這篇文章主要介紹了Android8.0適配前臺(tái)定位服務(wù)service的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2018-07-07
Android DatePicker和DatePickerDialog基本用法示例
這篇文章主要介紹了Android DatePicker和DatePickerDialog基本用法,實(shí)例分析了DatePicker和DatePickerDialog控件針對(duì)手機(jī)時(shí)間設(shè)置的相關(guān)技巧,需要的朋友可以參考下2016-06-06
外層豎向ScrollView,里層橫向ScrollView滑動(dòng)沖突的解決方法
下面小編就為大家?guī)?lái)一篇外層豎向ScrollView,里層橫向ScrollView滑動(dòng)沖突的解決方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2017-04-04
淺析Android手機(jī)衛(wèi)士手機(jī)定位的原理
手機(jī)定位的三種方式:網(wǎng)絡(luò)定位,基站定位,GPS定位。本文給大家介紹Android手機(jī)衛(wèi)士手機(jī)定位的原理,感興趣的朋友一起學(xué)習(xí)吧2016-04-04
Android自動(dòng)測(cè)試工具M(jìn)onkey的實(shí)現(xiàn)方法
本文主要介紹Android Monkey 實(shí)現(xiàn)方法,Monkey測(cè)試是一種為了測(cè)試軟件的穩(wěn)定性、健壯性的快速有效的方法,具有非常重要的參考價(jià)值,希望對(duì)小伙伴有所幫助2016-07-07

