好些util工具类, 你不用再写重复代码了~~

转载地址 : http://blog.csdn.net/flying_vip_521/article/details/7656413  
通过URL获取图片,优先从本地读取, 如果本地没有联网获取。
Java代码   收藏代码
  1. package com.net.util;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.MalformedURLException;  
  9. import java.net.URL;  
  10. import java.util.ArrayList;  
  11. import java.util.List;  
  12.   
  13. import android.content.Context;  
  14. import android.graphics.Bitmap;  
  15. import android.graphics.BitmapFactory;  
  16. import android.os.Environment;  
  17. import android.util.Log;  
  18. /** 
  19.  * 图片下载工具类 
  20.  *  
  21.  * @author gaozhibin 
  22.  * 
  23.  */  
  24. public class BitmapUtil {  
  25.     private static final String TAG = "BtimapUtil";  
  26.       
  27.   
  28.     /** 
  29.      * 根据网址获得图片,优先从本地获取,本地没有则从网络下载 
  30.      *  
  31.      * @param url  图片网址 
  32.      * @param context 上下文 
  33.      * @return 图片 
  34.      */  
  35.     public static Bitmap getBitmap(String url,Context context){  
  36.         Log.e(TAG, "------url="+url);  
  37.         String imageName= url.substring(url.lastIndexOf("/")+1, url.length());  
  38.         File file = new File(getPath(context),imageName);  
  39.         if(file.exists()){  
  40.             Log.e(TAG, "getBitmap from Local");  
  41.             return BitmapFactory.decodeFile(file.getPath());  
  42.         }  
  43.         return getNetBitmap(url,file,context);  
  44.     }  
  45.       
  46.     /** 
  47.      * 根据传入的list中保存的图片网址,获取相应的图片列表 
  48.      *  
  49.      * @param list  保存图片网址的列表 
  50.      * @param context 上下文 
  51.      * @return 图片列表 
  52.      */  
  53.     public static List<Bitmap> getBitmap(List<String> list,Context context){  
  54.         List<Bitmap> result = new ArrayList<Bitmap>();  
  55.         for(String strUrl : list){  
  56.             Bitmap bitmap = getBitmap(strUrl,context);  
  57.             if(bitmap!=null){  
  58.                 result.add(bitmap);  
  59.             }  
  60.         }  
  61.         return result;  
  62.     }  
  63.   
  64.     /** 
  65.      * 获取图片的存储目录,在有sd卡的情况下为 “/sdcard/apps_images/本应用包名/cach/images/” 
  66.      * 没有sd的情况下为“/data/data/本应用包名/cach/images/” 
  67.      *  
  68.      * @param context 上下文 
  69.      * @return 本地图片存储目录 
  70.      */  
  71.     private static String getPath(Context context){  
  72.         String path = null;  
  73.         boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);  
  74.         String packageName = context.getPackageName()+"/cach/images/";  
  75.         if(hasSDCard){  
  76.             path="/sdcard/apps_images/"+packageName;  
  77.         }else{  
  78.             path="/data/data/"+packageName;       
  79.         }    
  80.         File file = new File(path);  
  81.         boolean isExist = file.exists();  
  82.         if(!isExist){  
  83.               
  84.             file.mkdirs();  
  85.               
  86.         }  
  87.         return file.getPath();  
  88.     }  
  89.   
  90.     /** 
  91.      * 网络可用状态下,下载图片并保存在本地 
  92.      *  
  93.      * @param strUrl 图片网址 
  94.      * @param file 本地保存的图片文件 
  95.      * @param context  上下文 
  96.      * @return 图片 
  97.      */  
  98.     private static Bitmap getNetBitmap(String strUrl,File file,Context context) {  
  99.         Log.e(TAG, "getBitmap from net");  
  100.         Bitmap bitmap = null;  
  101.         if(NetUtil.isConnnected(context)){  
  102.             try {  
  103.                 URL url = new URL(strUrl);  
  104.                 HttpURLConnection con = (HttpURLConnection) url.openConnection();  
  105.                 con.setDoInput(true);  
  106.                 con.connect();  
  107.                 InputStream in = con.getInputStream();  
  108.                 bitmap = BitmapFactory.decodeStream(in);  
  109.                 FileOutputStream out = new FileOutputStream(file.getPath());  
  110.                 bitmap.compress(Bitmap.CompressFormat.PNG,100, out);  
  111.                 out.flush();  
  112.                 out.close();  
  113.                 in.close();  
  114.             } catch (MalformedURLException e) {  
  115.                 e.printStackTrace();  
  116.             } catch (IOException e) {  
  117.                 e.printStackTrace();  
  118.             } finally{  
  119.                   
  120.             }             
  121.         }  
  122.         return bitmap;  
  123.     }  
  124.       
  125. }  

