package com.yaoxin.newapp;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.List;


import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


public class Utils {


public static final String STRING_NO_POINT = "";
public static Context applicationContext;
public static final int LEVEL_INTERN = 0;
public static final int LEVEL_NORMAL = 1;
public static final int LEVEL_PHARMACIST = 6;
public static final int LEVEL_LICENSED_PHARMACIST = 7;


/**
* 检测是否有可用网络

* @param context
* @return 网络连接状态
*/
public static boolean isNetworkAvailable(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// 获取网络信息
NetworkInfo info = cm.getActiveNetworkInfo();
// 返回检测的网络状态
return (info != null && info.isConnected() && info.isAvailable());
} catch (Exception e) {
e.printStackTrace();
return false;
}
}


public static  boolean isWifiConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWiFiNetworkInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWiFiNetworkInfo != null) {
return mWiFiNetworkInfo.isAvailable();
}
}
return false;
}


public static  boolean isMobileConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mMobileNetworkInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mMobileNetworkInfo != null) {
return mMobileNetworkInfo.isAvailable();
}
}
return false;
}

   /*
    * 获取当前的网络状态 -1:没有网络  1:WIFI网络  2:wap网络  3:net网络 
    * 
    * */
public static int getConnectedType(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager
.getActiveNetworkInfo();
if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
return mNetworkInfo.getType();
}
}
return -1;
}


//获取缓存文件名
public static String getCacheFileName(String filename){
String cacheDir = applicationContext.getFilesDir().getAbsolutePath();
if (filename.startsWith("/")){
return cacheDir + filename;
} else{
return cacheDir + "/" + filename;
}
}


//将String内容保存到文件中
//返回值: true - 成功    false - 失败
public static Boolean saveContentToFile(String content, String filename){
try{
File f = new File(filename);
if (!f.exists()){
f.getParentFile().mkdirs();
f.createNewFile();
}
FileOutputStream ofile = new FileOutputStream(f);
ofile.write(content.getBytes());
ofile.close();
return true;
} catch (Exception e){
return false;
}
}


//将String内容保存到缓存文件中,自动为filename文件名添加缓存路径
//返回值: true - 成功    false - 失败
public static Boolean saveStringToCacheFile(String content, String filename){
return saveContentToFile(content, getCacheFileName(filename));
}

//读取文件内容
public static String getContentFromFile(String filename){
 String res = "";   
 try{   
        FileInputStream fin = new FileInputStream(filename);   
        int length = fin.available();   
        byte [] buffer = new byte[length];   
        fin.read(buffer);       
        res = EncodingUtils.getString(buffer, "UTF-8");   
        fin.close();       
    }   
    catch(Exception e){   
        e.printStackTrace();   
    }   
    return res;  
}


//读取缓存文件内容,自动为文件名添加缓存路径
public static String getContentFromCacheFile(String filename){
return getContentFromFile(getCacheFileName(filename));
}

//将JSON保存到缓存文件中
//JSONObject、JSONArray自动识别
//自动为文件名添加缓存路径
//返回值: true - 成功    false - 失败
public static Boolean savejSONToCacheFile(Object JSON, String filename){
String content;
try{
JSONObject obj = (JSONObject)JSON;
content = obj.toString();
} catch(Exception e){
try{
JSONArray arr = (JSONArray)JSON;
content = arr.toString();
} catch(Exception e1){
return false;
}
}
return saveContentToFile(content, getCacheFileName(filename));
}

//从指定文件中获取JSONObject
public static JSONObject getJSONObjectFromFile(String filename){
try {
return new JSONObject(getContentFromFile(filename));
} catch (Exception e) {
return null;
}
}

//从指定缓存文件中获取JSONObject
//自动添加缓存路径
public static JSONObject getJSONObjectFromCacheFile(String filename){
return getJSONObjectFromFile(getCacheFileName(filename));
}


//从指定文件中获取JSONArray
public static JSONArray getJSONArrayFromFile(String filename){
try {
return new JSONArray(getContentFromFile(filename));
} catch (Exception e) {
return null;
}
}

//从指定缓存文件中获取JSONArray
//自动添加缓存路径
public static JSONArray getJSONArrayFromCacheFile(String filename){
return getJSONArrayFromFile(getCacheFileName(filename));
}


//直接获取用户id(手机号)
public static String getUserId(){
try{
SharedPreferences userinfo = applicationContext.getSharedPreferences(
LoginActivity.PREFS_PRIVATE, Context.MODE_PRIVATE);
return  userinfo.getString("userid", "");
} catch (Exception e){
return "";
}
}

private static String getUserProfileName(){
// String cacheDir = getFilesDir().getAbsolutePath();
String userId = getUserId();
// return cacheDir + "/" + userId + ".json";
return getCacheFileName(userId + ".json");
}

//直接获取用户等级
public static String getUserLevel(){
try{
JSONObject json = getJSONObjectFromFile(getUserProfileName());
return json.getString("member_level");
} catch (Exception e){
return "0";
}
}

//本地保存用户等级
public static void saveUserLevel(String level){
try{
JSONObject json = getJSONObjectFromFile(getUserProfileName());
json.put("member_level", level);
saveContentToFile(json.toString(), getUserProfileName());
} catch (Exception e){
//do nothing
}
}

