确保每一个包存在一个类文件

This commit is contained in:
zengfantian 2014-12-05 18:19:02 +08:00
parent b51bdb5fa2
commit ff9a9a53d2
21 changed files with 2489 additions and 3 deletions

View File

@ -1,12 +1,71 @@
package com.zftlive.android; package com.zftlive.android;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import android.app.Activity;
import android.app.Application; import android.app.Application;
import android.content.Context;
/** /**
* 整个应用程序Applicaiton * 整个应用程序Applicaiton
* @author 曾繁添 *
* * @author 曾繁添
*
*/ */
public class MApplication extends Application { public class MApplication extends Application {
private static Context instance;
public static Stack<Activity> activitys = new Stack<Activity>();
public static Context gainContext() {
return instance;
}
public void onCreate() {
super.onCreate();
instance = this;
}
private static Map<String, Object> data = new HashMap<String, Object>();
public static void assignData(String strKey, Object strValue) {
if (data.size() > 5) {
throw new RuntimeException("超过允许最大数");
}
data.put(strKey, strValue);
}
public static Object gainData(String strKey) {
return data.get(strKey);
}
public static void pushTask(Activity task) {
activitys.push(task);
}
public static void removeTask(Activity task) {
activitys.remove(task);
}
public static void removeTask(int taskIndex) {
if (activitys.size() > taskIndex)
activitys.remove(taskIndex);
}
public static void removeToTop() {
int end = activitys.size();
int start = 1;
for (int i = end - 1; i >= start; i--) {
activitys.get(i).finish();
}
}
public static void removeAll() {
for (Activity task : activitys) {
task.finish();
}
}
} }

View File

@ -0,0 +1,5 @@
package com.zftlive.android.common;
public class VersionChecker {
}

View File

@ -0,0 +1,7 @@
package com.zftlive.android.entity;
import com.zftlive.android.base.BaseEntity;
public class Config extends BaseEntity {
}

View File

@ -0,0 +1,12 @@
package com.zftlive.android.exception;
import com.zftlive.android.base.BaseException;
/**
* SD卡剩余空间异常
* @author 曾繁添
*
*/
public class NoFreeMbException extends BaseException {
}

View File

@ -0,0 +1,258 @@
package com.zftlive.android.model;
import java.util.ArrayList;
import java.util.List;
/**
* 树节点Model
* @author 曾繁添
*
*/
public class Node {
private String label;//节点显示的文字
private String value;//节点的值
private int icon = -1;//是否显示小图标,-1表示隐藏图标
private int tipCount = 0; //显示tips数量
private String linkURL;//打开连接URL
private Node parent;//父节点
private List<Node> children = new ArrayList<Node>();//子节点
private boolean isChecked = false;//是否处于选中状态
private boolean isExpanded = true;//是否处于展开状态
private boolean hasCheckBox = true;//是否拥有复选框
private boolean isShowTips = true; //是否显示提醒数目
/**
* Node构造函数
* @param label 节点显示的文字
* @param value 节点的值
*/
public Node(String label,String value){
this.label = label;
this.value = value;
}
/**
* 设置父节点
* @param node
*/
public void setParent(Node node){
this.parent = node;
}
/**
* 获得父节点
* @return
*/
public Node getParent(){
return this.parent;
}
/**
* 设置节点文本
* @param label
*/
public void setLabel(String label){
this.label = label;
}
/**
* 获得节点文本
* @return
*/
public String getLabel(){
return this.label;
}
/**
* 设置节点值
* @param value
*/
public void setValue(String value){
this.value = value;
}
/**
* 获得节点值
* @return
*/
public String getValue(){
return this.value;
}
/**
* 设置节点图标文件
* @param icon
*/
public void setIcon(int icon){
this.icon = icon;
}
/**
* 获得图标文件
* @return
*/
public int getIcon(){
return icon;
}
/**
* 获得节点连接URL
* @return
*/
public String getLinkURL() {
return linkURL;
}
/**
* 设置节点连接URL
* @param linkURL
*/
public void setLinkURL(String linkURL) {
this.linkURL = linkURL;
}
/**
* 获得节点tip数量
* @return
*/
public int getTipCount() {
return tipCount;
}
/**
* 设置节点tip数量
* @param tip数量
*/
public void setTipCount(int tipCount) {
this.tipCount = tipCount;
}
/**
* 设置是否显示tips
* @return
*/
public void setIsShowTips(boolean isShowTips){
this.isShowTips = isShowTips;
}
/**
* 获取是否显示tips
* @return
*/
public boolean getIsShowTips(){
return this.isShowTips;
}
/**
* 是否根节点
* @return
*/
public boolean isRoot(){
return parent==null?true:false;
}
/**
* 获得子节点
* @return
*/
public List<Node> getChildren(){
return this.children;
}
/**
* 添加子节点
* @param node
*/
public void add(Node node){
if(!children.contains(node)){
children.add(node);
}
}
/**
* 清除所有子节点
*/
public void clear(){
children.clear();
}
/**
* 删除一个子节点
* @param node
*/
public void remove(Node node){
if(!children.contains(node)){
children.remove(node);
}
}
/**
* 删除指定位置的子节点
* @param location
*/
public void remove(int location){
children.remove(location);
}
/**
* 获得节点的级数,根节点为0
* @return
*/
public int getLevel(){
return parent==null?0:parent.getLevel()+1;
}
/**
* 设置节点选中状态
* @param isChecked
*/
public void setChecked(boolean isChecked){
this.isChecked = isChecked;
}
/**
* 获得节点选中状态
* @return
*/
public boolean isChecked(){
return isChecked;
}
/**
* 设置是否拥有复选框
* @param hasCheckBox
*/
public void setCheckBox(boolean hasCheckBox){
this.hasCheckBox = hasCheckBox;
}
/**
* 是否拥有复选框
* @return
*/
public boolean hasCheckBox(){
return hasCheckBox;
}
/**
* 是否叶节点,即没有子节点的节点
* @return
*/
public boolean isLeaf(){
return children.size()<1?true:false;
}
/**
* 当前节点是否处于展开状态
* @return
*/
public boolean isExpanded(){
return isExpanded;
}
/**
* 设置节点展开状态
* @return
*/
public void setExpanded(boolean isExpanded){
this.isExpanded = isExpanded;
}
/**
* 递归判断父节点是否处于折叠状态,有一个父节点折叠则认为是折叠状态
* @return
*/
public boolean isParentCollapsed(){
if(parent==null)return !isExpanded;
if(!parent.isExpanded())return true;
return parent.isParentCollapsed();
}
/**
* 递归判断所给的节点是否当前节点的父节点
* @param node 所给节点
* @return
*/
public boolean isParent(Node node){
if(parent==null)return false;
if(node.equals(parent))return true;
return parent.isParent(node);
}
}

