寂寞笑我太堕落吧 关注:4贴子:443
package com.juchao.upg.android.util;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.juchao.upg.android.R;
import com.juchao.upg.android.ui.StartActivity;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.view.Display;
public class ClientUtil {
private static final int COMPRESSION=30;
/**
* 获取屏幕的宽高
* @param mActivity
* @return
*/
public static int[] getWidthHeight(Activity mActivity){
int[] w_h = new int[2];
Display display = mActivity.getWindowManager().getDefaultDisplay();
w_h[0] = display.getWidth();
w_h[1] = display.getHeight();
return w_h;
}
/**
* 将dip转换为px
*
* @param context
* @param dipValue
* @return
*/
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
/**
* 将px转换为dip
*
* @param context
* @param dipValue
* @return
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static String getSDPath(){
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
//判断sd卡是否存在
if (sdCardExist){
sdDir = Environment.getExternalStorageDirectory();//获取跟目录
return sdDir.toString();
}
return null;
}
public static String getRootDir(){
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
public static String getDownDir(){
String path = getRootDir() + "/upg/apk";
File file = new File(path);
if(!file.exists()){//判断文件夹目录是否存在
file.mkdirs();//如果不存在则创建
}
return file.getAbsolutePath();
}
public static String getImageDir(){
String path = getRootDir() + "/upg/image";
File file = new File(path);
if(!file.exists()){//判断文件夹目录是否存在
file.mkdirs();//如果不存在则创建
}
return file.getAbsolutePath();
}
/**
* 保存图片
* @param Bmp
* @param filePath
*/
public static void saveImage(Bitmap Bmp,String fileName){
try {
File path = new File(getImageDir() ,fileName);// 给新照的照片文件命名
// path.createNewFile();
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(path));
/* 采用压缩转档方法 */
//Bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
Bmp.compress(Bitmap.CompressFormat.PNG, 80, bos);
/* 调用flush()方法,更新BufferStream */
bos.flush();
/* 结束OutputStream */
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 80;
while ( baos.toByteArray().length / 1024>100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();//重置baos即清空baos
options -= 10;//每次都减少10
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
return bitmap;
}
public static void saveImage1(Bitmap Bmp,String fileName){
try {
File path = new File(getImageDir() ,fileName);// 给新照的照片文件命名
// path.createNewFile();
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(path));
/* 采用压缩转档方法 */
//Bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
Bmp.compress(Bitmap.CompressFormat.PNG, 30, bos);
/* 调用flush()方法,更新BufferStream */
bos.flush();
/* 结束OutputStream */
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Bitmap getThumbnailImage(String fileName ,int w ,int h){
BitmapFactory.Options opts = new BitmapFactory.Options();
// 设置为ture只获取图片大小
opts.inJustDecodeBounds = true;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
// 返回为空
String path = getImageDir() + File.separator +fileName;
BitmapFactory.decodeFile(path , opts);
int width = opts.outWidth;
int height = opts.outHeight;
float scaleWidth = 0.f, scaleHeight = 0.f;
if (width > w || height > h) {
// 缩放
scaleWidth = ((float) width) / w;
scaleHeight = ((float) height) / h;
}
opts.inJustDecodeBounds = false;
float scale = Math.max(scaleWidth, scaleHeight);
opts.inSampleSize = (int)scale;
WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
return Bitmap.createScaledBitmap(weak.get(), w, h, true);
}
/**
*
* @param usedTime 单位:秒
* @return
*/
public static String getUsedTime(int usedTime){
int minute = 0;
int second = 0;
if(usedTime >= 60){
minute = (int) usedTime / 60;
second = (int)(usedTime % 60);
return minute + "分" + second + "秒";
}else{
return "0分" + usedTime + "秒";
}
}
/**
*
* @return
*/
public static String getLocalMacAddress(Context context) {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();
}
@SuppressWarnings("deprecation")
public static void showNotification(Context context,String title, String summary) {
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification();
n.flags |= Notification.FLAG_SHOW_LIGHTS;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.defaults = Notification.DEFAULT_ALL;
n.icon = R.drawable.messageremind;
n.when = System.currentTimeMillis();
// Simply open the parent activity
Intent intent = new Intent(context,StartActivity.class);
//broadcastIntent.putExtra(PushConstants.APP_KEY, APPKEY);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
// Change the name of the notification here
n.setLatestEventInfo(context, title, summary, pi);
mNotificationManager.notify(0, n);
}
public static String getTimeFormat(long time){
Date date = new Date(time);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return dateFormat.format(date);
}
public static Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float hh = 720f;//这里设置高度为800f
float ww = 480f;//这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;//设置缩放比例
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
}
}


1楼2015-09-01 17:45回复
    package com.juchao.upg.android.util;
    public class Constants {
    public static final Boolean LOGD_ENABLE = true;
    public static final Boolean LOG_SDCARD_ENABLE = false;
    public static final String LOG_FILE_NAME = "com.juchao.upg.android_log.txt";
    public static final String BASE_IP = "172.16.2.13";
    public static final String BASE_PORT = "8080";
    public static final String BASE_URL = "http://"+BASE_IP+":"+BASE_PORT+"/baoquan";
    public static final int REQUEST_SUCCESS = 0;
    public static final int REQUEST_FAIL = -1;
    public static final String KEY_SERVICE_ADDRESS = "key_service_address"; //服务器地址
    public static final String KEY_SERVICE_PORT = "key_service_port"; //服务器端口
    public static final String KEY_ONLY_REMIND_ONCE = "key_only_remind_once"; //仅提醒一次
    public static final String KEY_REMIND_INTERVAL = "key_remind_interval"; //时间间隔
    public static final String KEY_TOKEN = "key_token"; //登录token
    public static final String KEY_USER_ID = "key_user_id"; //登录用户ID
    public static final String KEY_USER_NAME = "key_user_name"; //登录的用户名
    public static final String KEY_MAC = "key_mac"; //
    public static final String KEY_LAST_UPDATE_DATA_TIME = "key_last_update_data_time"; //上次更新基础数据的时间
    public static final String KEY_LAST_PUSH_TIME = "key_last_push_time";
    public static final String KEY_LAST_MSG_ID = "key_last_msg_id"; //
    /**
    * Maintenace 功能
    * 对应表 Maintenace_Item_Table_Name 字段:state.
    */
    public static final int WX_NOT_COMMIT = 1; //问题未维修
    public static final int WX_HAS_COMMIT = 2; //问题已维修
    public static final int WX_HAS_COMMIT_TASK_STATE_SET = 2; // 已维修下载,需要效果确认的任务
    //Task attribute state
    public static final int TASK_NOT_DOWNLOAD = 0; //未下载的任务
    public static final int TASK_HAS_DOWNLOAD = 1; //任务已下载,未曾维修
    public static final int TASK_HAS_MAINTENACE = 2; //已维修
    public static final int TASK_HAS_EFFECT = 3; //已 效果确认
    public static final int TASK_HAS_FINISH = 4; //已完成的任务(已上传成功)
    //对 problem 表 添加uploadState 状态
    public static final int TASK_NOT_UPLOAD = 0;
    public static final int TASK_HAS_UPLOAD = 1;
    //对缩小版本添加前缀
    public static final String PHOTO_PREFIX = "T_";
    //使用后门 开户日志记录
    public static final String BEGIN_LOG="begin_record_log";
    public static final int TEXT_COUNT_LIMIT=255;
    public static final int DJ_POPUP = 1;
    public static final int WX_POPUP = 2;
    }


