- 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
- 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
- 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
- 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地址工具類
- 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)
工具類:判斷一個類是否是給定類的子類
- 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的存儲大小。
- 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();
- }
- }