View File

@ -0,0 +1,54 @@
package com.zftlive.android.model;
import java.io.Serializable;
/**
* 下拉框单选框复选框选项Bean
* @author 曾繁添
* @version 1.0
*/
public class Option implements Serializable,Cloneable{
private static final long serialVersionUID = -724868344947644938L;
private String label = "请选择...";
private String value = "";
public Option() {
}
public Option(String value,String label) {
this.label = label;
this.value = value;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return label;
}
}

View File

@ -0,0 +1,154 @@
package com.zftlive.android.model;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.hardware.Camera;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.SystemClock;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import com.zftlive.android.MApplication;
/**
* 运行环境信息
* @author 曾繁添
* @version 1.0
*/
public final class SysEnv {
/***Log输出标识**/
private static final String TAG = SysEnv.class.getSimpleName();
/***屏幕显示材质**/
private static final DisplayMetrics mDisplayMetrics = new DisplayMetrics();
/**上下文**/
private static final Context context = MApplication.gainContext();
/**操作系统名称(GT-I9100G)***/
public static final String MODEL_NUMBER = Build.MODEL;
/**操作系统名称(I9100G)***/
public static final String DISPLAY_NAME = Build.DISPLAY;
/**操作系统版本(4.4)***/
public static final String OS_VERSION = Build.VERSION.RELEASE;;
/**应用程序版本***/
public static final String APP_VERSION = getVersion();
/***屏幕宽度**/
public static final int SCREEN_WIDTH = getDisplayMetrics().widthPixels;
/***屏幕高度**/
public static final int SCREEN_HEIGHT = getDisplayMetrics().heightPixels;
/***本机手机号码**/
public static final String PHONE_NUMBER = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number();
/***设备ID**/
public static final String DEVICE_ID = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
/***设备IMEI号码**/
public static final String IMEI = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getSimSerialNumber();
/***设备IMSI号码**/
public static final String IMSI = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
/**获取系统显示材质***/
public static DisplayMetrics getDisplayMetrics(){
WindowManager windowMgr = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
windowMgr.getDefaultDisplay().getMetrics(mDisplayMetrics);
return mDisplayMetrics;
}
/**获取摄像头支持的分辨率***/
public static List<Camera.Size> getSupportedPreviewSizes(Camera camera){
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> sizeList = parameters.getSupportedPreviewSizes();
return sizeList;
}
/**
* 获取应用程序版本versionName
* @return 当前应用的版本号
*/
public static String getVersion() {
PackageManager manager = context.getPackageManager();
PackageInfo info = null;
try {
info = manager.getPackageInfo(context.getPackageName(), 0);
} catch (NameNotFoundException e) {
Log.e(TAG, "获取应用程序版本失败,原因:"+e.getMessage());
return "";
}
return info.versionName;
}
/**
* 获取系统内核版本
* @return
*/
public static String getKernelVersion(){
String strVersion= "";
FileReader mFileReader = null;
BufferedReader mBufferedReader = null;
try {
mFileReader = new FileReader("/proc/version");
mBufferedReader = new BufferedReader(mFileReader, 8192);
String str2 = mBufferedReader.readLine();
strVersion = str2.split("\\s+")[2];//KernelVersion
} catch (Exception e) {
Log.e(TAG, "获取系统内核版本失败,原因:"+e.getMessage());
}finally{
try {
mBufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return strVersion;
}
/***
* 获取MAC地址
* @return
*/
public static String getMacAddress(){
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if(wifiInfo.getMacAddress()!=null){
return wifiInfo.getMacAddress();
} else {
return "";
}
}
/**
* 获取运行时间
* @return 运行时间(单位/s)
*/
public static long getRunTimes() {
long ut = SystemClock.elapsedRealtime() / 1000;
if (ut == 0) {
ut = 1;
}
return ut;
}
}

View File

@ -0,0 +1,15 @@
package com.zftlive.android.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class NetworkStateService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -0,0 +1,142 @@
package com.zftlive.android.tools;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.util.Log;
/**
* 基于静态内部类实现的单例保证线程安全的网络信息工具类 <per> 使用该工具类之前记得在AndroidManifest.xml添加权限许可 <xmp>
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
* </xmp> </per>
*
* 安卓判断网络状态只需要在相应的Activity的相关方法onCreat/onResum调用一行代码即可
* NetWorkUtils.getInstance(getActivity()).validateNetWork();
*
*
*
* @author 曾繁添
* @version 1.0
*/
public class ToolNetwork {
public final static String NETWORK_CMNET = "CMNET";
public final static String NETWORK_CMWAP = "CMWAP";
public final static String NETWORK_WIFI = "WIFI";
public final static String TAG = "NetWorkUtils";
private static NetworkInfo networkInfo = null;
private Context mContext = null;
private ToolNetwork() {
}
public static ToolNetwork getInstance() {
return SingletonHolder.instance;
}
public ToolNetwork init(Context context){
this.mContext = context;
return this;
}
/**
* 判断网络是否可用
*
* @return /
*/
public boolean isAvailable() {
ConnectivityManager manager = (ConnectivityManager) mContext
.getApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
if (null == manager) {
return false;
}
networkInfo = manager.getActiveNetworkInfo();
if (null == networkInfo || !networkInfo.isAvailable()) {
return false;
}
return true;
}
/**
* 判断网络是否已连接
*
* @return /
*/
public boolean isConnected() {
if (!isAvailable()) {
return false;
}
if (!networkInfo.isConnected()) {
return false;
}
return true;
}
/**
* 检查当前环境网络是否可用不可用跳转至开启网络界面,不设置网络强制关闭当前Activity
*/
public void validateNetWork() {
if (!isConnected()) {
Builder dialogBuilder = new AlertDialog.Builder(mContext);
dialogBuilder.setTitle("网络设置");
dialogBuilder.setMessage("网络不可用,是否现在设置网络?");
dialogBuilder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
((Activity) mContext).startActivityForResult(
new Intent(
Settings.ACTION_SETTINGS),
which);
}
});
dialogBuilder.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialogBuilder.create();
dialogBuilder.show();
}
}
/**
* 获取网络连接信息</br> 无网络</br> WIFI网络WIFI</br> WAP网络CMWAP</br>
* NET网络CMNET</br>
*
* @return
*/
public String getNetworkType() {
if (isConnected()) {
int type = networkInfo.getType();
if (ConnectivityManager.TYPE_MOBILE == type) {
Log.i(TAG,
"networkInfo.getExtraInfo()-->"
+ networkInfo.getExtraInfo());
if (NETWORK_CMWAP.equals(networkInfo.getExtraInfo()
.toLowerCase())) {
return NETWORK_CMWAP;
} else {
return NETWORK_CMNET;
}
} else if (ConnectivityManager.TYPE_WIFI == type) {
return NETWORK_WIFI;
}
}
return "";
}
private static class SingletonHolder {
private static ToolNetwork instance = new ToolNetwork();
}
}

