package com.partynetwork.iparty.app;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.List;
import java.util.UUID;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.webkit.CacheManager;
import com.baidu.frontia.FrontiaApplication;
import com.lidroid.xutils.BitmapUtils;
import com.partynetwork.dataprovider.DataProvider;
import com.partynetwork.dataprovider.util.MD5Util;
import com.partynetwork.dataprovider.util.StringUtil;
import com.partynetwork.iparty.app.api.ApiClient;
import com.partynetwork.iparty.app.bean.BLogin;
import com.partynetwork.iparty.app.bean.IpartyList;
import com.partynetwork.iparty.app.bean.NoticeList;
import com.partynetwork.iparty.app.bean.ShareList;
import com.partynetwork.iparty.app.common.CyptoUtils;
import com.partynetwork.iparty.app.util.ImageUtils;
import com.partynetwork.iparty.app.util.StringUtils;
import com.partynetwork.iparty.info.UserInfo;
/**
* 全局应用程序类:用于保存和调用全局应用配置及访问网络数据
*/
public class AppContext extends Application {
public static final int NETTYPE_WIFI = 0x01;
public static final int NETTYPE_CMWAP = 0x02;
public static final int NETTYPE_CMNET = 0x03;
public static final int PAGE_SIZE = 20;// 默认分页大小
private static final int CACHE_TIME = 60 * 60000;// 缓存失效时间
private boolean login = false; // 登录状态
private int loginUid = 0; // 登录用户的id
private Hashtable<String, Object> memCacheRegion = new Hashtable<String, Object>();
private String saveImagePath;// 保存图片路径
private String saveDbPath;// 保存数据库路径
private DataProvider mDataProvider;
private BitmapUtils bitmapUtils;
private static AppContext appContext;
public static AppContext getInstance() {
if (appContext == null) {
appContext = new AppContext();
return appContext;
}
return appContext;
}
@Override
public void onCreate() {
super.onCreate();
appContext = this;
// 注册App异常崩溃处理器
Thread.setDefaultUncaughtExceptionHandler(AppException
.getAppExceptionHandler());
FrontiaApplication.initFrontiaApplication(this);
init();
}
/**
* 初始化
*/
private void init() {
// 设置保存图片的路径
saveImagePath = getProperty(AppConfig.SAVE_IMAGE_PATH);
if (StringUtil.isEmpty(saveImagePath)) {
setProperty(AppConfig.SAVE_IMAGE_PATH,
AppConfig.DEFAULT_SAVE_IMAGE_PATH);
saveImagePath = AppConfig.DEFAULT_SAVE_IMAGE_PATH;
}
saveDbPath = getProperty(AppConfig.SAVE_DB_PATH);
if (StringUtil.isEmpty(saveDbPath)) {
setProperty(AppConfig.SAVE_DB_PATH, AppConfig.DEFAULT_SAVE_DB_PATH);
saveDbPath = AppConfig.DEFAULT_SAVE_DB_PATH;
}
initImageLoad();
}
private void initImageLoad() {
bitmapUtils = new BitmapUtils(this);
}
public String getSaveImagePath() {
return saveImagePath;
}
public void setSaveImagePath(String saveImagePath) {
this.saveImagePath = saveImagePath;
}
public String getSaveDbPath() {
return saveDbPath;
}
public void setSaveDbPath(String saveDbPath) {
this.saveDbPath = saveDbPath;
}
public DataProvider getmDataProvider() {
if (mDataProvider == null) {
mDataProvider = DataProvider.getInstance();
mDataProvider.DataProviderContext(this);
}
return mDataProvider;
}
public void setmDataProvider(DataProvider mDataProvider) {
this.mDataProvider = mDataProvider;
}
public BitmapUtils getBitmapUtils() {
if (bitmapUtils == null) {
bitmapUtils = new BitmapUtils(this);
}
return bitmapUtils;
}
/**
* 检测当前系统声音是否为正常模式
*
* @return
*/
public boolean isAudioNormal() {
AudioManager mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
return mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
}
/**
* 应用程序是否发出提示音
*
* @return
*/
public boolean isAppSound() {
return isAudioNormal() && isVoice();
}
/**
* 检测网络是否可用
*
* @return
*/
public boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnectedOrConnecting();
}
/**
* 获取当前网络类型
*
* @return 0:没有网络 1:WIFI网络 2:WAP网络 3:NET网络
*/
public int getNetworkType() {
int netType = 0;
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null) {
return netType;
}
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_MOBILE) {
String extraInfo = networkInfo.getExtraInfo();
if (!StringUtil.isEmpty(extraInfo)) {
if (extraInfo.toLowerCase().equals("cmnet")) {
netType = NETTYPE_CMNET;
} else {
netType = NETTYPE_CMWAP;
}
}
} else if (nType == ConnectivityManager.TYPE_WIFI) {
netType = NETTYPE_WIFI;
}
return netType;
}
/**
* 判断当前版本是否兼容目标版本的方法
*
* @param VersionCode
* @return
*/
public static boolean isMethodsCompat(int VersionCode) {
int currentVersion = android.os.Build.VERSION.SDK_INT;
return currentVersion >= VersionCode;
}
/**
* 获取App安装包信息
*
* @return
*/
public PackageInfo getPackageInfo() {
PackageInfo info = null;
try {
info = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
e.printStackTrace(System.err);
}
if (info == null)
info = new PackageInfo();
return info;
}
/**
* 获取App唯一标识
*
* @return
*/
public String getAppId() {
String uniqueID = getProperty(AppConfig.CONF_APP_UNIQUEID);
if (StringUtil.isEmpty(uniqueID)) {
uniqueID = UUID.randomUUID().toString();
setProperty(AppConfig.CONF_APP_UNIQUEID, uniqueID);
}
return uniqueID;
}
/**
* 是否是第一次登陆
*
* @return
*/
public boolean isFirstLogin() {
String first = getProperty("is_first");
if (!first.equals("false")) {
setProperty("is_first", "false");
return true;
}
return false;
}
/**
* 用户是否登录
*
* @return
*/
public boolean isLogin() {
if (getLoginUid() != 0) {
return true;
} else {
return false;
}
}
/**
* 获取登录用户id
*
* @return
*/
public int getLoginUid() {
String Uid = getProperty("user.uid");
if (Uid == null) {
return 0;
} else {
int id = StringUtils.toInt(Uid, 0);
this.loginUid = id;
return id;
}
}
/**
* 用户注销
*/
public void Logout() {
this.cleanLoginInfo();
this.login = false;
this.loginUid = 0;
setProperty("user.uid", "0");
}
/**
* 保存用户头像
*
* @param fileName
* @param bitmap
*/
public void saveUserFace(String fileName, Bitmap bitmap) {
try {
ImageUtils.saveImage(this, fileName, bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取用户头像
*
* @param key
* @return
* @throws AppException
*/
public Bitmap getUserFace(String key) throws AppException {
FileInputStream fis = null;
try {
fis = openFileInput(key);
return BitmapFactory.decodeStream(fis);
} catch (Exception e) {
throw AppException.run(e);
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
}
/**
* 保存登录信息
*
* @param username
* @param pwd
*/
public void saveLoginInfo(BLogin login) {
this.loginUid = login.getUid();
this.login = true;
setProperty("user.uid", String.valueOf(login.getUid()));
setProperty("user.name", login.getName());
setProperty("user.face", login.getFace());// 用户头像
setProperty("user.sex", String.valueOf(login.getSex()));
setProperty("user.state", login.getState());
setProperty("user.age", String.valueOf(login.getAge()));
setProperty("user.account", login.getAccount());
setProperty("user.pwd", CyptoUtils.encode("ipartyApp", login.getPwd()));
setProperty("user.location", login.getLocation());
setProperty("user.phone", login.getPhone());
setProperty("user.email", login.getEmail());
}
public void saveUserInfo(UserInfo userInfo) {
this.loginUid = userInfo.getUserId();
this.login = true;
setProperty("user.uid", String.valueOf(userInfo.getUserId()));
setProperty("user.name", userInfo.getUserName());
setProperty("user.face", userInfo.getUserHeadUrl());// 用户头像
setProperty("user.sex", String.valueOf(userInfo.getUserSex()));
setProperty("user.state", userInfo.getUserState());
setProperty("user.age", String.valueOf(userInfo.getUserAge()));
setProperty("user.location", userInfo.getUserCity());
setProperty("user.phone", userInfo.getUserPhone());
setProperty("user.email", userInfo.getUserEmail());
}
/**
* 获取登录信息
*
* @return
*/
public BLogin getLoginInfo() {
BLogin lu = new BLogin();
lu.setUid(StringUtils.toInt(getProperty("user.uid"), 0));
lu.setName(getProperty("user.name"));
lu.setFace(getProperty("user.face"));
lu.setAccount(getProperty("user.account"));
lu.setPwd(CyptoUtils.decode("ipartyApp", getProperty("user.pwd")));
lu.setLocation(getProperty("user.location"));
lu.setSex(StringUtils.toInt(getProperty("user.sex"), 0));
lu.setAge(StringUtils.toInt(getProperty("user.age"), 0));
lu.setState(getProperty("user.state"));
lu.setPhone(getProperty("user.phone"));
lu.setEmail(getProperty("user.email"));
return lu;
}
/**
* 清除登录信息
*/
public void cleanLoginInfo() {
removeProperty("user.uid", "user.name", "user.face", "user.account",
"user.pwd", "user.location", "user.sex", "user.age",
"user.state", "user.phone", "user.email");
}
/**
* 是否加载显示文章图片
*
* @return
*/
public boolean isLoadImage() {
String perf_loadimage = getProperty(AppConfig.CONF_LOAD_IMAGE);
// 默认是加载的
if (StringUtil.isEmpty(perf_loadimage))
return true;
else
return StringUtils.toBool(perf_loadimage);
}
/**
* 设置是否加载文章图片
*
* @param b
*/
public void setConfigLoadimage(boolean b) {
setProperty(AppConfig.CONF_LOAD_IMAGE, String.valueOf(b));
}
/**
* 是否发出提示音
*
* @return
*/
public boolean isVoice() {
String perf_voice = getProperty(AppConfig.CONF_VOICE);
// 默认是开启提示声音
if (StringUtil.isEmpty(perf_voice))
return true;
else
return StringUtils.toBool(perf_voice);
}
/**
* 设置是否发出提示音
*
* @param b
*/
public void setConfigVoice(boolean b) {
setProperty(AppConfig.CONF_VOICE, String.valueOf(b));
}
/**
* 设置启动检查更新
*
* @param b
*/
public void setConfigCheckUp(boolean b) {
setProperty(AppConfig.CONF_CHECKUP, String.valueOf(b));
}
/**
* 是否启动检查更新
*
* @return
*/
public boolean isCheckUp() {
String perf_checkup = getProperty(AppConfig.CONF_CHECKUP);
// 默认是开启
if (StringUtil.isEmpty(perf_checkup)) {
return true;
} else {
return StringUtils.toBool(perf_checkup);
}
}
/**
* 是否左右滑动
*
* @return
*/
public boolean isScroll() {
String perf_scroll = getProperty(AppConfig.CONF_SCROLL);
// 默认是关闭左右滑动
if (StringUtil.isEmpty(perf_scroll))
return false;
else
return StringUtils.toBool(perf_scroll);
}
/**
* 设置是否左右滑动
*
* @param b
*/
public void setConfigScroll(boolean b) {
setProperty(AppConfig.CONF_SCROLL, String.valueOf(b));
}
/**
* 是否Https登录
*
* @return
*/
public boolean isHttpsLogin() {
String perf_httpslogin = getProperty(AppConfig.CONF_HTTPS_LOGIN);
// 默认是http
if (StringUtil.isEmpty(perf_httpslogin))
return false;
else
return StringUtils.toBool(perf_httpslogin);
}
/**
* 设置是是否Https登录
*
* @param b
*/
public void setConfigHttpsLogin(boolean b) {
setProperty(AppConfig.CONF_HTTPS_LOGIN, String.valueOf(b));
}
/**
* 判断缓存是否存在
*
* @param cachefile
* @return
*/
private boolean isExistDataCache(String cachefile) {
boolean exist = false;
File data = getFileStreamPath(cachefile);
if (data.exists())
exist = true;
return exist;
}
/**
* 判断缓存是否失效
*
* @param cachefile
* @return
*/
public boolean isCacheDataFailure(String cachefile) {
boolean failure = false;
File data = getFileStreamPath(cachefile);
if (data.exists()
&& (System.currentTimeMillis() - data.lastModified()) > CACHE_TIME)
failure = true;
else if (!data.exists())
failure = true;
return failure;
}
/**
* 清除app缓存
*/
public void clearAppCache() {
// 清除webview缓存
File file = CacheManager.getCacheFileBaseDir();
if (file != null && file.exists() && file.isDirectory()) {
for (File item : file.listFiles()) {
item.delete();
}
file.delete();
}
deleteDatabase("webview.db");
deleteDatabase("webview.db-shm");
deleteDatabase("webview.db-wal");
deleteDatabase("webviewCache.db");
deleteDatabase("webviewCache.db-shm");
deleteDatabase("webviewCache.db-wal");
// 清除数据缓存
clearCacheFolder(getFilesDir(), System.currentTimeMillis());
clearCacheFolder(getCacheDir(), System.currentTimeMillis());
// 2.2版本才有将应用缓存转移到sd卡的功能
if (isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
clearCacheFolder(MethodsCompat.getExternalCacheDir(this),
System.currentTimeMillis());
}
}
/**
* 清除缓存目录
*
* @param dir
* 目录
* @param numDays
* 当前系统时间
* @return
*/
private int clearCacheFolder(File dir, long curTime) {
int deletedFiles = 0;
if (dir != null && dir.isDirectory()) {
try {
for (File child : dir.listFiles()) {
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, curTime);
}
if (child.lastModified() < curTime) {
if (child.delete()) {
deletedFiles++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return deletedFiles;
}
/**
* 将对象保存到内存缓存中
*
* @param key
* @param value
*/
public void setMemCache(String key, Object value) {
memCacheRegion.put(key, value);
}
/**
* 从内存缓存中获取对象
*
* @param key
* @return
*/
public Object getMemCache(String key) {
return memCacheRegion.get(key);
}
/**
* 保存磁盘缓存
*
* @param key
* @param value
* @throws IOException
*/
public void setDiskCache(String key, String value) throws IOException {
FileOutputStream fos = null;
try {
fos = openFileOutput("cache_" + key + ".data", Context.MODE_PRIVATE);
fos.write(value.getBytes());
fos.flush();
} finally {
try {
fos.close();
} catch (Exception e) {
}
}
}
/**
* 获取磁盘缓存数据
*
* @param key
* @return
* @throws IOException
*/
public String getDiskCache(String key) throws IOException {
FileInputStream fis = null;
try {
fis = openFileInput("cache_" + key + ".data");
byte[] datas = new byte[fis.available()];
fis.read(datas);
return new String(datas);
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
}
/**
* 保存对象
*
* @param ser
* @param file
* @throws IOException
*/
public boolean saveObject(Serializable ser, String file) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = openFileOutput(file, MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(ser);
oos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
oos.close();
} catch (Exception e) {
}
try {
fos.close();
} catch (Exception e) {
}
}
}
/**
* 读取对象
*
* @param file
* @return
* @throws IOException
*/
public Serializable readObject(String file) {
if (!isExistDataCache(file))
return null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = openFileInput(file);
ois = new ObjectInputStream(fis);
return (Serializable) ois.readObject();
} catch (FileNotFoundException e) {
} catch (Exception e) {
e.printStackTrace();
// 反序列化失败 - 删除缓存文件
if (e instanceof InvalidClassException) {
File data = getFileStreamPath(file);
data.delete();
}
} finally {
try {
ois.close();
} catch (Exception e) {
}
try {
fis.close();
} catch (Exception e) {
}
}
return null;
}
public void setProperty(String key, String value) {
AppConfig.getAppConfig(this).set(key, value);
}
public String getProperty(String key) {
return AppConfig.getAppConfig(this).get(key);
}
public void removeProperty(String... params) {
for (int i = 0; i < params.length; i++) {
setProperty(params[i], "");
}
}
/**
* 用户登录验证
*
* @param account
* @param pwd
* @return
* @throws AppException
*/
public BLogin loginVerify(String account, String pwd, int loginType)
throws AppException {
BLogin login = null;
login = ApiClient.login(this, account, pwd, loginType);
login.setAccount(account);
login.setPwd(MD5Util.md5(pwd));
return login;
}
/**
* 获取iparty列表数据
*
* @param type
* @param pageNum
* @param lastId
* @param pageSize
* @return
* @throws AppException
*/
public IpartyList getIpartyList(int type, int pageNum, int lastId,
int pageSize) throws AppException {
if (type > 2) {
type++;
}
return ApiClient.getIpartyList(this, type, pageNum, lastId, pageSize);
}
/**
* 获取i分享列表数据
*
* @param type
* @param pageNum
* @param lastId
* @param pageSize
* @return
* @throws AppException
*/
public ShareList getShareList(int type, int pageNum, int lastId,
int pageSize) throws AppException {
return ApiClient.getShareList(this, type, pageNum, lastId, pageSize);
}
/**
* 上传文件返回Url
*
* @param files
* @return
* @throws AppException
*/
public List<String> upFiles4Url(List<File> files) throws AppException {
return ApiClient.upFiles4Url(this, files);
}
/**
* 获取系统通知列表
*
* @return
* @throws AppException
*/
public NoticeList getNoticeList() throws AppException {
return ApiClient.getNoticeList(this);
}
/**
* 获取指定用户信息
*
* @param userId
* @return
* @throws AppException
*/
public UserInfo getUserInfo(int userId) throws AppException {
// TODO 自动生成的方法存根
return ApiClient.getUserInfo(this, userId);
}
/**
* 获取指定城市派对
*
* @param ipartyType
* @param cityNum
* @return
* @throws AppException
*/
public IpartyList getIpartyList4City(int ipartyType, String cityNum)
throws AppException {
return ApiClient.getIpartyList4City(this, ipartyType, cityNum);
}
/**
* 打招呼
*
* @param toUserId
* @param message
* @return
* @throws AppException
*/
public int setGreet(int toUserId, String message) throws AppException {
return ApiClient.setGreet(this, toUserId, message);
}
/**
* 设置账号信息
*
* @param idCard
* @param question
* @param answer
* @param password
* @return
* @throws AppException
*/
public int setAccountInfo(String idCard, String question, String answer,
String password) throws AppException {
return ApiClient.setAccountInfo(this, idCard, question, answer,
password);
}
/**
* 重设支付密码
*
* @param idCard
* @param question
* @param answer
* @return
* @throws AppException
*/
public int setPaymentPassword(String idCard, String question,
String answer, String password) throws AppException {
return ApiClient.setPaymentPassword(this, idCard, question, answer,
password);
}
/**
* 修改支付密码
*
* @param oldPsd
* @param newPsd
* @return
* @throws AppException
*/
public int resetPaymentPassword(String oldPsd, String newPsd)
throws AppException {
return ApiClient.resetPaymentPassword(this, oldPsd, newPsd);
}
/**
* 获取密码保护问题
*
* @return
* @throws AppException
*/
public String getPasswordProtection() throws AppException {
return ApiClient.getPasswordProtection(this);
}
/**
* 提现
*
* @param account
* @param money
* @param password
* @return
*/
public int checkout(String account, float money, String password)
throws AppException {
return ApiClient.checkout(this, account, money, password);
}
/**
* 认证
*
* @param authType
* @param authName
* @param authHead
* @return
* @throws AppException
*/
public int setAuth(int authType, String authName, String authHead)
throws AppException {
return ApiClient.setAuth(this, authType, authName, authHead);
}
/**
* 社交账号绑定
*
* @param uid
* @param token
* @param expiresTime
* @param type
* @return
* @throws AppException
*/
public int bind(String uid, String token, long expiresTime, int type)
throws AppException {
return ApiClient.bind(this, uid, token, expiresTime, type);
}
/**
* 快捷登陆
*
* @param account
* @param uid
* @param userName
* @param head
* @param token
* @param expiresTime
* @return
*/
public BLogin easyLogin(int loginType,String account, String uid, String userName,
String head, String token, long expiresTime) throws AppException {
return ApiClient.easyLogin(this, loginType,account, uid, userName, head, token,
expiresTime);
}
}