//将学分View中的学分减掉deltaPoints的学分显示
//自动判定,当新学分小于等于0时不显示
public static void changePointTextviewByDeltaPoint(TextView pointTextView, 
  int deltaPoints){
int point = getPointFromPointText(pointTextView.getText().toString()) - deltaPoints;
String newPoint = getFinalPointString(point);
pointTextView.setText(newPoint);
if (newPoint.equals(STRING_NO_POINT)){
pointTextView.setVisibility(View.GONE);
} else{
pointTextView.setVisibility(View.VISIBLE);
}
}

//自动为学分字符串前添加“+”
//无论学分字符串之前是否有“+”
//如果学分小于等于0,则返回Utils.STRING_NO_POINTS
public static String getFinalPointString(String pointString){
int point = getPointFromPointText(pointString);
return getFinalPointString(point);
}


//将学分数值转换为带“+”的学分字符串
//如果学分小于等于0,则返回Utils.STRING_NO_POINTS
public static String getFinalPointString(int point){
if (point > 0){
return "+" + point;
} else{
return STRING_NO_POINT;
}
}


//将学分字符串转换为数值
public static int getPointFromPointText(String pointText){
try {
if (pointText.startsWith("+")){
pointText = pointText.substring(1);
}
return Integer.valueOf(pointText).intValue();
} catch (Exception e) {
return 0;
}
}

//根据文章等级与店员等级判定返回指定文章JSON中的目标url
public static String getFinalUrl(JSONObject articleJSON){
String url = "";
try {
if (articleJSON.has("url")){
url = articleJSON.getString("url");
}
int articleLevel = LEVEL_INTERN;
if (articleJSON.has("content_level")){
String contentLevel = articleJSON.getString("content_level");
articleLevel = Integer.valueOf(contentLevel).intValue();
}
int userLevel = Integer.valueOf(getUserLevel()).intValue();
if (articleLevel >= LEVEL_LICENSED_PHARMACIST && userLevel < LEVEL_LICENSED_PHARMACIST){
return "yaoxin://lpharmacist/confirm";
} else if (articleLevel >= LEVEL_PHARMACIST && userLevel < LEVEL_PHARMACIST){
return "yaoxin://pharmacist/confirm";
} else if (articleLevel >= LEVEL_NORMAL && userLevel < LEVEL_NORMAL){
return "yaoxin://userlevel";
} else{
return url;
}
} catch (Exception e) {
return url;
}
}


//判定字符串是否是JSONObject或JSONArray
public static boolean isJSON(String content) {
try {
new JSONObject(content);
} catch (JSONException e) {
try {
new JSONArray(content);
} catch (JSONException c) {
return false;
}
}
return true;
}


//从JSONArray中移除指定序号的item
public static void removeJSONArrayItem(int index, JSONArray json) throws Exception{  
   if(index < 0)  
       return;  
   Field valuesField=JSONArray.class.getDeclaredField("values");  
   valuesField.setAccessible(true);  
   List values=(List)valuesField.get(json);  
   if(index >= values.size())  
       return;  
   values.remove(index);  
}

//简便的显示Toast方法
public static void showToast(String msg){
Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show();
}

//是否显示了首次登录蒙层指引
public static Boolean hasUserInstruction3Shown(){
SharedPreferences userInfo = applicationContext.getSharedPreferences(MainActivityPager.RED_PRIVATE,
Context.MODE_PRIVATE);
return userInfo.getBoolean("guidesp3", false);
}

//记录首次登录蒙层指引显示完成
public static void setUsesrInstruction3Shown(){
SharedPreferences userInfo = applicationContext.getSharedPreferences(MainActivityPager.RED_PRIVATE,
Context.MODE_PRIVATE);
Editor prefsPrivateEditor = userInfo.edit();
prefsPrivateEditor.putBoolean("guidesp3", true);
prefsPrivateEditor.commit();
}


//设置文章列表JSONObject中的某一项学分为新值
public static void updatePointOfArticleInJSON(int newPoint,
 JSONObject articleJSON,
 int index) {
try {
JSONArray list = articleJSON.getJSONArray("detail");
list.getJSONObject(index).put("point", Integer.toString(newPoint));
articleJSON.put("detail", list);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


//将文章列表缓存文件中的某一项学分设置为新值
//自动添加缓存路径
public static void updatePointOfArticleInCachedFile(int newPoint,
   String filename, 
   int index){
JSONObject json = getJSONObjectFromCacheFile(filename);
updatePointOfArticleInJSON(newPoint, json, index);
savejSONToCacheFile(json, filename);
}
}

更多相关文章

  1. NPM 和webpack 的基础使用
  2. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  3. android中使用ant更改包名
  4. 修改Android的开关机铃声、Android开关机画面与动画(附代码流程)
  5. [转帖] android平台刷机包的制作研究 1~2
  6. Android(安卓)缓存的工具类
  7. Android编译系统一
  8. android 保存和读取文件
  9. Android(安卓)解压zip文件

随机推荐

  1. MySQL查询缓存的小知识
  2. Mysql技术内幕之InnoDB锁的深入讲解
  3. MySQL 主从同步,事务回滚的实现原理
  4. MySQL 有关MHA搭建与切换的几个错误log汇
  5. MySQL数据归档小工具mysql_archiver详解
  6. 详解MySQL 数据分组
  7. 详解mysql 组合查询
  8. Mysql优化神器(推荐)
  9. 修改MySQL数据库引擎为InnoDB的操作
  10. MySQL按小时查询数据,没有的补0