View File

@ -0,0 +1,467 @@
package com.zftlive.android.tools;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.media.ExifInterface;
import android.view.View;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.zftlive.android.model.SysEnv;
/**
* 图片工具类
* @author 曾繁添
* @version 1.0
*/
public class ToolPicture {
/**
* 截取应用程序界面去除状态栏
* @param activity 界面Activity
* @return Bitmap对象
*/
public static Bitmap takeScreenShot(Activity activity){
View view =activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
Rect rect = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
Bitmap bitmap2 = Bitmap.createBitmap(bitmap,0,statusBarHeight, SysEnv.SCREEN_WIDTH, SysEnv.SCREEN_HEIGHT - statusBarHeight);
view.destroyDrawingCache();
return bitmap2;
}
/**
* 截取应用程序界面
* @param activity 界面Activity
* @return Bitmap对象
*/
public static Bitmap takeFullScreenShot(Activity activity){
activity.getWindow().getDecorView().setDrawingCacheEnabled(true);
Bitmap bmp = activity.getWindow().getDecorView().getDrawingCache();
View view = activity.getWindow().getDecorView();
Bitmap bmp2 = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);
//view.draw(new Canvas(bmp2));
//bmp就是截取的图片了可通过bmp.compress(CompressFormat.PNG, 100, new FileOutputStream(file));把图片保存为文件
//1得到状态栏高度
Rect rect = new Rect();
view.getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
System.out.println("状态栏高度:" + statusBarHeight);
//2得到标题栏高度
int wintop = activity.getWindow().findViewById(android.R.id.content).getTop();
int titleBarHeight = wintop - statusBarHeight;
System.out.println("标题栏高度:" + titleBarHeight);
// //把两个bitmap合到一起
// Bitmap bmpall=Biatmap.createBitmap(width,height,Config.ARGB_8888);
// Canvas canvas=new Canvas(bmpall);
// canvas.drawBitmap(bmp1,x,y,paint);
// canvas.drawBitmap(bmp2,x,y,paint);
return bmp;
}
/**
* 根据指定内容生成自定义宽高的二维码图片
* @param content 需要生成二维码的内容
* @param width 二维码宽度
* @param height 二维码高度
* @throws WriterException 生成二维码异常
*/
public static Bitmap makeQRImage(String content, int width, int height)
throws WriterException {
// 判断URL合法性
if (ToolString.isNoBlankAndNoNull(content))
return null;
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 图像数据转换使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(content,
BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
// 按照二维码的算法逐个生成二维码的图片两个for循环是图片横列扫描的结果
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (bitMatrix.get(x, y))
pixels[y * width + x] = 0xff000000;
else
pixels[y * width + x] = 0xffffffff;
}
}
// 生成二维码图片的格式使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
/**
* 读取图片属性旋转的角度
*
* @param path 图片绝对路径
* @return degree 旋转的角度
* @throws IOException
*/
public static int gainPictureDegree(String path) throws Exception {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (Exception e) {
throw(e);
}
return degree;
}
/**
* 旋转图片
* @param angle 角度
* @param bitmap 源bitmap
* @return Bitmap 旋转角度之后的bitmap
*/
public static Bitmap rotaingBitmap(int angle,Bitmap bitmap) {
//旋转图片 动作
Matrix matrix = new Matrix();;
matrix.postRotate(angle);
//重新构建Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix, true);
return resizedBitmap;
}
/**
* Drawable转成Bitmap
* @param drawable
* @return
*/
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof NinePatchDrawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
} else {
return null;
}
}
/**
* 从资源文件中获取图片
* @param context 上下文
* @param drawableId 资源文件id
* @return
*/
public static Bitmap gainBitmap(Context context,int drawableId){
Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), drawableId);
return bmp;
}
/**
* 灰白图片去色
* @param bitmap 需要灰度的图片
* @return 去色之后的图片
*/
public static Bitmap toBlack(Bitmap bitmap) {
Bitmap resultBMP = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
Bitmap.Config.RGB_565);
Canvas c = new Canvas(resultBMP);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bitmap, 0, 0, paint);
return resultBMP;
}
/**
* 将bitmap转成 byte数组
*
* @param bitmap
* @return
*/
public static byte[] toBtyeArray(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/**
* 将byte数组转成 bitmap
*
* @param b
* @return
*/
public static Bitmap bytesToBimap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}
/**
* 将Bitmap转换成指定大小
*
* @param bitmap 需要改变大小的图片
* @param width
* @param height
* @return
*/
public static Bitmap createBitmapBySize(Bitmap bitmap, int width, int height) {
return Bitmap.createScaledBitmap(bitmap, width, height, true);
}
/**
* 在图片右下角添加水印
* @param srcBMP 原图
* @param markBMP 水印图片
* @return 合成水印后的图片
*/
public static Bitmap composeWatermark(Bitmap srcBMP, Bitmap markBMP) {
if (srcBMP == null) {
return null;
}
// 创建一个新的和SRC长度宽度一样的位图
Bitmap newb = Bitmap.createBitmap(srcBMP.getWidth(), srcBMP.getHeight(), Config.ARGB_8888);
Canvas cv = new Canvas(newb);
// 00坐标开始画入原图
cv.drawBitmap(srcBMP, 0, 0, null);
// 在原图的右下角画入水印
cv.drawBitmap(markBMP, srcBMP.getWidth() - markBMP.getWidth() + 5, srcBMP.getHeight() - markBMP.getHeight() + 5, null);
// 保存
cv.save(Canvas.ALL_SAVE_FLAG);
// 存储
cv.restore();
return newb;
}
/**
* 将图片转成指定弧度角度的图片
*
* @param bitmap 需要修改的图片
* @param pixels 圆角的弧度
* @return 圆角图片
*/
public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
//根据图片创建画布
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(0xff424242);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* 缩放图片
*
* @param bmp 需要缩放的图片源
* @param newW 需要缩放成的图片宽度
* @param newH 需要缩放成的图片高度
* @return 缩放后的图片
*/
public static Bitmap zoom(Bitmap bmp, int newW, int newH) {
// 获得图片的宽高
int width = bmp.getWidth();
int height = bmp.getHeight();
// 计算缩放比例
float scaleWidth = ((float) newW) / width;
float scaleHeight = ((float) newH) / height;
// 取得想要缩放的matrix参数
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 得到新的图片
Bitmap newbm = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix,true);
return newbm;
}
/**
* 获取验证码图片
* @param width 验证码宽度
* @param height 验证码高度
* @return 验证码Bitmap对象
*/
public synchronized static Bitmap makeValidateCode(int width, int height){
return ValidateCodeGenerator.createBitmap(width, height);
}
/**
* 获取验证码值
* @return 验证码字符串
*/
public synchronized static String gainValidateCodeValue(){
return ValidateCodeGenerator.getCode();
}
/**
* 随机生成验证码内部类
*
*/
final static class ValidateCodeGenerator{
private static final char[] CHARS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
//default settings
private static final int DEFAULT_CODE_LENGTH = 4;
private static final int DEFAULT_FONT_SIZE = 20;
private static final int DEFAULT_LINE_NUMBER = 3;
private static final int BASE_PADDING_LEFT = 5, RANGE_PADDING_LEFT = 10, BASE_PADDING_TOP = 15, RANGE_PADDING_TOP = 10;
private static final int DEFAULT_WIDTH = 60, DEFAULT_HEIGHT = 30;
//variables
private static String value;
private static int padding_left, padding_top;
private static Random random = new Random();
public static Bitmap createBitmap(int width,int height) {
padding_left = 0;
//创建画布
Bitmap bp = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas c = new Canvas(bp);
//随机生成验证码字符
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < DEFAULT_CODE_LENGTH; i++) {
buffer.append(CHARS[random.nextInt(CHARS.length)]);
}
value = buffer.toString();
//设置颜色
c.drawColor(Color.WHITE);
//设置画笔大小
Paint paint = new Paint();
paint.setTextSize(DEFAULT_FONT_SIZE);
for (int i = 0; i < value.length(); i++) {
//随机样式
randomTextStyle(paint);
padding_left += BASE_PADDING_LEFT + random.nextInt(RANGE_PADDING_LEFT);
padding_top = BASE_PADDING_TOP + random.nextInt(RANGE_PADDING_TOP);
c.drawText(value.charAt(i) + "", padding_left, padding_top, paint);
}
for (int i = 0; i < DEFAULT_LINE_NUMBER; i++) {
drawLine(c, paint);
}
//保存
c.save(Canvas.ALL_SAVE_FLAG);
c.restore();
return bp;
}
public static String getCode() {
return value;
}
private static void randomTextStyle(Paint paint) {
int color = randomColor(1);
paint.setColor(color);
paint.setFakeBoldText(random.nextBoolean());//true为粗体false为非粗体
float skewX = random.nextInt(11) / 10;
skewX = random.nextBoolean() ? skewX : -skewX;
paint.setTextSkewX(skewX); //float类型参数负数表示右斜整数左斜
paint.setUnderlineText(true); //true为下划线false为非下划线
paint.setStrikeThruText(true); //true为删除线false为非删除线
}
private static void drawLine(Canvas canvas, Paint paint) {
int color = randomColor(1);
int startX = random.nextInt(DEFAULT_WIDTH);
int startY = random.nextInt(DEFAULT_HEIGHT);
int stopX = random.nextInt(DEFAULT_WIDTH);
int stopY = random.nextInt(DEFAULT_HEIGHT);
paint.setStrokeWidth(1);
paint.setColor(color);
canvas.drawLine(startX, startY, stopX, stopY, paint);
}
private static int randomColor(int rate) {
int red = random.nextInt(256) / rate;
int green = random.nextInt(256) / rate;
int blue = random.nextInt(256) / rate;
return Color.rgb(red, green, blue);
}
}
}