Android 之 远程图片获取和本地缓存 
转载地址 : http://blog.csdn.net/xieqibao/article/details/6682128  

Java代码   收藏代码
  1. package com.net.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.UnsupportedEncodingException;  
  5. import java.util.List;  
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.HttpStatus;  
  8. import org.apache.http.NameValuePair;  
  9. import org.apache.http.client.ClientProtocolException;  
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  11. import org.apache.http.client.methods.HttpGet;  
  12. import org.apache.http.client.methods.HttpPost;  
  13. import org.apache.http.client.methods.HttpUriRequest;  
  14. import org.apache.http.impl.client.DefaultHttpClient;  
  15. import org.apache.http.util.EntityUtils;  
  16. import org.json.JSONException;  
  17. import org.json.JSONObject;  
  18. import android.content.Context;  
  19. import android.net.ConnectivityManager;  
  20. import android.net.NetworkInfo;  
  21. import android.util.Log;  
  22. import android.widget.Toast;  
  23.   
  24. public class NetUtil {  
  25.     private static final String TAG = "NetUtil";  
  26.   
  27.     /** 
  28.      * 网络连接是否可用 
  29.      */  
  30.     public static boolean isConnnected(Context context) {  
  31.         ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  32.         if (null != connectivityManager) {  
  33.             NetworkInfo networkInfo[] = connectivityManager.getAllNetworkInfo();  
  34.   
  35.             if (null != networkInfo) {  
  36.                 for (NetworkInfo info : networkInfo) {  
  37.                     if (info.getState() == NetworkInfo.State.CONNECTED) {  
  38.                         Log.e(TAG, "the net is ok");  
  39.                         return true;  
  40.                     }  
  41.                 }  
  42.             }  
  43.         }  
  44.         Toast.makeText(context, "网络连接失败", Toast.LENGTH_SHORT).show();  
  45.         return false;  
  46.     }  
  47.   
  48.     /** 
  49.      * 网络可用状态下,通过get方式向server端发送请求,并返回响应数据 
  50.      *  
  51.      * @param strUrl 请求网址 
  52.      * @param context 上下文 
  53.      * @return 响应数据 
  54.      */  
  55.     public static JSONObject getResponseForGet(String strUrl, Context context) {  
  56.         if (isConnnected(context)) {  
  57.             return getResponseForGet(strUrl);  
  58.         }  
  59.         return null;  
  60.     }  
  61.   
  62.     /** 
  63.      * 通过Get方式处理请求,并返回相应数据 
  64.      *  
  65.      * @param strUrl 请求网址 
  66.      * @return 响应的JSON数据 
  67.      */  
  68.     public static JSONObject getResponseForGet(String strUrl) {  
  69.         HttpGet httpRequest = new HttpGet(strUrl);  
  70.         return getRespose(httpRequest);  
  71.     }  
  72.   
  73.     /** 
  74.      * 网络可用状态下,通过post方式向server端发送请求,并返回响应数据 
  75.      *  
  76.      * @param market_uri 请求网址 
  77.      * @param nameValuePairs 参数信息 
  78.      * @param context 上下文 
  79.      * @return 响应数据 
  80.      */  
  81.     public static JSONObject getResponseForPost(String market_uri, List<NameValuePair> nameValuePairs, Context context) {  
  82.         if (isConnnected(context)) {  
  83.             return getResponseForPost(market_uri, nameValuePairs);  
  84.         }  
  85.         return null;  
  86.     }  
  87.   
  88.     /** 
  89.      * 通过post方式向服务器发送请求,并返回响应数据 
  90.      *  
  91.      * @param strUrl 请求网址 
  92.      * @param nameValuePairs 参数信息 
  93.      * @return 响应数据 
  94.      */  
  95.     public static JSONObject getResponseForPost(String market_uri, List<NameValuePair> nameValuePairs) {  
  96.         if (null == market_uri || "" == market_uri) {  
  97.             return null;  
  98.         }  
  99.         HttpPost request = new HttpPost(market_uri);  
  100.         try {  
  101.             request.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
  102.             return getRespose(request);  
  103.         } catch (UnsupportedEncodingException e1) {  
  104.             e1.printStackTrace();  
  105.         }  
  106.         return null;  
  107.     }  
  108.   
  109.     /** 
  110.      * 响应客户端请求 
  111.      *  
  112.      * @param request 客户端请求get/post 
  113.      * @return 响应数据 
  114.      */  
  115.     public static JSONObject getRespose(HttpUriRequest request) {  
  116.         try {  
  117.             HttpResponse httpResponse = new DefaultHttpClient().execute(request);  
  118.             int statusCode = httpResponse.getStatusLine().getStatusCode();  
  119.             if (HttpStatus.SC_OK == statusCode) {  
  120.                 String result = EntityUtils.toString(httpResponse.getEntity());  
  121.                 Log.i(TAG, "results=" + result);  
  122.                 return new JSONObject(result);  
  123.             }  
  124.         } catch (ClientProtocolException e) {  
  125.             e.printStackTrace();  
  126.         } catch (IOException e) {  
  127.             e.printStackTrace();  
  128.         } catch (JSONException e) {  
  129.             e.printStackTrace();  
  130.         }  
  131.         return null;  
  132.     }  
  133. }  


