`

图片下载工具类:BitmapUtil 等小工具类

阅读更多
http://blog.csdn.net/flying_vip_521/article/details/7656413
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. }  
package com.net.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
/**
 * 图片下载工具类
 * 
 * @author gaozhibin
 *
 */
public class BitmapUtil {
	private static final String TAG = "BtimapUtil";
	

	/**
	 * 根据网址获得图片,优先从本地获取,本地没有则从网络下载
	 * 
	 * @param url  图片网址
	 * @param context 上下文
	 * @return 图片
	 */
	public static Bitmap getBitmap(String url,Context context){
		Log.e(TAG, "------url="+url);
		String imageName= url.substring(url.lastIndexOf("/")+1, url.length());
		File file = new File(getPath(context),imageName);
		if(file.exists()){
			Log.e(TAG, "getBitmap from Local");
			return BitmapFactory.decodeFile(file.getPath());
		}
		return getNetBitmap(url,file,context);
	}
	
	/**
	 * 根据传入的list中保存的图片网址,获取相应的图片列表
	 * 
	 * @param list  保存图片网址的列表
	 * @param context 上下文
	 * @return 图片列表
	 */
	public static List<Bitmap> getBitmap(List<String> list,Context context){
		List<Bitmap> result = new ArrayList<Bitmap>();
		for(String strUrl : list){
			Bitmap bitmap = getBitmap(strUrl,context);
			if(bitmap!=null){
				result.add(bitmap);
			}
		}
		return result;
	}

	/**
	 * 获取图片的存储目录,在有sd卡的情况下为 “/sdcard/apps_images/本应用包名/cach/images/”
	 * 没有sd的情况下为“/data/data/本应用包名/cach/images/”
	 * 
	 * @param context 上下文
	 * @return 本地图片存储目录
	 */
	private static String getPath(Context context){
		String path = null;
		boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
		String packageName = context.getPackageName()+"/cach/images/";
		if(hasSDCard){
			path="/sdcard/apps_images/"+packageName;
		}else{
			path="/data/data/"+packageName;		
		}  
		File file = new File(path);
		boolean isExist = file.exists();
		if(!isExist){
			
			file.mkdirs();
			
		}
		return file.getPath();
	}

	/**
	 * 网络可用状态下,下载图片并保存在本地
	 * 
	 * @param strUrl 图片网址
	 * @param file 本地保存的图片文件
	 * @param context  上下文
	 * @return 图片
	 */
	private static Bitmap getNetBitmap(String strUrl,File file,Context context) {
		Log.e(TAG, "getBitmap from net");
		Bitmap bitmap = null;
		if(NetUtil.isConnnected(context)){
			try {
				URL url = new URL(strUrl);
				HttpURLConnection con = (HttpURLConnection) url.openConnection();
				con.setDoInput(true);
				con.connect();
				InputStream in = con.getInputStream();
				bitmap = BitmapFactory.decodeStream(in);
				FileOutputStream out = new FileOutputStream(file.getPath());
				bitmap.compress(Bitmap.CompressFormat.PNG,100, out);
				out.flush();
				out.close();
				in.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally{
				
			}			
		}
		return bitmap;
	}
	
}

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. }  
package com.net.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

public class NetUtil {
	private static final String TAG = "NetUtil";

	/**
	 * 网络连接是否可用
	 */
	public static boolean isConnnected(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (null != connectivityManager) {
			NetworkInfo networkInfo[] = connectivityManager.getAllNetworkInfo();

			if (null != networkInfo) {
				for (NetworkInfo info : networkInfo) {
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						Log.e(TAG, "the net is ok");
						return true;
					}
				}
			}
		}
		Toast.makeText(context, "网络连接失败", Toast.LENGTH_SHORT).show();
		return false;
	}

	/**
	 * 网络可用状态下,通过get方式向server端发送请求,并返回响应数据
	 * 
	 * @param strUrl 请求网址
	 * @param context 上下文
	 * @return 响应数据
	 */
	public static JSONObject getResponseForGet(String strUrl, Context context) {
		if (isConnnected(context)) {
			return getResponseForGet(strUrl);
		}
		return null;
	}

	/**
	 * 通过Get方式处理请求,并返回相应数据
	 * 
	 * @param strUrl 请求网址
	 * @return 响应的JSON数据
	 */
	public static JSONObject getResponseForGet(String strUrl) {
		HttpGet httpRequest = new HttpGet(strUrl);
		return getRespose(httpRequest);
	}

	/**
	 * 网络可用状态下,通过post方式向server端发送请求,并返回响应数据
	 * 
	 * @param market_uri 请求网址
	 * @param nameValuePairs 参数信息
	 * @param context 上下文
	 * @return 响应数据
	 */
	public static JSONObject getResponseForPost(String market_uri, List<NameValuePair> nameValuePairs, Context context) {
		if (isConnnected(context)) {
			return getResponseForPost(market_uri, nameValuePairs);
		}
		return null;
	}

	/**
	 * 通过post方式向服务器发送请求,并返回响应数据
	 * 
	 * @param strUrl 请求网址
	 * @param nameValuePairs 参数信息
	 * @return 响应数据
	 */
	public static JSONObject getResponseForPost(String market_uri, List<NameValuePair> nameValuePairs) {
		if (null == market_uri || "" == market_uri) {
			return null;
		}
		HttpPost request = new HttpPost(market_uri);
		try {
			request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			return getRespose(request);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		return null;
	}

	/**
	 * 响应客户端请求
	 * 
	 * @param request 客户端请求get/post
	 * @return 响应数据
	 */
	public static JSONObject getRespose(HttpUriRequest request) {
		try {
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (HttpStatus.SC_OK == statusCode) {
				String result = EntityUtils.toString(httpResponse.getEntity());
				Log.i(TAG, "results=" + result);
				return new JSONObject(result);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}
}


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. }  
package com.innofidei;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LocatUtil {
	private static String logToFileCommand = "logcat -v time -f ";

	public static void startLog(String saveiDir, String fileName) {
		SimpleDateFormat format = new SimpleDateFormat("yyMMdd_HHmmss");
		String nowStr = format.format(new Date());
		fileName = fileName + "_" + nowStr + ".txt";
		new File(saveiDir).mkdirs();
		try {
			Runtime.getRuntime().exec(logToFileCommand + saveiDir + fileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


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. }  
package org.join.weather.util;


import java.util.List;


import org.join.weather.WeatherActivity;
import org.join.weather.WeatherActivity.OnActivityResumeAndPauseListener;


import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;


public class GPSUtil implements OnActivityResultListener,
		OnActivityResumeAndPauseListener {


	// WeatherActivity对象
	private WeatherActivity weatherActivity;
	// LocationManager对象
	private LocationManager locationManager;
	// Location对象
	private Location location;
	// 当前位置提供者
	private String provider;


	// 时间(秒)
	private long minTime = 60 * 1000;
	// 距离(米)
	private float minDistance = 500;
	// 定位方式
	private int mode = 1;


	// 位置监听接口
	private LocationListener mLocationListener = new LocationListener() {


		@Override
		public void onLocationChanged(final Location loc) {
			// 当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发
			Log.v("onLocationChanged", "=onLocationChanged");


			if (loc != null) {
				location = loc;
				showLocationInfo(loc);
			} else {
				Toast.makeText(weatherActivity, "当前位置不可定位!", Toast.LENGTH_SHORT)
						.show();
				// 注销监听事件
				// locationManager.removeUpdates(mLocationListener);
			}
		}


		@Override
		public void onProviderDisabled(String provider) {
			// Provider被disable时触发此函数,比如GPS被关闭
			Log.v("onProviderDisabled", "=onProviderDisabled");
		}


		@Override
		public void onProviderEnabled(String provider) {
			// Provider被enable时触发此函数,比如GPS被打开
			Log.v("onProviderEnabled", "=onProviderEnabled");
		}


		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
			Log.v("onStatusChanged", "=onStatusChanged");
		}
	};


	// 超时注销服务
	private Handler myHandler = new Handler() {


		@Override
		public void handleMessage(Message msg) {
			if (null == location) {
				// 提示信息
				Toast.makeText(weatherActivity, "当前位置不可定位!", Toast.LENGTH_SHORT)
						.show();
			}
			// 注销监听事件
			locationManager.removeUpdates(mLocationListener);
		}


	};


	public GPSUtil(WeatherActivity weatherActivity, int mode) {
		this.weatherActivity = weatherActivity;
		weatherActivity.setOnActivityResultListener(this);
		weatherActivity.setOnResumeAndPauseListener(this);
		this.mode = mode;


		// 获得LocationManager服务
		locationManager = (LocationManager) weatherActivity
				.getSystemService(Context.LOCATION_SERVICE);


		if (openGPSSettings()) {
			setLocationServer(mode);
		} else {
			Toast.makeText(weatherActivity, "请开启GPS!", Toast.LENGTH_SHORT)
					.show();
			Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
			// 此为设置完成后返回到获取界面
			weatherActivity.startActivityForResult(intent, 0);
		}


	}


	public GPSUtil(WeatherActivity weatherActivity, int mode, long minTime,
			float minDistance) {
		this(weatherActivity, mode);
		this.minTime = minTime;
		this.minDistance = minDistance;
	}


	// 判断GPS模块是否存在或者是开启
	private boolean openGPSSettings() {
		if (locationManager
				.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			return true;
		}
		return false;
	}


	// 更新当前位置信息(如果使用GPS,需要保证在室外,并且没有大建筑物遮挡,如果使用网络定位,要保证网络通畅)
	public void setLocationServer(int mode) {


		Toast.makeText(weatherActivity, "正在定位!", Toast.LENGTH_SHORT).show();


		switch (mode) {
		case 1: {
			// GPS定位
			if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
				provider = LocationManager.GPS_PROVIDER;
				location = locationManager.getLastKnownLocation(provider);
				// 设置监听器,自动更新的最小时间为间隔N秒或最小位移变化超过N米
				locationManager.requestLocationUpdates(provider, minTime,
						minDistance, mLocationListener);
				Log.v("GPS定位", "GPS定位!");
			} else {
				Log.v("GPS定位", "未提供GPS定位功能!");
			}
			break;
		}
		case 2: {
			// NETWORK定位
			provider = LocationManager.NETWORK_PROVIDER;
			location = locationManager.getLastKnownLocation(provider);
			// 设置监听器,自动更新的最小时间为间隔N秒或最小位移变化超过N米
			locationManager.requestLocationUpdates(provider, minTime,
					minDistance, mLocationListener);
			Log.v("NETWORK定位", "NETWORK定位!");
			break;
		}
		case 3: {
			// 查询符合条件的Location Provider来定位


			// 获得Criteria对象(指定条件参数)
			Criteria criteria = new Criteria();
			// 获得最好的单位效果
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(false);
			// 使用省电模式
			criteria.setPowerRequirement(Criteria.POWER_LOW);
			// 获得当前位置的提供者
			provider = locationManager.getBestProvider(criteria, true);
			// 获得当前位置
			location = locationManager.getLastKnownLocation(provider);


			if (null != provider) {
				// 设置监听器,自动更新的最小时间为间隔N秒或最小位移变化超过N米
				locationManager.requestLocationUpdates(provider, minTime,
						minDistance, mLocationListener);
			} else {
				Log.v("provider", "null == provider");
			}
			Log.v("最优定位", provider);
			break;
		}
		}


		if (null != location) {
			showLocationInfo(location);
		}
		// 延迟10秒
		myHandler.sendEmptyMessageDelayed(0, 10 * 1000);
	}


	// 显示定位信息
	private void showLocationInfo(Location loc) {


		String msg = "";


		try {
			msg = "经度:" + location.getLongitude() + "\n";
			msg += "纬度:" + location.getLatitude() + "\n";
			Geocoder gc = new Geocoder(weatherActivity);
			List<Address> addresses = gc.getFromLocation(
					location.getLatitude(), location.getLongitude(), 1);
			// 相关信息
			if (addresses.size() > 0) {
				msg += "AddressLine:" + addresses.get(0).getAddressLine(0)
						+ "\n";
				msg += "CountryName:" + addresses.get(0).getCountryName()
						+ "\n";
				msg += "Locality:" + addresses.get(0).getLocality() + "\n";
				msg += "FeatureName:" + addresses.get(0).getFeatureName();
			}
		} catch (Exception e) {
			msg = e.getMessage();
		}


		new AlertDialog.Builder(weatherActivity).setMessage(msg)
				.setPositiveButton("确定", null).show();
	}


	@Override
	public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
		// 从设置GPS的Activity返回时
		if (0 == requestCode) {
			if (openGPSSettings()) {
				setLocationServer(mode);
			} else {
				Toast.makeText(weatherActivity, "GPS仍未开启!", Toast.LENGTH_SHORT)
						.show();
			}
		}
		return false;
	}


	// 在Activity恢复活动时,响应位置更新
	@Override
	public void onResume() {
		if (null != provider) {
			locationManager.requestLocationUpdates(provider, minTime,
					minDistance, mLocationListener);
		}
	}


	// 在Activity暂停活动时,取消位置更新
	@Override
	public void onPause() {
		if (null != locationManager) {
			locationManager.removeUpdates(mLocationListener);
		}
	}


}


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. }  
package com.innofidei.location;

import java.net.InetAddress;
import java.net.UnknownHostException;

import android.content.Context;
import android.net.wifi.WifiManager;

public class AdressUtil {
	public String getIp(Context myContext) {
		InetAddress address = getWifiIp(myContext);
		if (address != null) {
			return address.getHostAddress();
		}
		return null;
	}

	private InetAddress getWifiIp(Context myContext) {
		if (myContext == null) {
			throw new NullPointerException("Global context is null");
		}
		WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
		if (isWifiEnabled(myContext)) {
			int ipAsInt = wifiMgr.getConnectionInfo().getIpAddress();
			if (ipAsInt == 0) {
				return null;
			} else {
				return intToInet(ipAsInt);
			}
		} else {
			return null;
		}
	}

	private boolean isWifiEnabled(Context myContext) {
		if (myContext == null) {
			throw new NullPointerException("Global context is null");
		}
		WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
		if (wifiMgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
			return true;
		} else {
			return false;
		}
	}

	private InetAddress intToInet(int value) {
		byte[] bytes = new byte[4];
		for (int i = 0; i < 4; i++) {
			bytes[i] = byteOfInt(value, i);
		}
		try {
			return InetAddress.getByAddress(bytes);
		} catch (UnknownHostException e) {
			// This only happens if the byte array has a bad length
			return null;
		}
	}

	private byte byteOfInt(int value, int which) {
		int shift = which * 8;
		return (byte) (value >> shift);
	}
}


工具类:字符串处理
工具类:日期处理
工具类:加密(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. }  
public class ClassUtils {

    /**
     * Checks if a class is a subclass of a class with the specified name. Used
     * as an instanceOf without having to load the class, useful when trying to
     * check for classes that might not be available in the runtime JRE.
     * 
     * @param clazz
     *            The class to check
     * @param className
     *            The class name to look for in the super classes
     * @return true if the class extends a class by the specified name.
     */
    public static boolean extendsClass(final Class<?> clazz, String className) {
        Class<?> superClass = clazz.getSuperclass();

        while (superClass != null) {
            if (superClass.getName().equals(className)) {
                return true;
            }
            superClass = superClass.getSuperclass();

        }
        return false;
    }
}


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. }  
import java.io.File;

import android.os.Environment;
import android.os.StatFs;

public class MemoryStatus {
    static final int ERROR = -1;

    /**
     * 外部存储是否可用
     * @return
     */
    static public boolean externalMemoryAvailable() {
        return android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取手机内部可用空间大小
     * @return
     */
    static public long getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    /**
     * 获取手机内部空间大小
     * @return
     */
    static public long getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return totalBlocks * blockSize;
    }

    /**
     * 获取手机外部可用空间大小
     * @return
     */
    static public long getAvailableExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            return availableBlocks * blockSize;
        } else {
            return ERROR;
        }
    }

    /**
     * 获取手机外部空间大小
     * @return
     */
    static public long getTotalExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            return totalBlocks * blockSize;
        } else {
            return ERROR;
        }
    }

    static public String formatSize(long size) {
        String suffix = null;

        if (size >= 1024) {
            suffix = "KiB";
            size /= 1024;
            if (size >= 1024) {
                suffix = "MiB";
                size /= 1024;
            }
        }

        StringBuilder resultBuffer = new StringBuilder(Long.toString(size));
        int commaOffset = resultBuffer.length() - 3;
        while (commaOffset > 0) {
            resultBuffer.insert(commaOffset, ',');
            commaOffset -= 3;
        }

        if (suffix != null)
            resultBuffer.append(suffix);
        return resultBuffer.toString();
    }
}

 

分享到:
评论

相关推荐

    Android开发之超强图片工具类BitmapUtil完整实例

    本文实例讲述了Android开发之超强图片工具类BitmapUtil。分享给大家供大家参考,具体如下: 说明:为了方便大家使用,本人把大家常用的图片处理代码集中到这个类里 使用了LruCache与SoftReference /** * 图片加载...

    自己收集整理的一些常用的工具类

    DeviceStatusUtils 手机状态工具类 主要包括网络、蓝牙、屏幕亮度、飞行模式、音量等 DigestUtils DigestUtils FileUtils 文件操作 HanziToPinyin 拼音汉字处理 IOUtils IOUtils MD5 MD5 MiscUtils 设备信息的获取 ...

    BitmapUtil

    bitmap 缓存工具类,实现缓存sd卡以及内存功能,

    Android代码-android-utils

    囊括了一大部分Android应用开发过程当中常用的工具类。工具类来源整理自网络和自己编写。 所有的工具类简介 (a - z): 类 介绍 AnimationUtils Animation 工具类 AppUtils APP 相关信息工具类 ...

    安卓常用工具类

    工具类有:AppUtil、BitmapUtil、DateUtil、JsonUtil、LogUtil、MeasureUtil、NetWorkUtil、PreferencesUtil、ReflectUtil、SDCardUtil、ScreenUtil、XmlUtil、ColorUtil、ExitActivityUtil、FileUtil、HttpUtil、...

    Android代码-Lazy

    这个是我自己收集整理的一些常用的工具类 有好的工具类,欢迎提交PR 作者微博: @海淀区小鬼风尘 ...手机状态工具类 主要包括网络、蓝牙、屏幕亮度、飞行模式、音量等 DigestUtils DigestUtils FileU

    Android史上最全Util工具类集锦

    Android史上最全Util工具类集锦: 1.AppUtil 2.BitmapUtil 3.DataUtil 4.FileUtil 5.MobleInfoUtil 6.NetUtil 7.QRUtils(二维码生成工具) 8.ScreenUtil 9.SDCardUtil 10.StringUtils 吐血总结,希望对大家有用

    通用Android工具库Common4Android.zip

    设备信息获取工具类,获得设备型号、设备生产厂商、屏幕尺寸、GPS状态、wifi状态等。 DialogUtil.java 弹窗工具类,ProgressDialog,AlertDialog,Toast弹出封装。 ...

    android开发工具类

    各种android开发工具类,能帮助您快速开发 AndroidHttpBaiduServer.java │ AndroidHttpServer.java │ AndroidHttpServerVersion.java │ AutoUpdateVersion.java │ AutoUpdateVersion2.java │ BaseSpinner.java...

    Android BitmapUtils工具类使用详解

    本文实例为大家分享了Android BitmapUtils工具类的具体代码,供大家参考,具体内容如下 public final class BitmapUtils { public static final String TAG = BitmapUtil; private static int sShotScreenWidth =...

    Android应用开发的通用开源工具类包

    源码KissTools,KissTools是Android应用开发的通用开源工具类包,包括BitmapUtil, BundleUtil, ClipboardUtil, DeviceUtil, DrawableUtil, FileUtil, JSONUtil, KeyboardUtil, LogUtil, MediaUtil, NetworkUtil, ...

    SuperUtils:utils项目

    Android工具库 其中很大一部分是Android应用程序开发过程中常用的工具。 工具来自网络并自行编写。 (不断收集整理) (中文文档)[ ]快速使用:在项目...用于管理应用程序的活动和退出 算术精密计算工具类位图实用程

Global site tag (gtag.js) - Google Analytics