View File

@ -0,0 +1,72 @@
package com.zftlive.android.tools;
import java.io.InputStream;
import java.util.Properties;
import android.content.Context;
import com.zftlive.android.MApplication;
/**
* 配置文件工具类
*
* @author 曾繁添
* @version 1.0
*
*/
public final class ToolProperties extends Properties {
private static Properties property = new Properties();
public static String readAssetsProp(String fileName, String key) {
String value = "";
try {
InputStream in = MApplication.gainContext().getAssets().open(fileName);
property.load(in);
value = property.getProperty(key);
} catch (Exception e1) {
e1.printStackTrace();
}
return value;
}
public static String readAssetsProp(Context context,String fileName, String key) {
String value = "";
try {
InputStream in = context.getAssets().open(fileName);
property.load(in);
value = property.getProperty(key);
} catch (Exception e1) {
e1.printStackTrace();
}
return value;
}
public static String readAssetsProp(String fileName, String key,String defaultValue) {
String value = "";
try {
InputStream in = MApplication.gainContext().getAssets().open(fileName);
property.load(in);
value = property.getProperty(key, defaultValue);
} catch (Exception e1) {
e1.printStackTrace();
}
return value;
}
public static String readAssetsProp(Context context,String fileName, String key,String defaultValue) {
String value = "";
try {
InputStream in = context.getAssets().open(fileName);
property.load(in);
value = property.getProperty(key, defaultValue);
} catch (Exception e1) {
e1.printStackTrace();
}
return value;
}
}

View File

