1. 程式人生 > >Android開發過程中常用到的工具類HttpUtils,SDCardUtils

Android開發過程中常用到的工具類HttpUtils,SDCardUtils

 在開發過程我們最長用到的就是判斷網路是否可用,以及把檔案存到指定目錄下等等,而這如果不專門寫一個工具類,將會非常的不方便,因此,我將我做專案過程中用到的幾個工具類貼出來,需要用的童鞋,可以直接拿去用咯~~~

1.NetWorkUtils.java:

public class NetWorkUtils {     /**      * 判斷網路是否可用      *       * @param context      * @return      */     public static boolean isAvailable(Context context) {         boolean flag = false;         // 構建一個連線管理物件,有多個作用(WIFI, GPRS, UMTS, etc)         // 1. 監視網路的當前狀態         // 2. 當網路發生變化時,可以提供一個通知         // 3. 當一個已連線的網路丟失時,嘗試啟動另外一個網路連線         // 4. 提供一套api來查詢當前網路狀態的好壞         ConnectivityManager manager = (ConnectivityManager) context                 .getSystemService(Context.CONNECTIVITY_SERVICE);         NetworkInfo networkInfo = manager.getActiveNetworkInfo();         if (networkInfo != null) {             flag = networkInfo.isAvailable();         }         return flag;     }     /**      * 判斷網路是否已連線      *       * @param context      * @return      */     public static boolean isNetWorkConnected(Context context) {         boolean flag = false;         ConnectivityManager manager = (ConnectivityManager) context                 .getSystemService(Context.CONNECTIVITY_SERVICE);         NetworkInfo networkInfo = manager.getActiveNetworkInfo();         if (isAvailable(context)) {             flag = networkInfo.isConnected();         }         return flag;     }     /**      * 判斷wifi是否可用      *       * @param context      * @return      */     public static boolean isWIFINetworkAvailable(Context context) {         boolean flag = false;         ConnectivityManager manager = (ConnectivityManager) context                 .getSystemService(Context.CONNECTIVITY_SERVICE);         NetworkInfo networkInfo = manager                 .getNetworkInfo(ConnectivityManager.TYPE_WIFI);         if (networkInfo != null && networkInfo.isConnected()) {             flag = true;         }         return flag;     }     /**      * 判斷mobile網路是否可用      *       * @param context      * @return      */     public static boolean isMOBILENetworkAvailable(Context context) {         boolean flag = false;         ConnectivityManager manager = (ConnectivityManager) context                 .getSystemService(Context.CONNECTIVITY_SERVICE);         NetworkInfo networkInfo = manager                 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);         if (networkInfo != null && networkInfo.isConnected()) {             flag = true;         }         return flag;     }     /**      * 得到當前網路的型別      *       * @param context      * @return      */     public static int getNetworkType(Context context) {         ConnectivityManager manager = (ConnectivityManager) context                 .getSystemService(Context.CONNECTIVITY_SERVICE);         NetworkInfo networkInfo = manager.getActiveNetworkInfo();         if (networkInfo != null)             return networkInfo.getType();         return -1;     }

   /**
     * 判斷網路是否為漫遊
     */
    public static boolean isNetworkRoaming(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            Log.w(LOG_TAG, "couldn't get connectivity manager");
        } else {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null
                    && info.getType() == ConnectivityManager.TYPE_MOBILE) {
                TelephonyManager tm = (TelephonyManager) context
                        .getSystemService(Context.TELEPHONY_SERVICE);
                if (tm != null && tm.isNetworkRoaming()) {
                    Log.d(LOG_TAG, "network is roaming");
                    return true;
                } else {
                    Log.d(LOG_TAG, "network is not roaming");
                }
            } else {
                Log.d(LOG_TAG, "not using mobile network");
            }
        }
        return false;
    }
}

2.SDCardUtils.java:

public class SDCardutils {     public static boolean isMounted(){         boolean flag = false;         flag = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());         return flag;     }     /**      * 獲取SDCard的路徑      * @return      */     public static String getSDCardPath(){         String path = null;         if(isMounted()){             path = Environment.getExternalStorageDirectory().getAbsolutePath();         }         return path;     }     public static long getTotalSize(){         long size = 0;         //StatFs類是用來描述檔案系統的,可以描述整個檔案系統的大小         StatFs sf = new StatFs(getSDCardPath());         Long blockSize = sf.getBlockSizeLong();         Long blockCount = sf.getBlockCountLong();         size = blockCount * blockSize/1024/1024;         return size;     }     public static long getAviableSize(){         long size = 0;         //StatFs類是用來描述檔案系統的,可以描述整個檔案系統的大小         StatFs sf = new StatFs(getSDCardPath());         Long blockSize = sf.getBlockSizeLong();         Long blockCount = sf.getAvailableBlocksLong();         size = blockCount * blockSize/1024/1024;         return size;     }     /**      * 獲取指定公共目錄的路徑      * @param type 可以包含音樂,鈴聲,鬧鐘,相簿,圖片,電影      * @return      */     public static String getPublicPath(String type){         String path = null;         if(isMounted()){             path = Environment.getExternalStoragePublicDirectory(type).getAbsolutePath();         }         return path;     }     /**      * 獲取指定用於應用程式的路徑      * @param context      * @param type      * @return      */     public static String getPrivatePath(Context context,String type){         String path = null;         if(isMounted()){             path = context.getExternalFilesDir(type).getAbsolutePath();         }         return path;     }      /**      * 將data寫入type型別所指向的目錄下名為filaName的檔案中      * @param data      * @param context      * @param fileName      * @param type      * @return true代表寫入成功      */     public static boolean saveData2PrivateSDCard(byte[] data,Context context,String fileName,String type){         boolean flag = false;         if(isMounted()){             File f = new File(getPrivatePath(context, type));             if(!f.exists()){                 f.mkdirs();             }             BufferedOutputStream bos = null;             try {                 bos = new BufferedOutputStream(new FileOutputStream(new File(f,fileName)));                 bos.write(data,0,data.length);                 bos.flush();                 flag = true;             } catch (FileNotFoundException e) {                 e.printStackTrace();             } catch (IOException e) {                 e.printStackTrace();             }         }         return flag;     }      /**          * 將data寫入type型別的公共資料夾中名為filaname的檔案中          * @param data          * @param context          * @param fileName          * @param type          * @return true代表寫入成功          */         public static boolean saveData2PublicSDCard(byte[] data,String fileName,String type){             boolean flag = false;             if(isMounted()){                 File f = new File(getPublicPath(type));                 if(!f.exists()){                     f.mkdirs();                 }                 BufferedOutputStream bos = null;                 try {                     bos = new BufferedOutputStream(new FileOutputStream(new File(f,fileName)));                     bos.write(data,0,data.length);                     bos.flush();                     flag = true;                 } catch (FileNotFoundException e) {                     e.printStackTrace();                 } catch (IOException e) {                     e.printStackTrace();                 }             }             return flag;         }         /**          * 將data存入SDCard根目錄下資料夾名為dir下的檔名為filaName的檔案中          * @param data          * @param dir          * @param fileName          * @return          */         public static boolean saveData2SDCard(byte[] data,String dir,String fileName){             boolean flag = false;             if(isMounted()){                 String path = getSDCardPath()+File.separator+dir;                 File f = new File(path);                 if(!f.exists()){                     f.mkdirs();                 }             }                 BufferedOutputStream bos = null;                 try {                     bos = new BufferedOutputStream(new FileOutputStream(new File(dir,fileName)));                     bos.write(data,0,data.length);                     bos.flush();                     flag = true;                 } catch (FileNotFoundException e) {                     e.printStackTrace();                 } catch (IOException e) {                     e.printStackTrace();                 }             return flag;         }         /**          * 讀取sd卡根目錄地下名為dir資料夾下的名為fileName的檔案的內容          * @param dir          * @param fileName          * @return          */         public static byte[] getDataFromSDCard(String dir,String fileName){             byte[] data = null;             if(isMounted()){                 String path = getSDCardPath()+File.separator+dir+File.separator+fileName;                 File f = new File(path);                 if(f.exists()){                     BufferedInputStream bis = null;                     ByteArrayOutputStream bos = null;                     bos = new ByteArrayOutputStream();                     try {                         bis = new BufferedInputStream(new FileInputStream(f));                         int len = 0;                         byte[] temp = new byte[1024];                         while((len = bis.read(temp)) != -1){                             bos.write(temp,0,len);                             bos.flush();                         }                         data = bos.toByteArray();                     } catch (FileNotFoundException e) {                         // TODO Auto-generated catch block                         e.printStackTrace();                     } catch (IOException e) {                         // TODO Auto-generated catch block                         e.printStackTrace();                     }finally{                         try {                             if(bis != null){                                 bis.close();                             }                         } catch (IOException e) {                             // TODO Auto-generated catch block                             e.printStackTrace();                         }                     }                 }             }             return data;         } }