Android项目开发前准备工作(二)

时间:2022-10-08 19:02:17

     让Android融入我的生活!

     上一篇介绍了部分开发前的准备工作,因为考虑到篇幅太长,大家看着也费劲,所以以后我的所有博客都不会太长,如果太长的话,我会分为几期进行介绍,好了,不费话了,继续上一篇!

     1:所有网络请求要全部由一个方法执行,用回调接口实现返回的数据处理,请求前对网络状态进行判断,若无网络,则直接返回,这样可以

大大减少应用的耗电量,顺便说一句,应用当中的耗电最多的是连网、GPS、各种传感器,大家在空暇之余可以对这几点进行检查,来提高我们

APP的性能!

	/**
* 网络状态
*
* @param context
* @return
*/
public static boolean IsNetwork(Context context) {
boolean flag = true;
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) {
flag = true;
} else {
flag = false;
}
return flag;
}

/**
* 获取机器ip地址
*
* @return
*/
public static String getLocalIpAddress(Context context) {
String ip = null;
if (isWifiEnabled(context)) {
ip = getWifiIpAddress(context);
Log.d(Constants.TAG, "===获取wifi网络ip===" + ip);
} else {
ip = get3GIp();
Log.e(Constants.TAG, "===获取3g网络ip===" + ip);
}
return ip;
}

     2:一些特别重要的全局变量要保存在自己的Application中,当应用出现闪退时,Constants常量类的属性将可能会被回收,如果继续访问的话
,取到的值可能为空,而Application中即使出现闪退,变量也不会被回收!

package com.uhuibao.hupeng;

/**
* @ClassName: BaseApplication
* @Description: TODO 全局配置文件
* @author huangmz&AricMiao
* @date 2014-12-16 上午9:31:41
*/
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import com.baidu.frontia.FrontiaApplication;
import com.baidu.mapapi.SDKInitializer;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.uhuibao.hupeng.answer.AnswerDraftBean;
import com.uhuibao.hupeng.ask.AskDraftBean;
import com.uhuibao.hupeng.config.ConfigUrls;
import com.uhuibao.hupeng.config.Constants;
import com.uhuibao.hupeng.me.UserInfoBean;
import com.uhuibao.hupeng.utils.ParseJsonUtils;
import com.uhuibao.hupeng.utils.SharedPreUtils;
import com.uhuibao.hupeng.utils.StorageUtils;

@SuppressLint("UseSparseArrays")
public class BaseApplication extends FrontiaApplication {
/** 日志输出标签 */
@SuppressWarnings("unused")
private static final String TAG = BaseApplication.class.getName();
/** 调试模式开关 */
public static final boolean DEBUG = true;
private static BaseApplication mInstance = null;
/** XUtils框架里的数据库操作模块 */
public DbUtils dbUtils;
/** XUtils框架里的Http请求模块 */
public HttpUtils httpUtils;
// public UserBean user;
public UserInfoBean mUser;
/**提问草稿箱*/
public Map askDrafts = new HashMap ();
/**回答草稿箱*/
public Map answerDrafts = new HashMap ();

public int interfaceType = -1;
private Map mapInfos = new HashMap ();

@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mInstance = this;
// 在使用百度 SDK 各组件之前初始化 context信息,传入 ApplicationContext
SDKInitializer.initialize(this);
// 生产全局数据库操作类
dbUtils = DbUtils.create(this);
// 生产全局网络操作类
httpUtils = new HttpUtils();
httpUtils.configSoTimeout(60 * 1000);
httpUtils.configTimeout(5 * 1000);
// 生产全局图片操作类
initImageLoader(this);

if (SharedPreUtils.getInstance().getInt(Constants.xmlUserId, 0) == 0) {// 未登录状态
mUser = new UserInfoBean();
} else {// 登录状态
try {
mUser = dbUtils.findById(UserInfoBean.class, SharedPreUtils.getInstance().getInt(Constants.xmlUserId, 0));
} catch (DbException e) {
mUser = new UserInfoBean();
}
}
}