@ -0,0 +1,94 @@
package com.zftlive.android.tools;
import java.lang.reflect.Field;
import android.content.Context;
import android.util.Log;
import com.zftlive.android.MApplication;
/**
* 获取资源工具类
* @author 曾繁添
* @version 1.0
*/
public class ToolResource {
private static final String TAG = ToolResource.class.getName();
private static Context mContext = MApplication.gainContext();
private static Class<?> CDrawable = null;
private static Class<?> CLayout = null;
private static Class<?> CId = null;
private static Class<?> CAnim = null;
private static Class<?> CStyle = null;
private static Class<?> CString = null;
private static Class<?> CArray = null;
static{
try{
CDrawable = Class.forName(mContext.getPackageName() + ".R$drawable");
CLayout = Class.forName(mContext.getPackageName() + ".R$layout");
CId = Class.forName(mContext.getPackageName() + ".R$id");
CAnim = Class.forName(mContext.getPackageName() + ".R$anim");
CStyle = Class.forName(mContext.getPackageName() + ".R$style");
CString = Class.forName(mContext.getPackageName() + ".R$string");
CArray = Class.forName(mContext.getPackageName() + ".R$array");
}catch(ClassNotFoundException e){
Log.i(TAG,e.getMessage());
}
}
public static int getDrawableId(String resName){
return getResId(CDrawable,resName);
}
public static int getLayoutId(String resName){
return getResId(CLayout,resName);
}
public static int getIdId(String resName){
return getResId(CId,resName);
}
public static int getAnimId(String resName){
return getResId(CAnim,resName);
}
public static int getStyleId(String resName){
return getResId(CStyle,resName);
}
public static int getStringId(String resName){
return getResId(CString,resName);
}
public static int getArrayId(String resName){
return getResId(CArray,resName);
}
private static int getResId(Class<?> resClass,String resName){
if(resClass == null){
Log.i(TAG,"getRes(null," + resName + ")");
throw new IllegalArgumentException("ResClass is not initialized. Please make sure you have added neccessary resources. Also make sure you have " + mContext.getPackageName() + ".R$* configured in obfuscation. field=" + resName);
}
try {
Field field = resClass.getField(resName);
return field.getInt(resName);
} catch (Exception e) {
Log.i(TAG, "getRes(" + resClass.getName() + ", " + resName + ")");
Log.i(TAG, "Error getting resource. Make sure you have copied all resources (res/) from SDK to your project. ");
Log.i(TAG, e.getMessage());
}
return -1;
}
}

View File

@ -0,0 +1,105 @@
package com.zftlive.android.tools;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import com.zftlive.android.MApplication;
/**
* 发送短信验证码工具类
* @author 曾繁添
* @version 1.0
*
*/
public class ToolSMS {
public static String APPKEY = "25c13dc2e1c4";
public static String APPSECRET = "14340f710d155024867d4870786d4c10";
public static String CHINA = "86";
private static IValidateSMSCode mIValidateSMSCode;
private static Handler mSMSHandle = new MySMSHandler();
private static Context context = MApplication.gainContext();
public static void initSDK(String appkey, String appSecrect){
// 初始化短信SDK
SMSSDK.initSDK(context, appkey, appSecrect);
//注册回调监听接口
SMSSDK.registerEventHandler(new EventHandler() {
public void afterEvent(int event, int result, Object data) {
Message msg = new Message();
msg.arg1 = event;
msg.arg2 = result;
msg.obj = data;
mSMSHandle.sendMessage(msg);
}
});
}
/**
* 请求获取短信验证码
* @param phone 手机号
*/
public static void getVerificationCode(String phone){
SMSSDK.getVerificationCode(CHINA, phone);
}
/**
* 提交短信验证码校验是否正确
* @param phone 手机号
* @param validateCode 手机短信验证码
*/
public static void submitVerificationCode(String phone, String validateCode,IValidateSMSCode callback){
mIValidateSMSCode = callback;
SMSSDK.submitVerificationCode(CHINA, phone, validateCode);
}
/**
* 释放资源
*/
public static void release(){
// 销毁回调监听接口
SMSSDK.unregisterAllEventHandler();
}
/**
* 消息处理Handle
*/
private static class MySMSHandler extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int event = msg.arg1;
int result = msg.arg2;
Object data = msg.obj;
if (result == SMSSDK.RESULT_COMPLETE) {
//提交验证码成功
if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
//验证成功回调
if(null != mIValidateSMSCode){
mIValidateSMSCode.onSucced();
}
}
} else {
Throwable exption = ((Throwable) data);
//验证成功回调
if(null != mIValidateSMSCode){
mIValidateSMSCode.onFailed(exption);
}
}
}
}
/**
* 提交短信验证码回调接口
*/
public interface IValidateSMSCode{
void onSucced();
void onFailed(Throwable e);
}
}

View File

@ -0,0 +1,110 @@
package com.zftlive.android.tools;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.Handler;
import android.os.Message;
/**
* 访问WebService的工具类,
*
* @author 曾繁添
* @version 1.0
*
*/
public class ToolSOAP {
// 含有3个线程的线程池
private static final ExecutorService executorService = Executors.newFixedThreadPool(3);
/**
*
* @param url WebService服务器地址
* @param namespace 命名空间
* @param methodName WebService的调用方法名
* @param properties WebService的参数
* @param webServiceCallBack 返回结果回调接口
*/
public static void callService(String url,final String namespace,final String methodName,HashMap<String,String> properties,final WebServiceCallBack webServiceCallBack) {
// 创建HttpTransportSE对象传递WebService服务器地址
final HttpTransportSE httpTransportSE = new HttpTransportSE(url);
// 创建SoapObject对象
SoapObject soapObject = new SoapObject(namespace, methodName);
// SoapObject添加参数
if (properties != null) {
for (Iterator<Map.Entry<String, String>> it = properties.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, String> entry = it.next();
soapObject.addProperty(entry.getKey(), entry.getValue());
}
}
// 实例化SoapSerializationEnvelope传入WebService的SOAP协议的版本号
final SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// 设置是否调用的是.Net开发的WebService
soapEnvelope.setOutputSoapObject(soapObject);
soapEnvelope.dotNet = true;
httpTransportSE.debug = true;
// 用于子线程与主线程通信的Handler
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == 0){
webServiceCallBack.onSucced((SoapObject) msg.obj);
}else{
webServiceCallBack.onFailure((String)msg.obj);
}
}
};
// 开启线程去访问WebService
executorService.submit(new Runnable() {
@Override
public void run() {
SoapObject resultSoapObject = null;
Message mgs = mHandler.obtainMessage();
try {
httpTransportSE.call(namespace + methodName, soapEnvelope);
if (soapEnvelope.getResponse() != null) {
// 获取服务器响应返回的SoapObject
resultSoapObject = (SoapObject) soapEnvelope.bodyIn;
}
mgs.what = 0;
mgs.obj = resultSoapObject;
} catch (Exception e) {
mgs.what = 1;
mgs.obj = e.getMessage();
}
// 将获取的消息利用Handler发送到主线程
mHandler.sendMessage(mgs);
}
});
}
/**
* WebService回调接口
*
*/
public interface WebServiceCallBack {
public void onSucced(SoapObject result);
public void onFailure(String result);
}
}

