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

本文分享了两个提升Android应用性能的方法:一是通过统一网络请求管理及智能判断网络状态减少耗电量;二是合理存放重要全局变量于Application中以防止闪退导致的数据丢失。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     让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();
	}
	
}

package com.bdvcd.app.utils; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; /** * 文件名:SharedPrefsUtil.java App存储数据工具类 * 版本信息:V1.0 * 日期:2013-03-11 * Copyright BDVCD Corporation 2013 * 版权所有 http://www.bdvcd.com */ public class SharedPrefsUtil { /** 数据存储的XML名称 **/ public final static String SETTING = "bdvcd"; /** * 存储数据(Long) * * @param context * @param key * @param value */ public static void putLongValue(Context context, String key, long value) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.putLong(key, value); sp.commit(); } /** * 存储数据(Int) * * @param context * @param key * @param value */ public static void putIntValue(Context context, String key, int value) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.putInt(key, value); sp.commit(); } /** * 存储数据(String) * * @param context * @param key * @param value */ public static void putStringValue(Context context, String key, String value) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.putString(key, value); sp.commit(); } /** * 存储数据(boolean) * * @param context * @param key * @param value */ public static void putBooleanValue(Context context, String key, boolean value) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.putBoolean(key, value); sp.commit(); } /** * 取出数据(Long) * * @param context * @param key * @param defValue * @return */ public static long getLongValue(Context context, String key, long defValue) { SharedPreferences sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE); long value = sp.getLong(key, defValue); return value; } /** * 取出数据(int) * * @param context * @param key * @param defValue * @return */ public static int getIntValue(Context context, String key, int defValue) { SharedPreferences sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE); int value = sp.getInt(key, defValue); return value; } /** * 取出数据(boolean) * * @param context * @param key * @param defValue * @return */ public static boolean getBooleanValue(Context context, String key, boolean defValue) { SharedPreferences sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE); boolean value = sp.getBoolean(key, defValue); return value; } /** * 取出数据(String) * * @param context * @param key * @param defValue * @return */ public static String getStringValue(Context context, String key, String defValue) { SharedPreferences sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE); String value = sp.getString(key, defValue); return value; } /** * 清空所有数据 * * @param context * @param key * @param defValue * @return */ public static void clear(Context context) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.clear(); sp.commit(); } /** * 清空所有数据 * * @param context * @param key * @param defValue * @return */ public static void remove(Context context, String key) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.remove(key); sp.commit(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

红-旺永福

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值