/** 获取BaseApplication全局配置文件的单例 */
public static BaseApplication getApp() {
return mInstance;
}

/**获取服务器地址列表,但值为空时再次获取网络地址,避免在程序异常的时候将全局变量回收拿不到网络地址的情况*/
public Map getMapInfos(){
if(mapInfos == null || mapInfos.isEmpty()){
if(!ParseJsonUtils.parseJsonInterface(getCacheServerInfo())){ //本操作先去缓存
findServerInfo(); //再去网络地址
}
}
return mapInfos;
}

public void putMapInfo(String type, String url){
mapInfos.put(type, url);
}

/**
* 在缓存将接口信息读出
*
* @return json
*/
private String getCacheServerInfo() {
SharedPreferences shared = getSharedPreferences("interface",
Context.MODE_PRIVATE);
String json = shared.getString("json", "");
return json;
}

/***
* 图片加载universal image loader框架配置
*
* @param context
* 内容上下文
*/
public static void initImageLoader(Context context) {
// This configuration tuning is custom. You can tune every option, you
// may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
File cache = StorageUtils.getImageDir();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).threadPoolSize(5)// 设置线程池大小,默认5个
.threadPriority(Thread.NORM_PRIORITY - 2) // 设置正在运行任务的所有线程在系统中的优先级
.diskCache(new UnlimitedDiscCache(cache)) // 设置本地图片缓存文件夹
.denyCacheImageMultipleSizesInMemory() // 强制UIL在内存中不能存储内容相同但大小不同的图像。
.diskCacheFileNameGenerator(new Md5FileNameGenerator()) // 使用md5算法为本地图片文件名
.diskCacheSize(100 * 1024 * 1024) // 设置本地图片缓存文件夹大小为100
// Mb,超出组件自动删除
.tasksProcessingOrder(QueueProcessingType.LIFO)
// .writeDebugLogs() // 调试模式,正式版需去除Remove for release app
.build(); // 配置保存
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}

//读取接口地址
private void findServerInfo() {
RequestParams params = new RequestParams();// 声明封装请求参数类
params.addBodyParameter(ConfigUrls.COMMON_RARAM, ConfigUrls.getServerInfo(mInstance));// 获取请求参数JSON
/** 发送网络请求 */
BaseApplication.getApp().httpUtils.send(HttpRequest.HttpMethod.POST,ConfigUrls.SERVER_URL, params,
new RequestCallBack () {
@Override
public void onFailure(HttpException arg0, String arg1) {
if (BaseApplication.DEBUG)
Log.e(TAG, "findServerInfo onFailure=" + arg1);
}
@Override
public void onSuccess(ResponseInfo arg0) {
// TODO Auto-generated method stub
if (BaseApplication.DEBUG)
Log.e(TAG, "findServerInfo:onSuccess="+ arg0.result);
try {
JSONObject jsonObject = new JSONObject(arg0.result);
String reqCode = jsonObject.getString(ConfigUrls.RESP_CODE);
if (reqCode.equals(ConfigUrls.CODE_OK)) {
// 解析Json
JSONArray dataArray = jsonObject.getJSONArray(ConfigUrls.RESP_DATA);
if (dataArray != null && dataArray.length() > 0) {
String json = dataArray.getString(0);
if (ParseJsonUtils.parseJsonInterface(json)) {
setCacheServerInfo(json);
}
}
}
} catch (Exception e) {
if (BaseApplication.DEBUG)
Log.e(TAG, "findServerInfo Exception=", e);
}
}
});
}

/**
* 将接口信息保存在缓存
*
* @param json
*/
private void setCacheServerInfo(String json) {
SharedPreferences shared = getSharedPreferences("interface",
Context.MODE_PRIVATE);
Editor editor = shared.edit();
editor.putString("json", json);
editor.commit();
}

}
,>
,>
,>
,>
,>
,>
,>