    2楼2015-09-01 17:45
    回复
      2026-02-05 17:29:00
      广告
      不感兴趣
      开通SVIP免广告
      package com.juchao.upg.android.util;
      public class ConstantUtil {
      public static final int WXEFFECTCONFIRMSTATE = 3;
      public enum WxEffectConfirmTask{
      WxDownLoadTaskState,
      WxEffectConfirmTaskState;
      }
      public enum xxxx{
      }
      }


      3楼2015-09-01 17:46
      回复
        package com.juchao.upg.android.util;
        import java.util.Map;
        import android.content.SharedPreferences;
        import android.content.SharedPreferences.Editor;
        import android.preference.PreferenceManager;
        import com.juchao.upg.android.MyApp;
        /**
        *
        * 默认的SharedPreferences
        * 支持数据类型存储
        * 位置 packagename.xml
        * @author xuxd
        */
        public final class DefaultShared {
        private static final SharedPreferences spf = PreferenceManager
        .getDefaultSharedPreferences(MyApp.application.getBaseContext());
        public static void putBoolean(String key, boolean valeu) {
        spf.edit().putBoolean(key, valeu).commit();
        }
        public static void putFloat(String key, float valeu) {
        spf.edit().putFloat(key, valeu).commit();
        }
        public static void putInt(String key, int valeu) {
        spf.edit().putInt(key, valeu).commit();
        }
        public static void putLong(String key, long valeu) {
        spf.edit().putLong(key, valeu).commit();
        }
        public static void putString(String key, String valeu) {
        spf.edit().putString(key, valeu).commit();
        }
        /**
        * SharedPreferences支持数据类型
        * @param params
        */
        public static void putMap(Map<String,?> params)
        {
        if(params == null || params.size() == 0)
        return;
        Editor edit = spf.edit();
        for(Map.Entry<String, ?> entry : params.entrySet())
        {
        if(entry.getValue() instanceof Boolean)
        {
        edit.putBoolean(entry.getKey(), (Boolean)entry.getValue());
        }else if(entry.getValue() instanceof Float)
        {
        edit.putFloat(entry.getKey(), (Float)entry.getValue());
        }else if(entry.getValue() instanceof Integer)
        {
        edit.putInt(entry.getKey(), (Integer)entry.getValue());
        }else if(entry.getValue() instanceof Long)
        {
        edit.putLong(entry.getKey(), (Long)entry.getValue());
        }else if(entry.getValue() instanceof String)
        {
        edit.putString(entry.getKey(), (String)entry.getValue());
        }
        }
        edit.commit();
        }
        public static boolean getBoolean(String key, boolean defValue) {
        return spf.getBoolean(key, defValue);
        }
        public static float getFloat(String key, float defValue) {
        return spf.getFloat(key, defValue);
        }
        public static int getInt(String key, int defValue) {
        return spf.getInt(key, defValue);
        }
        public static long getLong(String key, long defValue) {
        return spf.getLong(key, defValue);
        }
        public static String getString(String key, String defValue) {
        return spf.getString(key, defValue);
        }
        public static boolean isContainKey(String key){
        return spf.contains(key);
        }
        }