Log输出到sdcard工具类 
转载地址:http://blog.csdn.net/flying_vip_521/article/details/7652572 
Java代码   收藏代码
  1. package com.innofidei;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.Date;  
  7.   
  8. public class LocatUtil {  
  9.     private static String logToFileCommand = "logcat -v time -f ";  
  10.   
  11.     public static void startLog(String saveiDir, String fileName) {  
  12.         SimpleDateFormat format = new SimpleDateFormat("yyMMdd_HHmmss");  
  13.         String nowStr = format.format(new Date());  
  14.         fileName = fileName + "_" + nowStr + ".txt";  
  15.         new File(saveiDir).mkdirs();  
  16.         try {  
  17.             Runtime.getRuntime().exec(logToFileCommand + saveiDir + fileName);  
  18.         } catch (IOException e) {  
  19.             e.printStackTrace();  
  20.         }  
  21.     }  
  22. }  


GSPUtil 
Java代码   收藏代码
  1. package org.join.weather.util;  
  2.   
  3.   
  4. import java.util.List;  
  5.   
  6.   
  7. import org.join.weather.WeatherActivity;  
  8. import org.join.weather.WeatherActivity.OnActivityResumeAndPauseListener;  
  9.   
  10.   
  11. import android.app.AlertDialog;  
  12. import android.content.Context;  
  13. import android.content.Intent;  
  14. import android.location.Address;  
  15. import android.location.Criteria;  
  16. import android.location.Geocoder;  
  17. import android.location.Location;  
  18. import android.location.LocationListener;  
  19. import android.location.LocationManager;  
  20. import android.os.Bundle;  
  21. import android.os.Handler;  
  22. import android.os.Message;  
  23. import android.preference.PreferenceManager.OnActivityResultListener;  
  24. import android.provider.Settings;  
  25. import android.util.Log;  
  26. import android.widget.Toast;  
  27.   
  28.   
  29. public class GPSUtil implements OnActivityResultListener,  
  30.         OnActivityResumeAndPauseListener {  
  31.   
  32.   
  33.     // WeatherActivity对象  
  34.     private WeatherActivity weatherActivity;  
  35.     // LocationManager对象  
  36.     private LocationManager locationManager;  
  37.     // Location对象  
  38.     private Location location;  
  39.     // 当前位置提供者  
  40.     private String provider;  
  41.   
  42.   
  43.     // 时间(秒)  
  44.     private long minTime = 60 * 1000;  
  45.     // 距离(米)  
  46.     private float minDistance = 500;  
  47.     // 定位方式  
  48.     private int mode = 1;  
  49.   
  50.   
  51.     // 位置监听接口  
  52.     private LocationListener mLocationListener = new LocationListener() {  
  53.   
  54.   
  55.         @Override  
  56.         public void onLocationChanged(final Location loc) {  
  57.             // 当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发  
  58.             Log.v("onLocationChanged""=onLocationChanged");  
  59.   
  60.   
  61.             if (loc != null) {  
  62.                 location = loc;  
  63.                 showLocationInfo(loc);  
  64.             } else {  
  65.                 Toast.makeText(weatherActivity, "当前位置不可定位!", Toast.LENGTH_SHORT)  
  66.                         .show();  
  67.                 // 注销监听事件  
  68.                 // locationManager.removeUpdates(mLocationListener);  
  69.             }  
  70.         }  
  71.   
  72.   
  73.         @Override  
  74.         public void onProviderDisabled(String provider) {  
  75.             // Provider被disable时触发此函数,比如GPS被关闭  
  76.             Log.v("onProviderDisabled""=onProviderDisabled");  
  77.         }  
  78.   
  79.   
  80.         @Override  
  81.         public void onProviderEnabled(String provider) {  
  82.             // Provider被enable时触发此函数,比如GPS被打开  
  83.             Log.v("onProviderEnabled""=onProviderEnabled");  
  84.         }  
  85.   
  86.   
  87.         @Override  
  88.         public void onStatusChanged(String provider, int status, Bundle extras) {  
  89.             // Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数  
  90.             Log.v("onStatusChanged""=onStatusChanged");  
  91.         }  
  92.     };  
  93.   
  94.   
  95.     // 超时注销服务  
  96.     private Handler myHandler = new Handler() {  
  97.   
  98.   
  99.         @Override  
  100.         public void handleMessage(Message msg) {  
  101.             if (null == location) {  
  102.                 // 提示信息  
  103.                 Toast.makeText(weatherActivity, "当前位置不可定位!", Toast.LENGTH_SHORT)  
  104.                         .show();  
  105.             }  
  106.             // 注销监听事件  
  107.             locationManager.removeUpdates(mLocationListener);  
  108.         }  
  109.   
  110.   
  111.     };  
  112.   
  113.   
  114.     public GPSUtil(WeatherActivity weatherActivity, int mode) {  
  115.         this.weatherActivity = weatherActivity;  
  116.         weatherActivity.setOnActivityResultListener(this);  
  117.         weatherActivity.setOnResumeAndPauseListener(this);  
  118.         this.mode = mode;  
  119.   
  120.   
  121.         // 获得LocationManager服务  
  122.         locationManager = (LocationManager) weatherActivity  
  123.                 .getSystemService(Context.LOCATION_SERVICE);  
  124.   
  125.   
  126.         if (openGPSSettings()) {  
  127.             setLocationServer(mode);  
  128.         } else {  
  129.             Toast.makeText(weatherActivity, "请开启GPS!", Toast.LENGTH_SHORT)  
  130.                     .show();  
  131.             Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);  
  132.             // 此为设置完成后返回到获取界面  
  133.             weatherActivity.startActivityForResult(intent, 0);  
  134.         }  
  135.   
  136.   
  137.     }  
  138.   
  139.   
  140.     public GPSUtil(WeatherActivity weatherActivity, int mode, long minTime,  
  141.             float minDistance) {  
  142.         this(weatherActivity, mode);  
  143.         this.minTime = minTime;  
  144.         this.minDistance = minDistance;  
  145.     }  
  146.   
  147.   
  148.     // 判断GPS模块是否存在或者是开启  
  149.     private boolean openGPSSettings() {  
  150.         if (locationManager  
  151.                 .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {  
  152.             return true;  
  153.         }  
  154.         return false;  
  155.     }  
  156.   
  157.   
  158.     // 更新当前位置信息(如果使用GPS,需要保证在室外,并且没有大建筑物遮挡,如果使用网络定位,要保证网络通畅)  
  159.     public void setLocationServer(int mode) {  
  160.   
  161.   
  162.         Toast.makeText(weatherActivity, "正在定位!", Toast.LENGTH_SHORT).show();  
  163.   
  164.   
  165.         switch (mode) {  
  166.         case 1: {  
  167.             // GPS定位  
  168.             if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {  
  169.                 provider = LocationManager.GPS_PROVIDER;  
  170.                 location = locationManager.getLastKnownLocation(provider);  
  171.                 // 设置监听器,自动更新的最小时间为间隔N秒或最小位移变化超过N米  
  172.                 locationManager.requestLocationUpdates(provider, minTime,  
  173.                         minDistance, mLocationListener);  
  174.                 Log.v("GPS定位""GPS定位!");  
  175.             } else {  
  176.                 Log.v("GPS定位""未提供GPS定位功能!");  
  177.             }  
  178.             break;  
  179.         }  
  180.         case 2: {  
  181.             // NETWORK定位  
  182.             provider = LocationManager.NETWORK_PROVIDER;  
  183.             location = locationManager.getLastKnownLocation(provider);  
  184.             // 设置监听器,自动更新的最小时间为间隔N秒或最小位移变化超过N米  
  185.             locationManager.requestLocationUpdates(provider, minTime,  
  186.                     minDistance, mLocationListener);  
  187.             Log.v("NETWORK定位""NETWORK定位!");  
  188.             break;  
  189.         }  
  190.         case 3: {  
  191.             // 查询符合条件的Location Provider来定位  
  192.   
  193.   
  194.             // 获得Criteria对象(指定条件参数)  
  195.             Criteria criteria = new Criteria();  
  196.             // 获得最好的单位效果  
  197.             criteria.setAccuracy(Criteria.ACCURACY_FINE);  
  198.             criteria.setAltitudeRequired(false);  
  199.             criteria.setBearingRequired(false);  
  200.             criteria.setCostAllowed(false);  
  201.             // 使用省电模式  
  202.             criteria.setPowerRequirement(Criteria.POWER_LOW);  
  203.             // 获得当前位置的提供者  
  204.             provider = locationManager.getBestProvider(criteria, true);  
  205.             // 获得当前位置  
  206.             location = locationManager.getLastKnownLocation(provider);  
  207.   
  208.   
  209.             if (null != provider) {  
  210.                 // 设置监听器,自动更新的最小时间为间隔N秒或最小位移变化超过N米  
  211.                 locationManager.requestLocationUpdates(provider, minTime,  
  212.                         minDistance, mLocationListener);  
  213.             } else {  
  214.                 Log.v("provider""null == provider");  
  215.             }  
  216.             Log.v("最优定位", provider);  
  217.             break;  
  218.         }  
  219.         }  
  220.   
  221.   
  222.         if (null != location) {  
  223.             showLocationInfo(location);  
  224.         }  
  225.         // 延迟10秒  
  226.         myHandler.sendEmptyMessageDelayed(010 * 1000);  
  227.     }  
  228.   
  229.   
  230.     // 显示定位信息  
  231.     private void showLocationInfo(Location loc) {  
  232.   
  233.   
  234.         String msg = "";  
  235.   
  236.   
  237.         try {  
  238.             msg = "经度:" + location.getLongitude() + "\n";  
  239.             msg += "纬度:" + location.getLatitude() + "\n";  
  240.             Geocoder gc = new Geocoder(weatherActivity);  
  241.             List<Address> addresses = gc.getFromLocation(  
  242.                     location.getLatitude(), location.getLongitude(), 1);  
  243.             // 相关信息  
  244.             if (addresses.size() > 0) {  
  245.                 msg += "AddressLine:" + addresses.get(0).getAddressLine(0)  
  246.                         + "\n";  
  247.                 msg += "CountryName:" + addresses.get(0).getCountryName()  
  248.                         + "\n";  
  249.                 msg += "Locality:" + addresses.get(0).getLocality() + "\n";  
  250.                 msg += "FeatureName:" + addresses.get(0).getFeatureName();  
  251.             }  
  252.         } catch (Exception e) {  
  253.             msg = e.getMessage();  
  254.         }  
  255.   
  256.   
  257.         new AlertDialog.Builder(weatherActivity).setMessage(msg)  
  258.                 .setPositiveButton("确定"null).show();  
  259.     }  
  260.   
  261.   
  262.     @Override  
  263.     public boolean onActivityResult(int requestCode, int resultCode, Intent data) {  
  264.         // 从设置GPS的Activity返回时  
  265.         if (0 == requestCode) {  
  266.             if (openGPSSettings()) {  
  267.                 setLocationServer(mode);  
  268.             } else {  
  269.                 Toast.makeText(weatherActivity, "GPS仍未开启!", Toast.LENGTH_SHORT)  
  270.                         .show();  
  271.             }  
  272.         }  
  273.         return false;  
  274.     }  
  275.   
  276.   
  277.     // 在Activity恢复活动时,响应位置更新  
  278.     @Override  
  279.     public void onResume() {  
  280.         if (null != provider) {  
  281.             locationManager.requestLocationUpdates(provider, minTime,  
  282.                     minDistance, mLocationListener);  
  283.         }  
  284.     }  
  285.   
  286.   
  287.     // 在Activity暂停活动时,取消位置更新  
  288.     @Override  
  289.     public void onPause() {  
  290.         if (null != locationManager) {  
  291.             locationManager.removeUpdates(mLocationListener);  
  292.         }  
  293.     }  
  294.   
  295.   
  296. }  


