工具类

来源:互联网 发布:结绳记事 软件 编辑:程序博客网 时间:2024/06/03 20:25

工具类的总结


图片下载工具类

转自http://blog.csdn.net/flying_vip_521/article/details/7656413 

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;}}
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();}}}
GPS工具类

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() {@Overridepublic 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);}}@Overridepublic void onProviderDisabled(String provider) {// Provider被disable时触发此函数,比如GPS被关闭Log.v("onProviderDisabled", "=onProviderDisabled");}@Overridepublic void onProviderEnabled(String provider) {// Provider被enable时触发此函数,比如GPS被打开Log.v("onProviderEnabled", "=onProviderEnabled");}@Overridepublic void onStatusChanged(String provider, int status, Bundle extras) {// Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数Log.v("onStatusChanged", "=onStatusChanged");}};// 超时注销服务private Handler myHandler = new Handler() {@Overridepublic 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();}@Overridepublic 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恢复活动时,响应位置更新@Overridepublic void onResume() {if (null != provider) {locationManager.requestLocationUpdates(provider, minTime,minDistance, mLocationListener);}}// 在Activity暂停活动时,取消位置更新@Overridepublic void onPause() {if (null != locationManager) {locationManager.removeUpdates(mLocationListener);}}}
获取手机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 lengthreturn null;}}private byte byteOfInt(int value, int which) {int shift = which * 8;return (byte) (value >> shift);}}

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();    }}





0 0
原创粉丝点击