        4楼2015-09-01 17:46
        回复
          package com.juchao.upg.android.util;
          public interface DownloadProgressListener {
          public void onDownloadSize(int size);
          }


          5楼2015-09-01 17:46
          回复
            package com.juchao.upg.android.util;
            import java.io.File;
            import java.io.InputStream;
            import java.io.RandomAccessFile;
            import java.net.HttpURLConnection;
            import java.net.URL;
            import android.util.Log;
            import com.juchao.upg.android.net.download.FileDownloader;
            public class DownloadThread extends Thread{
            private static final String TAG=DownloadThread.class.getSimpleName();
            private File saveFile;
            private URL downUrl;
            private int block;
            /* 下载开始位置*/
            private int threadId = -1;
            private int downLength;
            private boolean finish = false;
            private com.juchao.upg.android.util.FileDownloader downloader;
            /**
            * downloader: 下载器
            * downUrl: 下载地址
            * saveFile: 下载路径
            */
            public DownloadThread(com.juchao.upg.android.util.FileDownloader fileDownloader, URL downUrl,File saveFile,int block, int downLength,int threadId){
            this.downUrl=downUrl;
            this.saveFile=saveFile;
            this.block=block;
            this.downloader=fileDownloader;
            this.threadId=threadId;
            this.downLength=downLength;
            }
            @Override
            public void run(){
            if(downLength < block){ //未下载完成
            try{
            //使用Get方式下载
            HttpURLConnection http=(HttpURLConnection)downUrl.openConnection();
            http.setConnectTimeout(5 * 1000);
            http.setRequestMethod("GET");
            http.setRequestProperty("Accept", "image/gif, image/jpeg,image/pjpeg,image/pjpeg,application/x-shockwave-flash," +
            "application/xaml+xml,application/vnd.ms-xpsdocument,application/x-ms-application,application/vnd.ms-excel," +
            "application/vnd.ms-powerpoint,application/msword,*/*");
            http.setRequestProperty("Accept-Language", "zh-CN");
            http.setRequestProperty("Referer", downUrl.toString());
            http.setRequestProperty("Charset", "UTF-8");
            int startPos=block *(threadId - 1) +downLength; //开始位置
            int endPos = block * threadId - 1;
            http.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); //设置获取实体数据的范围
            http.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 8.0; Windows NT 5.2;Trident/4.0;.NET CLR 1.1.4322;" +
            ".NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
            http.setRequestProperty("Connection", "Keep-Alive");
            InputStream inStream=http.getInputStream();
            byte[] buffer=new byte[1024];
            int offset=0;
            print("Thread " + this.threadId + " start download from position " + startPos);
            RandomAccessFile threadfile = new RandomAccessFile(this.saveFile, "rwd");
            threadfile.seek(startPos);
            while((offset = inStream.read(buffer,0,1024)) !=-1){
            threadfile.write(buffer,0,offset);
            downLength +=offset;
            downloader.update(this.threadId,downLength);
            downloader.append(offset);
            }
            threadfile.close();
            inStream.close();
            print("Thread " + this.threadId + " download finish");
            this.finish = true;
            }catch(Exception e){
            this.downLength = -1;
            print("Thread " + this.threadId + ":" + e);
            }
            }
            }
            /**
            * 打印日志信息
            * @param msg
            */
            private static void print(String msg){
            Log.i(TAG, msg);
            }
            public boolean isFinish(){
            return finish;
            }
            /**
            * 已经下载的内容大小
            * 如果返回
            */
            public long getDownLength(){
            return downLength;
            }
            }


            6楼2015-09-01 17:47
            回复
              package com.juchao.upg.android.util;
              import android.os.Environment;
              import java.io.File;
              public class FileUtil {
              public static String getRootDir(){
              return Environment.getExternalStorageDirectory().getAbsolutePath();
              }
              public static String getDownDir(){
              String path = getRootDir() + "/903dt/video";
              File file = new File(path);
              if(!file.exists()){//判断文件夹目录是否存在
              file.mkdirs();//如果不存在则创建
              }
              return file.getAbsolutePath();
              }
              public static String getImageDir(){
              String path = getRootDir() + "/903dt/cache";
              File file = new File(path);
              if(!file.exists()){//判断文件夹目录是否存在
              file.mkdirs();//如果不存在则创建
              }
              return file.getAbsolutePath();
              }
              public static void delVoiceFile(String fileName){
              try{
              File file = new File(getDownDir()+ File.separator + fileName);
              file.deleteOnExit();
              }catch(Exception e){
              e.printStackTrace();
              }
              }
              public static void delVoiceDir(){
              File file = new File(getDownDir());
              if(file.isDirectory()){//判断文件夹目录是否存在
              file.delete();
              }
              }
              public static String getExplainDir(){
              String path= getRootDir() + "/upg/explain" ;
              File file=new File(path);
              if(!file.exists()){
              file.mkdirs();
              }
              return file.getAbsolutePath();
              }
              public static String getBaseImageDir(){
              String path = getRootDir() +"/upg/baseImage" ;
              File file=new File(path);
              if(!file.exists()){
              file.mkdirs();
              }
              return file.getAbsolutePath();
              }
              public static boolean existExplainFile(long equipmentId,int type){
              File file = new File(getExplainDir() + File.separator + equipmentId + "_" +type + ".doc");
              File file1= new File(getExplainDir() + File.separator + equipmentId + "_" +type + ".pdf");
              if(!file.exists() && !file1.exists()){
              return false;
              }
              return true;
              }
              public static String getBaseEquipmentAttachmentDir(){
              String path = getRootDir()+"/upg/attachment";
              File file = new File(path);
              if(!file.exists()){
              file.mkdirs();
              }
              return file.getAbsolutePath();
              }
              public static String getMaintenacePicDir(){
              String path = getRootDir() +"/upg/maintenacePic";
              File file = new File(path);
              if(!file.exists()){
              file.mkdirs();
              }
              return file.getAbsolutePath();
              }
              }


              8楼2015-09-01 17:48
              回复
                package com.juchao.upg.android.util;
                public class FloatBottonUtil {
                public static final int SHAPENORMAL = 80;
                public static final int SHAPEPRESSED = 200;
                }


                9楼2015-09-01 17:48
                回复
                  2026-02-05 17:23:00
                  广告
                  不感兴趣
                  开通SVIP免广告
                  package com.juchao.upg.android.util;
                  import android.os.Handler;
                  import android.os.Message;
                  import com.iData.Scan.BarcodeControll;
                  public class HadwareControll {
                  public static BarcodeControll barcodeControll = new BarcodeControll();
                  static public Handler m_handler = null;
                  static public final int BARCODE_READ = 10;
                  private static boolean m_stop = false;
                  private static boolean start_Scan=false;
                  public static final boolean IsIScan;
                  static {
                  if(barcodeControll !=null){
                  IsIScan = true;
                  }else{
                  barcodeControll = new BarcodeControll();
                  if(barcodeControll !=null){
                  IsIScan = true;
                  }else{
                  IsIScan = false;
                  }
                  }
                  }
                  public static void Open() {
                  barcodeControll.Barcode_open();
                  m_stop = false;
                  start_Scan=false;
                  new BarcodeReadThread().start();
                  }
                  public static void Close() {
                  m_stop = true;
                  start_Scan=false;
                  barcodeControll.Barcode_Close();
                  }
                  public static void scan_start() {
                  barcodeControll.Barcode_StarScan();
                  start_Scan=true;
                  }
                  public static void scan_stop() {
                  barcodeControll.Barcode_StopScan();
                  }
                  static class BarcodeReadThread extends Thread {
                  public void run() {
                  // TODO Auto-generated method stub
                  while (!m_stop) {
                  try {
                  Thread.sleep(50);
                  ReadBarcodeID();
                  } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                  }
                  }
                  };
                  }
                  public static void ReadBarcodeID() {
                  String info = null;
                  byte[] buffer = null;
                  buffer = barcodeControll.Barcode_Read();
                  try {
                  info = new String(buffer, "GBK");
                  }catch (java.io.UnsupportedEncodingException e) {
                  e.printStackTrace();
                  }
                  if (info.length() > 0 && m_handler != null&&start_Scan) {
                  Message msg = new Message();
                  msg.what = BARCODE_READ;
                  msg.obj = info;
                  System.out.println("msg.obj=" + msg.obj);
                  m_handler.sendMessage(msg);
                  }
                  }
                  }


                  10楼2015-09-01 17:48
                  回复
                    package com.juchao.upg.android.util;
                    import java.util.Map;
                    import org.apache.http.message.BasicNameValuePair;
                    import android.app.Activity;
                    import android.content.Intent;
                    import android.os.Bundle;
                    import com.juchao.upg.android.R;
                    /**
                    * 启动Activity
                    * @author xuxd
                    *
                    */
                    public class IntentUtil {
                    /**
                    * 启动Activity ,不带参数
                    * @param activity
                    * @param cls
                    */
                    public static void startActivity(Activity activity,Class<?> cls){
                    Intent intent=new Intent();
                    intent.setClass(activity,cls);
                    activity.startActivity(intent);
                    activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                    }
                    /**
                    * 启动Activity ,不带参数
                    * @param activity
                    * @param cls
                    */
                    public static void startActivityFromMain(Activity activity,Class<?> cls){
                    Intent intent=new Intent();
                    intent.setClass(activity,cls);
                    activity.startActivity(intent);
                    }
                    /**
                    * 启动Activity ,带参数
                    * @param activity
                    * @param cls
                    * @param params
                    */
                    public static void startActivity(Activity activity,Class<?> cls,Bundle bundle){
                    Intent intent=new Intent();
                    intent.setClass(activity,cls);
                    intent.putExtras(bundle);
                    activity.startActivity(intent);
                    activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                    }
                    public static void startActivityFromMain(Activity activity,Class<?> cls,Bundle bundle){
                    Intent intent=new Intent();
                    intent.setClass(activity,cls);
                    intent.putExtras(bundle);
                    activity.startActivity(intent);
                    activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                    }
                    public static void startActivityFromMain1(Activity activity,Class<?> cls,Bundle bundle){
                    Intent intent=new Intent();
                    intent.setClass(activity,cls);
                    intent.putExtras(bundle);
                    activity.startActivity(intent);
                    //activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                    }
                    /**
                    * 启动service
                    * @param activity
                    * @param cls
                    * @param params
                    */
                    public static void startService(Activity activity,Class<?> cls,BasicNameValuePair...params){
                    Intent intent=new Intent();
                    intent.setClass(activity,cls);
                    for(int i=0;i<params.length;i++){
                    intent.putExtra(params[i].getName(), params[i].getValue());
                    }
                    activity.startService(intent);
                    }
                    }


                    11楼2015-09-01 17:48
                    回复
                      package com.juchao.upg.android.util;
                      import java.io.IOException;
                      import org.codehaus.jackson.map.DeserializationConfig;
                      import org.codehaus.jackson.map.ObjectMapper;
                      import org.codehaus.jackson.map.SerializationConfig;
                      import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
                      import org.codehaus.jackson.map.util.JSONPObject;
                      import org.codehaus.jackson.type.JavaType;
                      import android.text.TextUtils;
                      /**
                      * 简单封装Jackson,实现JSON String<->Java Object的Mapper.
                      *
                      * 封装不同的输出风格, 使用不同的builder函数创建实例.
                      *
                      */
                      public class JsonMapper {
                      private static final String tag = JsonMapperUtils.class.getSimpleName();
                      private ObjectMapper mapper;
                      public JsonMapper(Inclusion inclusion) {
                      mapper = new ObjectMapper();
                      //设置输出时包含属性的风格
                      SerializationConfig seriConf = mapper.getSerializationConfig();
                      seriConf.setSerializationInclusion(inclusion);
                      //设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
                      mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                      //禁止使用int代表Enum的order()来反序列化Enum,非常危险
                      mapper.configure(DeserializationConfig.Feature.FAIL_ON_NUMBERS_FOR_ENUMS, true);
                      }
                      /**
                      * 创建输出全部属性到Json字符串的Mapper.
                      */
                      public static JsonMapper buildNormalMapper() {
                      return new JsonMapper(Inclusion.ALWAYS);
                      }
                      /**
                      * 创建只输出非空属性到Json字符串的Mapper.
                      */
                      public static JsonMapper buildNonNullMapper() {
                      return new JsonMapper(Inclusion.NON_NULL);
                      }
                      /**
                      * 创建只输出初始值被改变的属性到Json字符串的Mapper.
                      */
                      public static JsonMapper buildNonDefaultMapper() {
                      return new JsonMapper(Inclusion.NON_DEFAULT);
                      }
                      /**
                      * 如果对象为Null, 返回"null".
                      * 如果集合为空集合, 返回"[]".
                      */
                      public String toJson(Object object) {
                      try {
                      return mapper.writeValueAsString(object);
                      } catch (IOException e) {
                      Log.e(tag,"write to json string error:" + object, e);
                      return null;
                      }
                      }
                      /**
                      * 如果JSON字符串为Null或"null"字符串, 返回Null.
                      * 如果JSON字符串为"[]", 返回空集合.
                      *
                      * 如需读取集合如List/Map, 且不是List<String>这种简单类型时,先使用函数constructParametricType构造类型.
                      * @see #constructParametricType(Class, Class...)
                      */
                      public <T> T fromJson(String jsonString, Class<T> clazz) {
                      if (TextUtils.isEmpty(jsonString)) {
                      return null;
                      }
                      try {
                      return mapper.readValue(jsonString, clazz);
                      } catch (IOException e) {
                      Log.e(tag,"parse json string error:" + jsonString, e);
                      return null;
                      }
                      }
                      /**
                      * 如果JSON字符串为Null或"null"字符串, 返回Null.
                      * 如果JSON字符串为"[]", 返回空集合.
                      *
                      * 如需读取集合如List/Map, 且不是List<String>这种简单类型时,先使用函数constructParametricType构造类型.
                      * @see #constructParametricType(Class, Class...)
                      */
                      public <T> T fromJson(String jsonString, JavaType javaType) {
                      if (TextUtils.isEmpty(jsonString)) {
                      return null;
                      }
                      try {
                      return (T) mapper.readValue(jsonString, javaType);
                      } catch (IOException e) {
                      Log.e(tag,"parse json string error:" + jsonString, e);
                      return null;
                      }
                      }
                      /**
                      * 构造泛型的Type如List<MyBean>, 则调用constructParametricType(ArrayList.class,MyBean.class)
                      * Map<String,MyBean>则调用(HashMap.class,String.class, MyBean.class)
                      */
                      public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses) {
                      return mapper.getTypeFactory().constructParametricType(parametrized, parameterClasses);
                      }
                      /**
                      * 输出JSONP格式数据.
                      */
                      public String toJsonP(String functionName, Object object) {
                      return toJson(new JSONPObject(functionName, object));
                      }
                      /**
                      * 设定是否使用Enum的toString函数来读写Enum,
                      * 为False时时使用Enum的name()函数来读写Enum, 默认为False.
                      * 注意本函数一定要在Mapper创建后, 所有的读写动作之前调用.
                      */
                      public void setEnumUseToString(boolean value) {
                      mapper.configure(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING, value);
                      mapper.configure(DeserializationConfig.Feature.READ_ENUMS_USING_TO_STRING, value);
                      }
                      /**
                      * 取出Mapper做进一步的设置或使用其他序列化API.
                      */
                      public ObjectMapper getMapper() {
                      return mapper;
                      }
                      }


                      12楼2015-09-01 17:49
                      回复
                        package com.juchao.upg.android.util;
                        import java.io.InputStream;
                        import java.util.ArrayList;
                        import org.codehaus.jackson.JsonGenerator;
                        import org.codehaus.jackson.JsonParser.Feature;
                        import org.codehaus.jackson.map.DeserializationConfig;
                        import org.codehaus.jackson.map.ObjectMapper;
                        import org.codehaus.jackson.map.SerializationConfig;
                        import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
                        import org.codehaus.jackson.map.type.TypeFactory;
                        import org.codehaus.jackson.type.JavaType;
                        /**
                        * json 解析类
                        *
                        * @author ynb
                        *
                        */
                        public class JsonMapperUtils {
                        private static final String TAG = JsonMapperUtils.class.getSimpleName();
                        private static ObjectMapper mMapper;
                        private static byte[] lock = new byte[0];
                        public static ObjectMapper getDefaultObjectMapper() {
                        synchronized (lock) {
                        if (mMapper == null) {
                        ObjectMapper mapper = new ObjectMapper();
                        SerializationConfig seriConf = mapper.getSerializationConfig();
                        seriConf.setSerializationInclusion(Inclusion.NON_NULL);
                        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); //设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
                        mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET,
                        false);
                        mapper.configure(Feature.AUTO_CLOSE_SOURCE, false);
                        // mapper.registerSubtypes(//
                        // User.class
                        // );
                        mMapper = mapper;
                        }
                        }
                        return mMapper;
                        }
                        /**
                        * 对象转成json
                        * @param <T>
                        * @param t
                        * @return
                        */
                        public static <T> String toJson(T t) {
                        if (t == null)
                        return null;
                        try {
                        return getDefaultObjectMapper().writeValueAsString(t);
                        } catch (Exception e) {
                        Log.w(TAG, e);
                        return null;
                        }
                        }
                        /**
                        * json 转成 对象
                        * @param <T>
                        * @param json
                        * @param clazz
                        * @return
                        */
                        public static <T> T toObject(String json, Class<T> clazz) {
                        try {
                        return getDefaultObjectMapper().readValue(json, clazz);
                        } catch (Exception e) {
                        Log.w(TAG, e);
                        return null;
                        }
                        }
                        /**
                        * json二进制流转成对象
                        * @param <T>
                        * @param in
                        * @param clazz
                        * @return
                        */
                        public static <T> T toObject(InputStream in, Class<T> clazz) {
                        try {
                        return getDefaultObjectMapper().readValue(in, clazz);
                        } catch (Exception e) {
                        Log.w(TAG, e);
                        return null;
                        }
                        }
                        public static <T> JavaType constructListType(Class<T> clazz) {
                        return TypeFactory.defaultInstance().constructCollectionType(
                        ArrayList.class, clazz);
                        }
                        }


                        13楼2015-09-01 17:49
                        回复
                          package com.juchao.upg.android.util;
                          import java.io.BufferedWriter;
                          import java.io.File;
                          import java.io.FileWriter;
                          import java.sql.Timestamp;
                          import java.util.Date;
                          import android.os.Environment;
                          public final class Log {
                          private static final boolean LOGD_ENABLE = Constants.LOGD_ENABLE;
                          private static final boolean LOGE_ENABLE = Constants.LOGD_ENABLE;
                          private static final boolean LOGI_ENABLE = Constants.LOGD_ENABLE;
                          private static final boolean LOGV_ENABLE = Constants.LOGD_ENABLE;
                          private static final boolean LOGW_ENABLE = Constants.LOGD_ENABLE;
                          /**
                          * Priority constant for the println method; use Log.v.
                          */
                          public static final int VERBOSE = android.util.Log.VERBOSE;
                          /**
                          * Priority constant for the println method; use Log.d.
                          */
                          public static final int DEBUG = android.util.Log.DEBUG;
                          /**
                          * Priority constant for the println method; use Log.i.
                          */
                          public static final int INFO = android.util.Log.INFO;
                          /**
                          * Priority constant for the println method; use Log.w.
                          */
                          public static final int WARN = android.util.Log.WARN;
                          /**
                          * Priority constant for the println method; use Log.e.
                          */
                          public static final int ERROR = android.util.Log.ERROR;
                          /**
                          * Priority constant for the println method.
                          */
                          public static final int ASSERT = android.util.Log.ASSERT;
                          private Log() {
                          }
                          public static boolean isLoggable(String tag, int level) {
                          return android.util.Log.isLoggable(tag, level);
                          }
                          /**
                          * Send a {@link #VERBOSE} log message.
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param msg The message you would like logged.
                          */
                          public static int v(String tag, String msg) {
                          if (!LOGV_ENABLE ) return 0;
                          if(Constants.LOG_SDCARD_ENABLE) fileLog(tag,msg);
                          return android.util.Log.v(tag, msg);
                          }
                          /**
                          * Send a {@link #VERBOSE} log message and log the exception.
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param msg The message you would like logged.
                          * @param tr An exception to log
                          */
                          public static int v(String tag, String msg, Throwable tr) {
                          if (!LOGV_ENABLE ) return 0;
                          if(Constants.LOG_SDCARD_ENABLE) fileLog(tag,msg);
                          return android.util.Log.v(tag, msg, tr);
                          }
                          /**
                          * Send a {@link #DEBUG} log message.
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param msg The message you would like logged.
                          */
                          public static int d(String tag, String msg) {
                          if (!LOGD_ENABLE ) return 0;
                          if(Constants.LOG_SDCARD_ENABLE) fileLog(tag,msg);
                          return android.util.Log.d(tag, msg);
                          }
                          /**
                          * Send a {@link #DEBUG} log message and log the exception.
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param msg The message you would like logged.
                          * @param tr An exception to log
                          */
                          public static int d(String tag, String msg, Throwable tr) {
                          if (!LOGD_ENABLE ) return 0;
                          if(Constants.LOG_SDCARD_ENABLE) fileLog(tag,msg);
                          return android.util.Log.d(tag, msg, tr);
                          }
                          /**
                          * Send an {@link #INFO} log message.
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param msg The message you would like logged.
                          */
                          public static int i(String tag, String msg) {
                          if (!LOGI_ENABLE ) return 0;
                          if(Constants.LOG_SDCARD_ENABLE) fileLog(tag,msg);
                          return android.util.Log.i(tag, msg);
                          }
                          /**
                          * Send a {@link #INFO} log message and log the exception.
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param msg The message you would like logged.
                          * @param tr An exception to log
                          */
                          public static int i(String tag, String msg, Throwable tr) {
                          if (!LOGI_ENABLE ) return 0;
                          if(Constants.LOG_SDCARD_ENABLE) fileLog(tag,msg);
                          return android.util.Log.i(tag, msg, tr);
                          }
                          /**
                          * Send a {@link #WARN} log message.
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param msg The message you would like logged.
                          */
                          public static int w(String tag, String msg) {
                          if (!LOGW_ENABLE ) return 0;
                          if(Constants.LOG_SDCARD_ENABLE) fileLog(tag,msg);
                          return android.util.Log.w(tag, msg);
                          }
                          /**
                          * Send a {@link #WARN} log message and log the exception.
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param msg The message you would like logged.
                          * @param tr An exception to log
                          */
                          public static int w(String tag, String msg, Throwable tr) {
                          if (!LOGW_ENABLE ) return 0;
                          if(Constants.LOG_SDCARD_ENABLE) fileLog(tag,msg);
                          return android.util.Log.w(tag, msg, tr);
                          }
                          /*
                          * Send a {@link #WARN} log message and log the exception.
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param tr An exception to log
                          */
                          public static int w(String tag, Throwable tr) {
                          if (!LOGW_ENABLE ) return 0;
                          if(Constants.LOG_SDCARD_ENABLE) fileLog(tag,tr.getMessage());
                          return android.util.Log.w(tag, tr);
                          }
                          /**
                          * Send an {@link #ERROR} log message.
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param msg The message you would like logged.
                          */
                          public static int e(String tag, String msg) {
                          if (!LOGE_ENABLE ) return 0;
                          if(Constants.LOG_SDCARD_ENABLE) fileLog(tag,msg);
                          return android.util.Log.e(tag, msg);
                          }
                          /**
                          * Send a {@link #ERROR} log message and log the exception.
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param msg The message you would like logged.
                          * @param tr An exception to log
                          */
                          public static int e(String tag, String msg, Throwable tr) {
                          if (!LOGE_ENABLE ) return 0;
                          if(Constants.LOG_SDCARD_ENABLE) fileLog(tag,msg);
                          return android.util.Log.e(tag, msg, tr);
                          }
                          /**
                          * Handy function to get a loggable stack trace from a Throwable
                          * @param tr An exception to log
                          */
                          public static String getStackTraceString(Throwable tr) {
                          return android.util.Log.getStackTraceString(tr);
                          }
                          /**
                          * Low-level logging call.
                          * @param priority The priority/type of this log message
                          * @param tag Used to identify the source of a log message. It usually identifies
                          * the class or activity where the log call occurs.
                          * @param msg The message you would like logged.
                          * @return The number of bytes written.
                          */
                          public static int println(int priority, String tag, String msg) {
                          return android.util.Log.println(priority, tag, msg);
                          }
                          /**
                          * 打印日志到文件
                          * @param tag
                          * @param msg
                          * @param logFileName
                          */
                          public static void fileLog(String tag, String msg){
                          if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                          return;
                          }
                          try {
                          File logFile = new File(Environment.getExternalStorageDirectory(), Constants.LOG_FILE_NAME);
                          if(!logFile.exists()){
                          logFile.createNewFile();
                          }
                          BufferedWriter bw = new BufferedWriter(new FileWriter(logFile, true));
                          bw.append(new Timestamp(System.currentTimeMillis()).toString())
                          //.append("----").append(new Date() + " : " + tag );
                          .append("----").append(new Date() + " : " + msg).append("\n");
                          bw.close();
                          } catch (Exception e) {
                          }
                          }
                          }


                          14楼2015-09-01 17:50
                          回复
                            package com.juchao.upg.android.util;
                            import java.security.MessageDigest;
                            import java.security.NoSuchAlgorithmException;
                            import android.util.Log;
                            public class MD5 {
                            /**
                            * Encodes a string
                            *
                            * @param str String to encode
                            * @return Encoded String
                            * @throws Exception
                            */
                            public static String crypt(String str)
                            {
                            Log.d("md5", str);
                            if (str == null || str.length() == 0) {
                            throw new IllegalArgumentException("String to encript cannot be null or zero length");
                            }
                            StringBuffer hexString = new StringBuffer();
                            try {
                            MessageDigest md = MessageDigest.getInstance("MD5");
                            md.update(str.getBytes());
                            byte[] hash = md.digest();
                            for (int i = 0; i < hash.length; i++) {
                            if ((0xff & hash[i]) < 0x10) {
                            hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
                            }
                            else {
                            hexString.append(Integer.toHexString(0xFF & hash[i]));
                            }
                            }
                            }
                            catch (NoSuchAlgorithmException e) {
                            e.printStackTrace();
                            }
                            return hexString.toString();
                            }
                            }


                            15楼2015-09-01 17:50
                            回复
                              2026-02-05 17:17:00
                              广告
                              不感兴趣
                              开通SVIP免广告
                              package com.juchao.upg.android.util;
                              import java.security.MessageDigest;
                              import java.security.NoSuchAlgorithmException;
                              import android.util.Log;
                              public class MD5 {
                              /**
                              * Encodes a string
                              *
                              * @param str String to encode
                              * @return Encoded String
                              * @throws Exception
                              */
                              public static String crypt(String str)
                              {
                              Log.d("md5", str);
                              if (str == null || str.length() == 0) {
                              throw new IllegalArgumentException("String to encript cannot be null or zero length");
                              }
                              StringBuffer hexString = new StringBuffer();
                              try {
                              MessageDigest md = MessageDigest.getInstance("MD5");
                              md.update(str.getBytes());
                              byte[] hash = md.digest();
                              for (int i = 0; i < hash.length; i++) {
                              if ((0xff & hash[i]) < 0x10) {
                              hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
                              }
                              else {
                              hexString.append(Integer.toHexString(0xFF & hash[i]));
                              }
                              }
                              }
                              catch (NoSuchAlgorithmException e) {
                              e.printStackTrace();
                              }
                              return hexString.toString();
                              }
                              }


                              16楼2015-09-01 17:52
                              回复