WebService for Android  

获取手机ip地址工具类 
Java代码   收藏代码
  1. package com.innofidei.location;  
  2.   
  3. import java.net.InetAddress;  
  4. import java.net.UnknownHostException;  
  5.   
  6. import android.content.Context;  
  7. import android.net.wifi.WifiManager;  
  8.   
  9. public class AdressUtil {  
  10.     public String getIp(Context myContext) {  
  11.         InetAddress address = getWifiIp(myContext);  
  12.         if (address != null) {  
  13.             return address.getHostAddress();  
  14.         }  
  15.         return null;  
  16.     }  
  17.   
  18.     private InetAddress getWifiIp(Context myContext) {  
  19.         if (myContext == null) {  
  20.             throw new NullPointerException("Global context is null");  
  21.         }  
  22.         WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);  
  23.         if (isWifiEnabled(myContext)) {  
  24.             int ipAsInt = wifiMgr.getConnectionInfo().getIpAddress();  
  25.             if (ipAsInt == 0) {  
  26.                 return null;  
  27.             } else {  
  28.                 return intToInet(ipAsInt);  
  29.             }  
  30.         } else {  
  31.             return null;  
  32.         }  
  33.     }  
  34.   
  35.     private boolean isWifiEnabled(Context myContext) {  
  36.         if (myContext == null) {  
  37.             throw new NullPointerException("Global context is null");  
  38.         }  
  39.         WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);  
  40.         if (wifiMgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {  
  41.             return true;  
  42.         } else {  
  43.             return false;  
  44.         }  
  45.     }  
  46.   
  47.     private InetAddress intToInet(int value) {  
  48.         byte[] bytes = new byte[4];  
  49.         for (int i = 0; i < 4; i++) {  
  50.             bytes[i] = byteOfInt(value, i);  
  51.         }  
  52.         try {  
  53.             return InetAddress.getByAddress(bytes);  
  54.         } catch (UnknownHostException e) {  
  55.             // This only happens if the byte array has a bad length  
  56.             return null;  
  57.         }  
  58.     }  
  59.   
  60.     private byte byteOfInt(int value, int which) {  
  61.         int shift = which * 8;  
  62.         return (byte) (value >> shift);  
  63.     }  
  64. }  


