- 浏览: 853671 次
文章分类
- 全部博客 (365)
- java (124)
- spring mvc (21)
- spring (22)
- struts2 (6)
- jquery (27)
- javascript (24)
- mybatis/ibatis (8)
- hibernate (7)
- compass (11)
- lucene (26)
- flex (0)
- actionscript (0)
- webservice (8)
- rabbitMQ/Socket (15)
- jsp/freemaker (5)
- 数据库 (27)
- 应用服务器 (21)
- Hadoop (1)
- PowerDesigner (3)
- EJB (0)
- JPA (0)
- PHP (2)
- C# (0)
- .NET (0)
- html (2)
- xml (5)
- android (7)
- flume (1)
- zookeeper (0)
- 证书加密 (2)
- maven (1)
- redis (2)
- cas (11)
最新评论
-
zuxianghuang:
通过pom上传报错 Artifact upload faile ...
nexus上传了jar包.通过maven引用当前jar,不能取得jar的依赖 -
流年末年:
百度网盘的挂了吧???
SSO单点登录系列3:cas-server端配置认证方式实践(数据源+自定义java类认证) -
953434367:
UfgovDBUtil 是什么类
Java发HTTP POST请求(内容为xml格式) -
smilease:
帮大忙了,非常感谢
freemaker自动生成源代码 -
syd505:
十分感谢作者无私的分享,仔细阅读后很多地方得以解惑。
Nginx 反向代理、负载均衡、页面缓存、URL重写及读写分离详解
http://blog.csdn.net/flying_vip_521/article/details/7656413
Android 之 远程图片获取和本地缓存
http://blog.csdn.net/xieqibao/article/details/6682128
Log输出到sdcard工具类
http://blog.csdn.net/flying_vip_521/article/details/7652572
GSPUtil
WebService for Android
获取手机ip地址工具类
工具类:字符串处理
工具类:日期处理
工具类:加密(java)
工具类:判断一个类是否是给定类的子类
android时时监听log
Android中StatFs获取系统/sdcard存储(剩余空间)大小
在存储文件时,为了保证有充足的剩余空间大小,通常需要知道系统内部或者sdcard的存储大小。
- 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;
- }
- }
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;
- }
- }
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();
- }
- }
- }
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);
- }
- }
- }
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);
- }
- }
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;
- }
- }
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();
- }
- }
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客户端同步服务器端表中数据架构分析
2013-11-21 15:49 3633需求:Android客户端有N个,服务器端只有一个 ... -
Android各种访问权限Permission详解
2013-11-04 09:03 727在Android的设计中,资源的访 ... -
android:屏幕自适应
2013-10-25 09:11 730demo下载:http://www.eoeandroid.c ... -
不带布局的RadioGroup——NoLayoutRadioGroup
2013-09-02 14:52 1035虽然android的源码也时不时的会去看,但大部分还是只能看 ... -
android屏幕自适应
2013-06-26 13:08 831以下是Demo首页的预览图 一、细说layou ... -
android intent隐式调用之一个应用程序启动另一个应用程序
2013-04-10 14:26 1520理解Intent的关键之一是理解清楚Intent的两种基本用 ...
相关推荐
本文实例讲述了Android开发之超强图片工具类BitmapUtil。分享给大家供大家参考,具体如下: 说明:为了方便大家使用,本人把大家常用的图片处理代码集中到这个类里 使用了LruCache与SoftReference /** * 图片加载...
3. **BitmapUtil**: 图片处理工具类,用于处理图片的加载、缩放、裁剪、压缩等。在Android应用中,图片的优化对于性能和用户体验至关重要,因此BitmapUtil能够减少内存消耗,防止OOM(内存溢出)问题。 4. **...
首先,让我们来看看其中可能包含的一些关键工具类: 1. **BitmapUtil**:处理图像的工具类,包括压缩图片、裁剪图片、转换为Base64字符串等功能,对内存管理至关重要,可以避免因大图导致的OOM问题。 2. **...
- **BitmapUtil**: 图片处理工具类,可能包含图片的压缩、裁剪、转换等功能。 - **NetworkUtil**: 检查网络状态,判断网络连接类型(如Wi-Fi、移动数据)等。 - **JSONUtil**: 解析和生成JSON数据,可以集成Gson...
1. **StringUtil**: 这个工具类主要处理字符串操作,如格式化、比较、拼接、截取等。它提供了检查空字符串、去除前后空格、转换为驼峰命名等方法,使得字符串处理更加便捷。 2. **BitmapUtil**: 用于图片处理,包括...
DeviceStatusUtils 手机状态工具类 主要包括网络、蓝牙、屏幕亮度、飞行模式、音量等 DigestUtils DigestUtils FileUtils 文件操作 HanziToPinyin 拼音汉字处理 IOUtils IOUtils MD5 MD5 MiscUtils 设备信息的获取 ...
3. **BitmapUtil**: 图片处理工具类,包括图片压缩、裁剪、转换等操作。例如,`compressBitmap()`用于压缩图片以减少内存消耗,`decodeSampledBitmapFromResource()`则用于根据屏幕尺寸加载适合的图片大小,防止OOM...
3. **BitmapUtil**: 图片处理工具类,包含图片压缩、裁剪、加载等操作。例如,`compressBitmap()` 可以用于减少图片内存占用,`cropBitmap()` 可实现图片的裁剪。 4. **IOUtil**: 输入输出工具类,处理文件读写、流...
- **BitmapUtil**:处理图片资源,包括压缩、裁剪、转换为其他格式等。 - **DateUtil**:处理日期时间,提供格式化、比较、计算差值等功能。 - **SharedPreferencesUtil**:封装SharedPreferences操作,便于...
以上就是Android开发中常见的工具类,它们涵盖了字符串、日期时间、日志、位图、SharedPreferences、网络状态、JSON解析、视图操作、文件操作以及权限请求等多个方面,是Android开发不可或缺的一部分。开发者可以...
bitmap 缓存工具类,实现缓存sd卡以及内存功能,
囊括了一大部分Android应用开发过程当中常用的工具类。工具类来源整理自网络和自己编写。 所有的工具类简介 (a - z): 类 介绍 AnimationUtils Animation 工具类 AppUtils APP 相关信息工具类 ...
此外,BitmapUtil可能是处理图像的工具类,它可能包含图片的加载、压缩、缓存等功能。在Android中,图片资源往往较大,合理处理可以节省内存,防止应用因内存泄漏而崩溃。 文件操作也是常见需求,FileUtil可能提供...
工具类有:AppUtil、BitmapUtil、DateUtil、JsonUtil、LogUtil、MeasureUtil、NetWorkUtil、PreferencesUtil、ReflectUtil、SDCardUtil、ScreenUtil、XmlUtil、ColorUtil、ExitActivityUtil、FileUtil、HttpUtil、...
这个是我自己收集整理的一些常用的工具类 有好的工具类,欢迎提交PR 作者微博: @海淀区小鬼风尘 ...手机状态工具类 主要包括网络、蓝牙、屏幕亮度、飞行模式、音量等 DigestUtils DigestUtils FileU
4. **图片处理**:BitmapUtil则涉及图片的加载、压缩、裁剪等操作,比如`compressBitmap(Bitmap bitmap, int quality)`用于压缩Bitmap以减少内存占用。 5. **日志打印**:LogUtil提供了一种统一的日志打印方式,...
Android史上最全Util工具类集锦: 1.AppUtil 2.BitmapUtil 3.DataUtil 4.FileUtil 5.MobleInfoUtil 6.NetUtil 7.QRUtils(二维码生成工具) 8.ScreenUtil 9.SDCardUtil 10.StringUtils 吐血总结,希望对大家有用
3. **BitmapUtil**:位图处理工具类,用于图片的压缩、加载、缓存等。 4. **NetworkUtil**:网络状态检测与网络请求辅助工具类。 5. **DateUtil**:日期时间处理工具类,提供了日期的格式化、比较和转换等功能。 6. ...
设备信息获取工具类,获得设备型号、设备生产厂商、屏幕尺寸、GPS状态、wifi状态等。 DialogUtil.java 弹窗工具类,ProgressDialog,AlertDialog,Toast弹出封装。 ...