View File

@ -0,0 +1,67 @@
package com.zftlive.android.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;
/**
* 字符串工具类
* @author 曾繁添
*
*/
public class ToolString {
/**
* 获取UUID
* @return 32UUID小写字符串
*/
public static String gainUUID(){
String strUUID = UUID.randomUUID().toString();
strUUID = strUUID.replaceAll("-", "").toLowerCase();
return strUUID;
}
/**
* 判断字符串是否非空非null
* @param strParm 需要判断的字符串
* @return 真假
*/
public static boolean isNoBlankAndNoNull(String strParm)
{
return (strParm == null) || (strParm.equals(""));
}
/**
* 将流转成字符串
* @param is 输入流
* @return
* @throws Exception
*/
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
/**
* 将文件转成字符串
* @param file 文件
* @return
* @throws Exception
*/
public static String getStringFromFile(File file) throws Exception {
FileInputStream fin = new FileInputStream(file);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
}

View File

@ -0,0 +1,155 @@
package com.zftlive.android.tools;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.zftlive.android.MApplication;
/**
* 自定义Toast控件
* @author 曾繁添
* @version 1.0
*/
public class ToolToast {
private static Toast mToast;
private static Handler mHandler = new Handler();
private static Runnable r = new Runnable() {
public void run() {
mToast.cancel();
}
};
/**
* 弹出较长时间提示信息
* @param context 上下文对象
* @param msg 要显示的信息
*/
public static void showLong(Context context, String msg){
buildToast(context,msg,Toast.LENGTH_LONG).show();
}
/**
* 弹出较长时间提示信息
* @param msg 要显示的信息
*/
public static void showLong(String msg){
buildToast(MApplication.gainContext(),msg,Toast.LENGTH_LONG).show();
}
/**
* 弹出较短时间提示信息
* @param context 上下文对象
* @param msg 要显示的信息
*/
public static void showShort(Context context, String msg){
buildToast(context,msg,Toast.LENGTH_SHORT).show();
}
/**
* 弹出较短时间提示信息
* @param msg 要显示的信息
*/
public static void showShort(String msg){
buildToast(MApplication.gainContext(),msg,Toast.LENGTH_SHORT).show();
}
/**
* 构造Toast
* @param context 上下文
* @return
*/
private static Toast buildToast(Context context,String msg,int duration){
return buildToast(context,msg,duration,"#d83636",16);
}
/**
* 构造Toast
* @param context 上下文
* @param msg 消息
* @param duration 显示时间
* @param bgColor 背景颜色
* @return
*/
public static Toast buildToast(Context context,String msg,int duration,String bgColor){
return buildToast(context,msg,duration,bgColor,16);
}
/**
* 构造Toast
* @param context 上下文
* @param msg 消息
* @param duration 显示时间
* @param bgColor 背景颜色
* @param textSp 文字大小
* @return
*/
public static Toast buildToast(Context context,String msg,int duration,String bgColor,int textSp){
return buildToast(context,msg,duration,bgColor,textSp,10);
}
/**
* 构造Toast
* @param context 上下文
* @param msg 消息
* @param duration 显示时间
* @param bgColor 背景颜色
* @param textSp 文字大小
* @param cornerRadius 四边圆角弧度
* @return
*/
@SuppressLint("NewApi")
public static Toast buildToast(Context context,String msg,int duration,String bgColor,int textSp,int cornerRadius){
mHandler.removeCallbacks(r);
if(null == mToast){
//构建Toast
mToast = Toast.makeText(context, null, duration);
mToast.setGravity(Gravity.CENTER, 0, 0);
//取消toast
mHandler.postDelayed(r, duration);
}
//设置Toast文字
TextView tv = new TextView(context);
int dpPadding = ToolUnit.dipTopx(10);
tv.setPadding(dpPadding, dpPadding, dpPadding, dpPadding);
tv.setGravity(Gravity.CENTER);
tv.setText(msg);
tv.setTextColor(Color.WHITE);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSp);
//Toast文字TextView容器
LinearLayout mLayout = new LinearLayout(context);
GradientDrawable shape = new GradientDrawable();
shape.setColor(Color.parseColor(bgColor));
shape.setCornerRadius(cornerRadius);
shape.setStroke(1, Color.parseColor(bgColor));
shape.setAlpha(180);
mLayout.setBackground(shape);
mLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
//设置layout_gravity
params.gravity = Gravity.CENTER;
mLayout.setLayoutParams(params);
//设置gravity
mLayout.setGravity(Gravity.CENTER);
mLayout.addView(tv);
//将自定义View覆盖Toast的View
mToast.setView(mLayout);
return mToast;
}
}

View File

@ -0,0 +1,60 @@
package com.zftlive.android.tools;
import android.util.DisplayMetrics;
import com.zftlive.android.model.SysEnv;
/**
* 单位换算工具类
* @author 曾繁添<br>
* px 像素 <br>
in 英寸<br>
mm 毫米<br>
pt 1/72 英寸<br>
dp 一个基于density的抽象单位如果一个160dpi的屏幕1dp=1px<br>
dip 等同于dp<br>
sp 同dp相似但还会根据用户的字体大小偏好来缩放<br>
建议使用sp作为文本的单位其它用dip<br>
布局时尽量使用单位dip少使用px <br>
*/
public class ToolUnit {
/**设备显示材质**/
private static DisplayMetrics mDisplayMetrics = SysEnv.getDisplayMetrics();
/**
* sp转换px
* @param spValue sp数值
* @return px数值
*/
public static int spTopx(float spValue) {
return (int) (spValue * mDisplayMetrics.scaledDensity + 0.5f);
}
/**
* px转换sp
* @param pxValue px数值
* @return sp数值
*/
public static int pxTosp(float pxValue) {
return (int) (pxValue / mDisplayMetrics.scaledDensity + 0.5f);
}
/**
* dip转换px
* @param dipValue dip数值
* @return px数值
*/
public static int dipTopx(int dipValue) {
return (int) (dipValue * mDisplayMetrics.density + 0.5f);
}
/**
* px转换dip
* @param pxValue px数值
* @return dip数值
*/
public static int pxTodip(float pxValue) {
return (int) (pxValue / mDisplayMetrics.density + 0.5f);
}
}