工具类:字符串处理  
工具类:日期处理  
工具类:加密(java)  
工具类:判断一个类是否是给定类的子类 
Java代码   收藏代码
  1. public class ClassUtils {  
  2.   
  3.     /** 
  4.      * Checks if a class is a subclass of a class with the specified name. Used 
  5.      * as an instanceOf without having to load the class, useful when trying to 
  6.      * check for classes that might not be available in the runtime JRE. 
  7.      *  
  8.      * @param clazz 
  9.      *            The class to check 
  10.      * @param className 
  11.      *            The class name to look for in the super classes 
  12.      * @return true if the class extends a class by the specified name. 
  13.      */  
  14.     public static boolean extendsClass(final Class<?> clazz, String className) {  
  15.         Class<?> superClass = clazz.getSuperclass();  
  16.   
  17.         while (superClass != null) {  
  18.             if (superClass.getName().equals(className)) {  
  19.                 return true;  
  20.             }  
  21.             superClass = superClass.getSuperclass();  
  22.   
  23.         }  
  24.         return false;  
  25.     }  
  26. }  


android时时监听log  

Android中StatFs获取系统/sdcard存储(剩余空间)大小  
在存储文件时,为了保证有充足的剩余空间大小,通常需要知道系统内部或者sdcard的存储大小。 
Java代码   收藏代码
  1. import java.io.File;  
  2.   
  3. import android.os.Environment;  
  4. import android.os.StatFs;  
  5.   
  6. public class MemoryStatus {  
  7.     static final int ERROR = -1;  
  8.   
  9.     /** 
  10.      * 外部存储是否可用 
  11.      * @return 
  12.      */  
  13.     static public boolean externalMemoryAvailable() {  
  14.         return android.os.Environment.getExternalStorageState().equals(  
  15.                 android.os.Environment.MEDIA_MOUNTED);  
  16.     }  
  17.   
  18.     /** 
  19.      * 获取手机内部可用空间大小 
  20.      * @return 
  21.      */  
  22.     static public long getAvailableInternalMemorySize() {  
  23.         File path = Environment.getDataDirectory();  
  24.         StatFs stat = new StatFs(path.getPath());  
  25.         long blockSize = stat.getBlockSize();  
  26.         long availableBlocks = stat.getAvailableBlocks();  
  27.         return availableBlocks * blockSize;  
  28.     }  
  29.   
  30.     /** 
  31.      * 获取手机内部空间大小 
  32.      * @return 
  33.      */  
  34.     static public long getTotalInternalMemorySize() {  
  35.         File path = Environment.getDataDirectory();  
  36.         StatFs stat = new StatFs(path.getPath());  
  37.         long blockSize = stat.getBlockSize();  
  38.         long totalBlocks = stat.getBlockCount();  
  39.         return totalBlocks * blockSize;  
  40.     }  
  41.   
  42.     /** 
  43.      * 获取手机外部可用空间大小 
  44.      * @return 
  45.      */  
  46.     static public long getAvailableExternalMemorySize() {  
  47.         if (externalMemoryAvailable()) {  
  48.             File path = Environment.getExternalStorageDirectory();  
  49.             StatFs stat = new StatFs(path.getPath());  
  50.             long blockSize = stat.getBlockSize();  
  51.             long availableBlocks = stat.getAvailableBlocks();  
  52.             return availableBlocks * blockSize;  
  53.         } else {  
  54.             return ERROR;  
  55.         }  
  56.     }  
  57.   
  58.     /** 
  59.      * 获取手机外部空间大小 
  60.      * @return 
  61.      */  
  62.     static public long getTotalExternalMemorySize() {  
  63.         if (externalMemoryAvailable()) {  
  64.             File path = Environment.getExternalStorageDirectory();  
  65.             StatFs stat = new StatFs(path.getPath());  
  66.             long blockSize = stat.getBlockSize();  
  67.             long totalBlocks = stat.getBlockCount();  
  68.             return totalBlocks * blockSize;  
  69.         } else {  
  70.             return ERROR;  
  71.         }  
  72.     }  
  73.   
  74.     static public String formatSize(long size) {  
  75.         String suffix = null;  
  76.   
  77.         if (size >= 1024) {  
  78.             suffix = "KiB";  
  79.             size /= 1024;  
  80.             if (size >= 1024) {  
  81.                 suffix = "MiB";  
  82.                 size /= 1024;  
  83.             }  
  84.         }  
  85.   
  86.         StringBuilder resultBuffer = new StringBuilder(Long.toString(size));  
  87.         int commaOffset = resultBuffer.length() - 3;  
  88.         while (commaOffset > 0) {  
  89.             resultBuffer.insert(commaOffset, ',');  
  90.             commaOffset -= 3;  
  91.         }  
  92.   
  93.         if (suffix != null)  
  94.             resultBuffer.append(suffix);  
  95.         return resultBuffer.toString();  
  96.     }  
  97. }  
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值