View File

@ -0,0 +1,306 @@
package com.zftlive.android.tools;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
/**
* XMPP工具类
* @author 曾繁添
* @version 1.0
*/
public class ToolXMPP {
private static ToolXMPP mToolXMPP = null;
private static XMPPConnection connection = null;
/**聊天窗口管理map集合**/
private Map<String, Chat> chatManage = new HashMap<String, Chat>();
private ToolXMPP() {
}
/**
* 对外公开的实例化接口
* @return
*/
public static ToolXMPP newInstance(String address,int port){
try {
if(mToolXMPP == null){
mToolXMPP = new ToolXMPP();
ConnectionConfiguration config = new ConnectionConfiguration(address,port);
/** 是否启用调试 */
config.setDebuggerEnabled(true);
connection = new XMPPConnection(config);
}
} catch (Exception e) {
System.out.println("创建XMMPP失败原因"+e.getMessage());
e.printStackTrace();
}
return mToolXMPP;
}
/**
* 获取Openfire连接
* @return
*/
public static XMPPConnection getConnection(){
return connection;
}
/**
* 连接服务器
* @return
*/
public boolean connect() {
try {
if(null != connection){
connection.connect();
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 断开连接
*/
public void disConnect() {
if(null != connection){
connection.disconnect();
}
}
/**
* 登录
*
* @param username 登录帐号
* @param pswd 登录密码
* @return 是否登录成功
*/
public boolean login(String username, String pswd) {
try {
if (connection == null) return false;
connection.login(username, pswd);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 获取或创建聊天窗口
* @param friend 好友名
* @param listenter 聊天监听器
* @return
*/
public Chat getFriendChat(String friend, MessageListener listenter) {
if(getConnection()==null)
return null;
/** 判断是否创建聊天窗口 */
for (String fristr : chatManage.keySet()) {
if (fristr.equals(friend)) {
// 存在聊天窗口则返回对应聊天窗口
return chatManage.get(fristr);
}
}
/** 创建聊天窗口 */
Chat chat = getConnection().getChatManager().createChat(friend + "@"+getConnection().getServiceName(), listenter);
/** 添加聊天窗口到chatManage */
chatManage.put(friend, chat);
return chat;
}
/**
* 创建聊天会话
* @param toUser 聊天对象id
* @param domain
*/
public Chat createChat(String toUser,String domain){
Chat mChat = connection.getChatManager().createChat(toUser+domain,mMessageListener);
return mChat;
}
/**
* 发送消息
* @param strMsg 消息内容
*/
public void sendMessage(Chat chat,String strMsg){
try {
//发送消息
chat.sendMessage(strMsg);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 修改密码
* @param newPswd 新密码
* @return 是否修改成功
*/
public static boolean changePassword(String newPswd)
{
try {
connection.getAccountManager().changePassword(newPswd);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 设置用户状态
*/
public void setPresence(int code) {
if (connection == null)
return;
Presence presence;
switch (code) {
case 0:
presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
Log.v("state", "设置在线");
break;
case 1:
presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.chat);
connection.sendPacket(presence);
Log.v("state", "设置Q我吧");
System.out.println(presence.toXML());
break;
case 2:
presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.dnd);
connection.sendPacket(presence);
Log.v("state", "设置忙碌");
System.out.println(presence.toXML());
break;
case 3:
presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.away);
connection.sendPacket(presence);
Log.v("state", "设置离开");
System.out.println(presence.toXML());
break;
case 4:
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
presence = new Presence(Presence.Type.unavailable);
presence.setPacketID(Packet.ID_NOT_AVAILABLE);
presence.setFrom(connection.getUser());
presence.setTo(entry.getUser());
connection.sendPacket(presence);
System.out.println(presence.toXML());
}
// 向同一用户的其他客户端发送隐身状态
presence = new Presence(Presence.Type.unavailable);
presence.setPacketID(Packet.ID_NOT_AVAILABLE);
presence.setFrom(connection.getUser());
presence.setTo(StringUtils.parseBareAddress(connection.getUser()));
connection.sendPacket(presence);
Log.v("state", "设置隐身");
break;
case 5:
presence = new Presence(Presence.Type.unavailable);
connection.sendPacket(presence);
Log.v("state", "设置离线");
break;
default:
break;
}
}
/**
* 删除当前用户
* @param connection
* @return
*/
public boolean deleteAccount()
{
try {
connection.getAccountManager().deleteAccount();
return true;
} catch (Exception e) {
return false;
}
}
/**
* 退出
*/
public void exit() {
// 状态
Presence presence = new Presence(Presence.Type.unavailable);
connection.sendPacket(presence);
//断开连接
disConnect();
}
/**
* 消息监听器
*/
public MessageListener mMessageListener = new MessageListener(){
@Override
public void processMessage(Chat arg0, Message msg) {
Log.i("ToolXMPP", "from="+msg.getFrom() + "to="+msg.getTo() + "body="+msg.getBody() + "subject="+msg.getSubject());
//登录用户
StringUtils.parseName(getConnection().getUser());
//发送消息用户
msg.getFrom();
//消息内容
String body = msg.getBody();
boolean left = body.substring(0, 1).equals("{");
boolean right = body.substring(body.length()-1, body.length()).equals("}");
if(left&&right){
try {
JSONObject obj = new JSONObject(body);
String type = obj.getString("messageType");
String chanId = obj.getString("chanId");
String chanName = obj.getString("chanName");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
/**
* 单人聊天信息监听类
*
*/
public ChatManagerListener mChatManagerListener = new ChatManagerListener(){
public void chatCreated(Chat chat, boolean arg1)
{
chat.addMessageListener(mMessageListener);
}
};
}

View File

@ -0,0 +1,39 @@
package com.zftlive.android.tools;
import com.thoughtworks.xstream.XStream;
/**
* XML工具类
* @author 曾繁添
*
*/
public class ToolXml {
/**
* java 转换成xml
*
* @Title: toXml
* @Description: 将JavaBean转成XML
* @param bean 对象实例
* @return String xml字符串
*/
public static String toXml(Object bean) {
XStream xstream = new XStream();
xstream.processAnnotations(bean.getClass());
return xstream.toXML(bean);
}
/**
* 将传入xml文本转换成Java对象
* @param xml
* @param bean xml对应的class类
* @return T xml对应的class类的实例对象 调用的方法实例
* PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class);
*/
public static <T> T toBean(String xml, Class<T> bean) {
XStream xstream = new XStream();
xstream.processAnnotations(bean);
T obj = (T) xstream.fromXML(xml);
return obj;
}
}

View File

@ -0,0 +1,51 @@
package com.zftlive.android.view;
import com.zftlive.android.MApplication;
/**
* 自定义View需要用到的常量方法
* @author 曾繁添
*
*/
public interface IView {
/**应用的包名称**/
String PACKAGE_NAME = MApplication.gainContext().getPackageName();
/***资源类型-array**/
String ARRAY = "array";
/***资源类型-attr**/
String ATTR = "attr";
/***资源类型-bool**/
String BOOL = "bool";
/***资源类型-color**/
String COLOR = "color";
/***资源类型-dimen**/
String DIMEN = "dimen";
/***资源类型-drawable**/
String DRAWABLE = "drawable";
/***资源类型-id**/
String ID = "id";
/***资源类型-id**/
String INTEGER = "integer";
/***资源类型-layout**/
String LAYOUT = "layout";
/***资源类型-drawable**/
String STRING = "string";
/***资源类型-style**/
String STYLE = "style";
/***资源类型-styleable**/
String STYLEABLE = "styleable";
}

View File

@ -0,0 +1,254 @@
package com.zftlive.android.widget;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* 自定义时长的Toast
* @author 曾繁添
* @version 1.0
*
*/
public class MyToast {
public static MyToast makeText(Context context, CharSequence text, int duration)
{
MyToast result = new MyToast(context);
LinearLayout mLayout=new LinearLayout(context);
TextView tv = new TextView(context);
tv.setText(text);
tv.setTextColor(Color.WHITE);
tv.setGravity(Gravity.CENTER);
GradientDrawable shape = new GradientDrawable();
shape.setColor(Color.parseColor("#FF6666"));
shape.setCornerRadius(0.9f);
shape.setStroke(1, Color.parseColor("#FF6666"));
shape.setAlpha(180);
mLayout.setBackground(shape);
int w=context.getResources().getDisplayMetrics().widthPixels / 2;
int h=context.getResources().getDisplayMetrics().widthPixels / 10;
mLayout.addView(tv, w, h);
result.mNextView = mLayout;
result.mDuration = duration;
return result;
}
public static final int LENGTH_SHORT = 2000;
public static final int LENGTH_LONG = 3500;
private final Handler mHandler = new Handler();
private int mDuration=LENGTH_SHORT;
private int mGravity = Gravity.CENTER;
private int mX, mY;
private float mHorizontalMargin;
private float mVerticalMargin;
private View mView;
private View mNextView;
private WindowManager mWM;
private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
public MyToast(Context context) {
init(context);
}
/**
* Set the view to show.
* @see #getView
*/
public void setView(View view) {
mNextView = view;
}
/**
* Return the view.
* @see #setView
*/
public View getView() {
return mNextView;
}
/**
* Set how long to show the view for.
* @see #LENGTH_SHORT
* @see #LENGTH_LONG
*/
public void setDuration(int duration) {
mDuration = duration;
}
/**
* Return the duration.
* @see #setDuration
*/
public int getDuration() {
return mDuration;
}
/**
* Set the margins of the view.
*
* @param horizontalMargin The horizontal margin, in percentage of the
* container width, between the container's edges and the
* notification
* @param verticalMargin The vertical margin, in percentage of the
* container height, between the container's edges and the
* notification
*/
public void setMargin(float horizontalMargin, float verticalMargin) {
mHorizontalMargin = horizontalMargin;
mVerticalMargin = verticalMargin;
}
/**
* Return the horizontal margin.
*/
public float getHorizontalMargin() {
return mHorizontalMargin;
}
/**
* Return the vertical margin.
*/
public float getVerticalMargin() {
return mVerticalMargin;
}
/**
* Set the location at which the notification should appear on the screen.
* @see android.view.Gravity
* @see #getGravity
*/
public void setGravity(int gravity, int xOffset, int yOffset) {
mGravity = gravity;
mX = xOffset;
mY = yOffset;
}
/**
* Get the location at which the notification should appear on the screen.
* @see android.view.Gravity
* @see #getGravity
*/
public int getGravity() {
return mGravity;
}
/**
* Return the X offset in pixels to apply to the gravity's location.
*/
public int getXOffset() {
return mX;
}
/**
* Return the Y offset in pixels to apply to the gravity's location.
*/
public int getYOffset() {
return mY;
}
/**
* schedule handleShow into the right thread
*/
public void show() {
mHandler.post(mShow);
if(mDuration>0)
{
mHandler.postDelayed(mHide, mDuration);
}
}
/**
* schedule handleHide into the right thread
*/
public void hide() {
mHandler.post(mHide);
}
private final Runnable mShow = new Runnable() {
public void run() {
handleShow();
}
};
private final Runnable mHide = new Runnable() {
public void run() {
handleHide();
}
};
private void init(Context context)
{
final WindowManager.LayoutParams params = mParams;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = android.R.style.Animation_Toast;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.setTitle("Toast");
mWM = (WindowManager) context.getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE);
}
private void handleShow() {
if (mView != mNextView) {
// remove the old view if necessary
handleHide();
mView = mNextView;
// mWM = WindowManagerImpl.getDefault();
final int gravity = mGravity;
mParams.gravity = gravity;
if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL)
{
mParams.horizontalWeight = 1.0f;
}
if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL)
{
mParams.verticalWeight = 1.0f;
}
mParams.x = mX;
mParams.y = mY;
mParams.verticalMargin = mVerticalMargin;
mParams.horizontalMargin = mHorizontalMargin;
if (mView.getParent() != null)
{
mWM.removeView(mView);
}
mWM.addView(mView, mParams);
}
}
private void handleHide()
{
if (mView != null)
{
if (mView.getParent() != null)
{
mWM.removeView(mView);
}
mView = null;
}
}
}