整理部分工具类

先Activity的抽象类 BaseActivity

[java]view plaincopy

/**

* Activity 基類

* @author KrisLight

*

*/

publicabstractclassBaseActivityextendsActivity {

privatestaticfinalString TAG = BaseActivity.class.getSimpleName();

/**

* 消息類型默認Default

*/

publicstaticintMSGTYPE_DEFAULT =0;

/**

* 消息類型為Info

*/

publicstaticintMSGTYPE_INFO =1;

/**

* 消息類型為Warning

*/

publicstaticintMSGTYPE_WARNING =2;

/**

* 消息類型為Error

*/

publicstaticintMSGTYPE_ERROR =3;

@Override

protectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

}

/**初始化**/

protectedabstractvoidinit();

/** 初始化監聽器**/

protectedabstractvoidinitListener();

/**  得到字符串資源 **/

publicString getResStr(intid)

{

returnthis.getResources().getString(id);

}

/** 短暂显示Toast提示(来自res) **/

protectedvoidshowShortToast(intresId) {

Toast.makeText(this, getString(resId), Toast.LENGTH_SHORT).show();

}

/** 短暂显示Toast提示(来自String) **/

protectedvoidshowShortToast(String text) {

Toast.makeText(this, text, Toast.LENGTH_SHORT).show();

}

/** 长时间显示Toast提示(来自res) **/

protectedvoidshowLongToast(intresId) {

Toast.makeText(this, getString(resId), Toast.LENGTH_LONG).show();

}

/** 长时间显示Toast提示(来自String) **/

protectedvoidshowLongToast(String text) {

Toast.makeText(this, text, Toast.LENGTH_LONG).show();

}

/** Debug输出Log日志 **/

protectedvoidshowLogDebug(String tag, String msg) {

Log.d(tag, msg);

}

/** Error输出Log日志 **/

protectedvoidshowLogError(String tag, String msg) {

Log.e(tag, msg);

}

/** 通过Class跳转界面 **/

protectedvoidstartActivity(Class cls) {

startActivity(cls,null);

}

/** 含有Bundle通过Class跳转界面 **/

protectedvoidstartActivity(Class cls, Bundle bundle) {

Intent intent =newIntent();

intent.setClass(this, cls);

if(bundle !=null) {

intent.putExtras(bundle);

}

if(intent.resolveActivity(getPackageManager()) !=null){

startActivity(intent);

}else{

showLogError(TAG,"there is no activity can handle this intent: "+intent.getAction().toString());

}

overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

}

/** 通过Action跳转界面 **/

protectedvoidstartActivity(String action) {

Intent intent =newIntent();

intent.setAction(action);

if(intent.resolveActivity(getPackageManager()) !=null){

startActivity(intent);

}else{

showLogError(TAG,"there is no activity can handle this intent: "+intent.getAction().toString());

}

}

/**含有Date通过Action跳转界面**/

protectedvoidstartActivity(String action,Uri data) {

Intent intent =newIntent();

intent.setAction(action);

intent.setData(data);

if(intent.resolveActivity(getPackageManager()) !=null){

startActivity(intent);

}else{

showLogError(TAG,"there is no activity can handle this intent: "+intent.getAction().toString());

}

}

/** 含有Bundle通过Action跳转界面 **/

protectedvoidstartActivity(String action, Bundle bundle) {

Intent intent =newIntent();

intent.setAction(action);

if(bundle !=null) {

intent.putExtras(bundle);

}

if(intent.resolveActivity(getPackageManager()) !=null){

startActivity(intent);

}else{

showLogError(TAG,"there is no activity can handle this intent: "+intent.getAction().toString());

}

overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

}

/** 含有标题、内容、两个按钮的对话框 **/

protectedvoidshowAlertDialog(String title, String message,

String positiveText,

DialogInterface.OnClickListener onPositiveClickListener,

String negativeText,

DialogInterface.OnClickListener onNegativeClickListener) {

AlertDialog alertDialog =newAlertDialog.Builder(this).setTitle(title)

.setMessage(message)

.setPositiveButton(positiveText, onPositiveClickListener)

.setNegativeButton(negativeText, onNegativeClickListener).create();

alertDialog.show();

}

/** 含有标题、内容、图标、两个按钮的对话框 **/

protectedvoidshowAlertDialog(String title, String message,

inticon, String positiveText,

DialogInterface.OnClickListener onPositiveClickListener,

String negativeText,

DialogInterface.OnClickListener onNegativeClickListener) {

AlertDialog alertDialog =newAlertDialog.Builder(this).setTitle(title)

.setMessage(message).setIcon(icon)

.setPositiveButton(positiveText, onPositiveClickListener)

.setNegativeButton(negativeText, onNegativeClickListener).create();

alertDialog.show();

}

/**

*

* @Function: com.light.mycal.base.BaseActivity

* @Description:根據不同的信息類型彈出不同等級的對話框

*

* @param i  資源id

* @param iMsgType 信息類型

*

* @version:v1.0

* @author:KrisLight

* @date:2013/9/4 下午4:56:39

*

* Modification History:

* Date         Author      Version     Description

* -----------------------------------------------------------------

* 2013/9/4    KrisLight      v1.0.0         create

*/

publicvoidShowMsgResStr(inti,intiMsgType)

{

String sTitle = getResStr(R.string.app_name);

inticonId =0;

if(iMsgType == MSGTYPE_INFO)

{

sTitle = getResStr(R.string.msgTypeInfo);

iconId = R.drawable.msgicon_info;

}

if(iMsgType == MSGTYPE_WARNING)

{

sTitle = getResStr(R.string.msgTypeWarning);

iconId = R.drawable.msgicon_warning;

}

if(iMsgType == MSGTYPE_ERROR)

{

sTitle = getResStr(R.string.msgTypeError);

iconId = R.drawable.msgicon_error;

}

AlertDialog.Builder dlg =newAlertDialog.Builder(this);

dlg.setMessage(getResStr(i));

dlg.setPositiveButton(getResStr(R.string.msgBoxButtonOk),null);

dlg.setTitle(sTitle);

dlg.setIcon(iconId);

dlg.create();

dlg.show();

}

/** 带有右进右出动画的退出 **/

publicvoidfinish() {

super.finish();

overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);

}

/** 默认退出 **/

protectedvoiddefaultFinish() {

super.finish();

}

}

配置文件工具Prefs

[java]view plaincopy

publicclassPrefs {

/** Friend+'s Preference file name */

publicstaticfinalString PREF_FILE ="friends_plus_pref";

/** Preference key[authToken] */

publicstaticfinalString KEY_AUTH_TOKEN ="auth_token";

/** Preference key[clientId] */

publicstaticfinalString KEY_CLIENT_ID ="client_id";

/** Preference key[login_email] */

publicstaticfinalString KEY_LOGIN_EMAIL ="login_email";

/** Preference key[login_IMId] */

publicstaticfinalString KEY_LOGIN_IMID ="login_imid";

/** Preference key[login_name] */

publicstaticfinalString KEY_LOGIN_NAME ="login_name";

/** Preference key[last_update_contact_list] */

publicstaticfinalString KEY_LAST_UPDATE_CONTACT_LIST ="last_update_contact_list";

publicstaticfinalString KEY_REGISTRATION_STEP ="registration_step";

publicstaticfinalString REGISTRATION_STEP_AUTHENTICATE ="authenticate";

publicstaticfinalString KEY_REGISTRATION_AUTHEN_CODE ="authen_code";

/**

* get the app's preference data

*

* @param context

* @param prefKey preference key

* @return

*/

publicstaticString getPreference(Context context, String prefKey) {

returngetPreference(context, prefKey,"");

}

/**

* get the app's preference data

*

* @param context

* @param prefKey preference key

* @param defVal default value

* @return

*/

publicstaticString getPreference(Context context, String prefKey, String defVal) {

if(TextUtils.isEmpty(prefKey))

returnnull;

SharedPreferences prefs =

context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);

returnprefs.getString(prefKey, defVal);

}

/**

* write data to app's preference

*

* @param context

* @param prefKey

* @param prefValue

*/

publicstaticvoidsavePreference(Context context, String prefKey, String prefValue) {

if(TextUtils.isEmpty(prefKey))

return;

SharedPreferences.Editor editor =

context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit();

editor.putString(prefKey, prefValue).commit();

}

/**

* remove preference value from app's preference file

* @param context

* @param prefKey

*/

publicstaticvoidremovePreference(Context context, String prefKey){

if(TextUtils.isEmpty(prefKey))

return;

SharedPreferences.Editor editor =

context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit();

editor.remove(prefKey).commit();

}

}

DBHelper类

[java]view plaincopy

/**

* DB工具類

* @author KrisLight

*

*/

publicclassDatabaseOpenHelperextendsSQLiteOpenHelper

{

privatestaticfinalString TAG = DatabaseOpenHelper.class.getSimpleName();

/** 數據庫操作結果 **/

publicenumResult

{

/** 成功 **/

Success,

/**未知錯誤**/

errUnknown,

/**無法插入新數據**/

errCantInsertNewData,

/**無法更新數據**/

errCantUpdateData,

/**無法創建Table**/

errCantCreateTable,

/**無法訪問數據庫**/

errNoDbAccess,

/**無法從表中獲取數據**/

errCantGetDataFromTable,

/**無法查到數據**/

errCantFindData,

/**無法得到數據**/

errCantGetData,

/**無法刪除數據**/

errCantDeleteData,

/**表不存在**/

errTableNotExists,

/**不能為該字段指定值**/

errCantSetValuesForDataRow,

/**不能從該字段得到值**/

errCantGetValuesFromDataRow,

};

/** 表名 **/

publicstaticfinalString TABLE_NAME ="appointments";

/** 臨時表名 **/

publicstaticfinalString TEMP_TABLE_NAME ="tempDb";

/** 數據庫名 **/

privatestaticfinalString DB_NAME ="MyCal.db";

privateSQLiteDatabase db =null;

/** 版本号 **/

privatestaticfinalintDB_VERSION =1;

/**創建Table的結果**/

privateResult resultDbTablesCreated = Result.errUnknown;

publicDatabaseOpenHelper(Context context, String name, CursorFactory factory,

intversion) {

super(context, DB_NAME, factory, DB_VERSION);

}

@Override

publicvoidonCreate(SQLiteDatabase sqLiteDatabase) {

DataRow nDataRow =newNoteDataRow();

String create_sql = getSqlTableDefinition(nDataRow.GetTableName(), nDataRow.GetTableDef());

Log.d(TAG,"create_sql: ---------------------"+create_sql+"------------");

try{

sqLiteDatabase.execSQL(create_sql);

resultDbTablesCreated = DatabaseOpenHelper.Result.Success;

}catch(Exception e) {

resultDbTablesCreated = DatabaseOpenHelper.Result.errCantCreateTable;

}

}

/**

* 得到創建表的SQL語句

* @param sTableName 表名

* @param vecTableDef 表的字段數組

* @return

*/

publicString getSqlTableDefinition(String sTableName, DataField[] vecTableDef)

{

String def ="CREATE TABLE "+ sTableName +" (";

for(inti =0; i < vecTableDef.length; i++)

{

def += vecTableDef[i].GetColumnDefinition();

if(i < (vecTableDef.length -1))

//中間逗號分隔

def +=", ";

}

def +=")";

returndef;

}

/* (non-Javadoc)

* @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)

*/

@Override

publicvoidonUpgrade(SQLiteDatabase db,intoldVersion,intnewVersion) {

switch(newVersion) {

case2:

/** only add column on old table**/

//          String add_column_sql = getSqlTableAddColumn(TABLE_NAME,newColumn);

//          Log.d(TAG, "add_column_sql:--------------"+add_column_sql+"----------");

//          db.execSQL(add_column_sql);

//          break;

case3:

//原來的字段集合

List columns = getColumns(db, TABLE_NAME);

String rename_sql = getSqlTableRename(TABLE_NAME);

Log.d(TAG,"rename_sql:--------------"+rename_sql+"----------");

//重命名

db.execSQL(rename_sql);

//創建新表

onCreate(db);

//舊字段和新的字段求交集

columns.retainAll(getColumns(db, TABLE_NAME));

String cols = Utils.join(columns,",");

//將舊的數據插入到新表

db.execSQL(String.format("INSERT INTO %s (%s) SELECT %s from temp_%s", TABLE_NAME, cols, cols, TABLE_NAME));

String drop_sql = getSqlTableDrop(TEMP_TABLE_NAME);

Log.d(TAG,"drop_sql:--------------"+drop_sql+"----------");

db.execSQL(drop_sql);

break;

default:

String ds = getSqlTableDrop(TABLE_NAME);

Log.d(TAG,"drop_sql:--------------"+ds+"----------");

break;

}

}

/**

*  得到重命名SQL

*/

privateString getSqlTableRename(String tableName){

StringBuffer sb =newStringBuffer();

sb.append("ALTER TABLE ");

sb.append(tableName);

sb.append(" RENAME TO temp_");

sb.append(tableName);

returnsb.toString();

}

/**

*  得到刪除表SQL

*/

privateString getSqlTableDrop(String tableName){

StringBuffer sb =newStringBuffer();

sb.append("DROP TABLE IF EXISTS ");

sb.append(tableName);

returnsb.toString();

}

/**

*  得到新增字段的表SQL

*/

privateString getSqlTableAddColumn(String tableName,String columnName){

StringBuffer sb =newStringBuffer();

sb.append("ALTER TABLE ");

sb.append(tableName);

sb.append(" ADD COLUMN ");

sb.append(columnName);

returnsb.toString();

}

/**

*  得到這個Table中的所有字段組成的List集合

*/

publicstaticList getColumns(SQLiteDatabase db, String tableName) {

List ar =null;

Cursor c =null;

try{

//查一條數據得到所有字段

c = db.rawQuery("select * from "+ tableName +" limit 1",null);

if(c !=null) {

ar =newArrayList(Arrays.asList(c.getColumnNames()));

}

}catch(Exception e) {

e.printStackTrace();

}finally{

if(c !=null)

c.close();

}

returnar;

}

/**

*  得到數據庫的名字

*

*/

publicfinalString getName()

{

returnDB_NAME;

}

/** 得到錯誤信息描述 **/

publicstaticintgetErrDesc(Result result)

{

intmsgId = R.string.errUnknown;

if(result == Result.errCantInsertNewData)

msgId = R.string.errCantInsertNewData;

if(result == Result.errCantUpdateData)

msgId = R.string.errCantUpdateData;

if(result == Result.errCantCreateTable)

msgId = R.string.errCantCreateTable;

if(result == Result.errNoDbAccess)

msgId = R.string.errNoDbAccess;

if(result == Result.errCantGetDataFromTable)

msgId = R.string.errCantGetDataFromTable;

if(result == Result.errCantFindData)

msgId = R.string.errCantFindData;

if(result == Result.errCantGetData)

msgId = R.string.errCantGetData;

if(result == Result.errCantDeleteData)

msgId = R.string.errCantDeleteData;

if(result == Result.errTableNotExists)

msgId = R.string.errTableNotExists;

if(result == Result.errCantSetValuesForDataRow)

msgId = R.string.errCantSetValuesForDataRow;

if(result == Result.errCantGetValuesFromDataRow)

msgId = R.string.errCantGetValuesFromDataRow;

returnmsgId;

}

/**關閉DB**/

publicvoidclose()

{

if(isOpened())

db.close();

}

/**判斷DB是否打開**/

publicbooleanisOpened()

{

if(db !=null)

returntrue;

returnfalse;

}

/**得到DB寫操作類 **/

publicSQLiteDatabase getWriteSQLiteDb()

{

returngetWritableDatabase();

}

/**得到DB讀操作類 **/

publicSQLiteDatabase getReadSQLiteDb()

{

returngetReadableDatabase();

}

/**查詢Table是否存在**/

publicbooleanisTableExists(String sTableName)

{

booleanbResult =false;

if(isOpened())

{

String sql ="select name from sqlite_master where type = 'table' and name = '%s'";

sql = String.format(sql, sTableName);

Cursor cr = db.rawQuery(sql,null);

if(cr.getCount() >0)

bResult =true;

cr.close();

}

returnbResult;

}

/** 建表是否成功 **/

publicbooleanTablesCreated()

{

returnresultDbTablesCreated == Result.Success;

}

/** 判斷DB是否準備好了**/

publicsynchronizedbooleanDatabaseReady()

{

return(isOpened() && TablesCreated());

}

/** 返回創建表的結果 是成功還是失敗 **/

publicResult TablesCreationResult()

{

returnresultDbTablesCreated;

}

}

表中字段类DataField

[java]view plaincopy

/**

*  表中的字段類

* @author KrisLight

*/

publicclassDataField

{

//types

/** Type枚举 如:INT,TEXT,BOOL**/

publicstaticenumType { INT, TEXT, BOOL };

//fields

/** Calendar實例 **/

privateCalendar dateOut = Calendar.getInstance();

//fields

/** 對應的數據類型 **/

privateDataRow dataRow =null;

/** 對應字段的值 **/

privateContentValues values =null;

//fields

/**字段索引**/

privateintindex =0;

/** ContentValues存放鍵值對的鍵值 **/

privateString sName ="";

/** 字段类型 从Type枚举中取一个类型的值 默認為Int **/

privateType FieldType = Type.INT;

/**是否可以為空**/

privatebooleanbCanBeNull =true;

/**是否是主鍵**/

privatebooleanbPrimaryKey =false;

//methods

/**

* 构造方法

* @param index 索引

* @param sName 字段名

* @param FieldType 字段类型

* @param bCanBeNull 是否为空

* @param bPrimaryKey 是否为主键

*/

publicDataField(intindex, String sName, Type FieldType,booleanbCanBeNull,booleanbPrimaryKey)

{

this.index = index;

this.sName = sName;

this.FieldType = FieldType;

this.bCanBeNull = bCanBeNull;

this.bPrimaryKey = bPrimaryKey;

}

/**

* 得到每一個字段描述 形如: "name int PRIMARY KEY Not Null"

* @return

*/

publicString GetColumnDefinition()

{

String s = sName +" "+ GetSqlType(FieldType);

if(bPrimaryKey)

s +=" PRIMARY KEY";

if(!bCanBeNull)

s +=" NOT NULL";

returns;

}

publicType GetType()

{

returnFieldType;

}

publicintGetIndex()

{

returnindex;

}

/** 根據SqlType返回真實的類型字段 注意BOOL對應的是Integer 其他類型的用Text **/

publicString GetSqlType(Type value)

{

switch(value)

{

caseINT:return"INTEGER";

caseTEXT:return"TEXT";

caseBOOL:return"INTEGER";

}

return"TEXT";

}

/** 设置这个字段对应的数据类型 **/

publicvoidSetParentRow(DataRow dataRow)

{

this.dataRow = dataRow;

this.values =this.dataRow.GetContentValues();

}

/** 得到字段的名字 **/

publicString GetName()

{

returnsName;

}

//getters

/** 字符串类型的字段的值 **/

publicString asString()

{

returnvalues.getAsString(sName);

}

/** Long类型的字段的值 **/

publiclongasLong()

{

returnvalues.getAsLong(sName);

}

/** Boolean类型的字段的值 **/

publicbooleanasBoolean()

{

return(values.getAsLong(sName) ==1);

}

/** 判断是否为Null **/

publicbooleanisNull()

{

return(values.get(sName) ==null);

}

/** 将Long类型的日期类型转换成标准的日期时间 **/

publicCalendar asCalendar()

{

dateOut.setTimeInMillis(values.getAsLong(sName));

returndateOut;

}

//setters

/** 设置字符串值 **/

publicvoidset(String value)

{

values.put(sName, value);

}

/** 设置整型值 **/

publicvoidset(longvalue)

{

values.put(sName, value);

}

/** 设置布尔值 **/

publicvoidset(booleanvalue)

{

inti = (value)?1:0;

values.put(sName, i);

}

/** 设置日期值 **/

publicvoidset(Calendar value)

{

values.put(sName, value.getTimeInMillis());

}

/** 设置Null值 **/

publicvoidsetNull()

{

values.put(sName, (String)null);

}

}

数据原型类DataRow

[java]view plaincopy

/**

* 抽象的数据类型类,

* 所有的数据原型都要继承这个类

* @author KrisLight

*

*/

publicabstractclassDataRow

{

/** 这个类型对应表中的字段集合 **/

privateDataField[] vecTableDef =null;

/** 这个类型对应表中的字段的值 用ContentValues形式存放 **/

privateContentValues values =newContentValues();

/** 構造方法 **/

publicDataRow(){}

/**

* 設置字段集合并綁定

* @param vecTableDef 字段集合

*/

publicvoidSetTableDefinition(DataField[] vecTableDef)

{

this.vecTableDef = vecTableDef;

UpdateDataFieldsParentRow(this);

}

/** 將數據類型綁定其對應的所有字段 **/

publicvoidUpdateDataFieldsParentRow(DataRow row)

{

for(inti =0; i < vecTableDef.length; i++)

vecTableDef[i].SetParentRow(row);

}

/** 拷貝另一個DataRow中的所有字段 **/

publicvoidCopyTableDefinition(DataRow data)

{

SetTableDefinition(data.vecTableDef);

}

/** 得到表中的所有字段 **/

publicDataField[] GetTableDef()

{

returnvecTableDef;

}

/** 驗證方法 **/

publicbooleanValidate()

{

returnfalse;

}

/** 清空ContentValues **/

publicvoidClearContentValues()

{

values.clear();

}

/** 得到ContentValues **/

publicContentValues GetContentValues()

{

returnvalues;

}

/** 設置ContentValues **/

publicvoidSetContentValues(ContentValues values)

{

this.values = values;

UpdateDataFieldsParentRow(this);

}

/** 拷貝ContentValues **/

publicbooleanCopyContentValues(ContentValues values)

{

this.values = values;

UpdateDataFieldsParentRow(this);

try

{

GetValuesFromDataRow();

returntrue;

}catch(Exception e) {

}

returnfalse;

}

/** 根據索引取出字段 **/

publicDataField Value(intidx)

{

returnvecTableDef[idx];

}

/** 得到索引位置的字段名 **/

publicString fieldName(intidx)

{

returnvecTableDef[idx].GetName();

}

/** 查詢結果 遍歷Cursor結果集給對應的字段賦值 **/

publicbooleanGetValuesFromCursor(Cursor cr)

{

if((cr !=null) && (cr.getPosition() != -1))

{

//遍歷

for(intidx =0; idx < vecTableDef.length; idx++)

{

DataField field = Value(idx);

//check if null value

if(cr.isNull(idx))

{

//如果查出的值為空 ,設置為空

field.setNull();

}else{

//根據其對應的類型取值

finalDataField.Type t = field.GetType();

//parse value by type

if(t == DataField.Type.INT)

field.set(cr.getLong(idx));

if(t == DataField.Type.TEXT)

field.set(cr.getString(idx));

if(t == DataField.Type.BOOL)

field.set((cr.getInt(idx) ==1)?true:false);

}

}

returntrue;

}

returnfalse;

}

//sets fields values data (ContentValues values contener) from parent object fields

/** 為字段賦值 **/

publicabstractvoidSetValuesForDataRow();

//gets data from fields values (ContentValues values contener) to parent object fields

/** 得到這個數據類型對應的所有的字段的值 **/

publicabstractvoidGetValuesFromDataRow();

/** 得到表名 **/

publicabstractString GetTableName();

}

Table类

[java]view plaincopy

/**

* 數據庫中的表類 包含了该表对应的数据类型以及对表的增删改查操作方法

* @author KrisLight

*/

publicclassDataTable

{

/** 這個表綁定的數據類型 **/

privateDataRow dataRow =null;

/** DB輔助類 **/

privateDatabaseOpenHelper helper;

/**

* 更據DataRow來決定是哪一個Table

* @param dataRow

*/

publicDataTable(DataRow dataRow,DatabaseOpenHelper helper)

{

this.dataRow = dataRow;

this.helper = helper;

}

/** 得到表名 **/

publicString getTableName()

{

returndataRow.GetTableName();

}

//DataRow getter()

publicDataRow getDataRow()

{

returndataRow;

}

/** 基本的插入操作 **/

publiclonginsertValues()

{

longlRowId = helper.getWritableDatabase().insert(getTableName(),null, dataRow.GetContentValues());

returnlRowId;

}

/** 基本的根據ID更新操作 **/

publiclongupdateValues(longlRowId)

{

String sWhere = String.format("_ID = %d", lRowId);

longlRowsUpdated = helper.getWritableDatabase().update(getTableName(), dataRow.GetContentValues(), sWhere,null);

returnlRowsUpdated;

}

/** 基本的根據ID刪除操作 **/

publiclongdeleteDataRow(longlRowId)

{

String sWhere = String.format("_ID = %d", lRowId);

longlRowsUpdated = helper.getWritableDatabase().delete(getTableName(), sWhere,null);

returnlRowsUpdated;

}

/** 基本的根據Id查詢表中的所有字段值 **/

publicCursor locateDataRow(longlRowId)

{

List columnNames = getColumn();

String cols = Utils.join(columnNames,",");

finalString s ="select %s from %s where _ID = %d";

String sql = String.format(s, cols, getTableName(), lRowId);

Cursor cr = helper.getReadableDatabase().rawQuery(sql,null);

//if cursor valid, set first data row as current

if((cr !=null) && (cr.getCount() >0))

cr.moveToFirst();

returncr;

}

/** 基本的根據類型和REF_ID查詢鬧鈴提醒功能表的所有字段數據 **/

publicCursor locateAlarmDataRow(intiType,longlRefID)

{

List columnNames = getColumn();

String cols = Utils.join(columnNames,",");

finalString s ="select %s from %s where Type = %d and RefID = %d";

String sql = String.format(s, cols, getTableName(), iType, lRefID);

Cursor cr = helper.getReadableDatabase().rawQuery(sql,null);

if((cr !=null) && (cr.getCount() >0))

cr.moveToFirst();

returncr;

}

/**

* 封装的saveOrUpdate操作

* @param bInsertMode  是否是插入模式 為true的話是插入新的數據 為false則直接更新舊數據

* @param lEditRowId   ID

* @return

*/

publicDatabaseOpenHelper.Result updateData(booleanbInsertMode,longlEditRowId)

{

DatabaseOpenHelper.Result result = DatabaseOpenHelper.Result.errUnknown;

if(helper.isOpened())

{

try

{

//為字段賦值

dataRow.SetValuesForDataRow();

}catch(Exception e) {

//異常就拋出錯誤信息 不能為數據類型的字段賦值

returnDatabaseOpenHelper.Result.errCantSetValuesForDataRow;

}

//select update mode

if(bInsertMode)

{

//insert new data row

longlRowId = insertValues();

if(lRowId >0)

{

//插入成功

result = DatabaseOpenHelper.Result.Success;

}else{

//插入失敗

result = DatabaseOpenHelper.Result.errCantInsertNewData;

}

}else{

//update existing data row

longlRowsUpdated = updateValues(lEditRowId);

if(lRowsUpdated ==1)

{

//更新成功

result = DatabaseOpenHelper.Result.Success;

}else{

//更新失敗

result = DatabaseOpenHelper.Result.errCantUpdateData;

}

}

}else{

result = DatabaseOpenHelper.Result.errNoDbAccess;

}

returnresult;

}

/** 封装的根據Id刪除 **/

publicDatabaseOpenHelper.Result deleteData(longiRowId)

{

DatabaseOpenHelper.Result result = DatabaseOpenHelper.Result.errUnknown;

if(helper.isOpened())

{

if(helper.isTableExists(getTableName()))

{

longlRowsDeleted = deleteDataRow(iRowId);

if(lRowsDeleted ==1)

{

result = DatabaseOpenHelper.Result.Success;

}else{

result = DatabaseOpenHelper.Result.errCantDeleteData;

}

}else{

result = DatabaseOpenHelper.Result.errTableNotExists;

}

}else{

result = DatabaseOpenHelper.Result.errNoDbAccess;

}

returnresult;

}

/** 封装的根據ID查詢數據 **/

publicDatabaseOpenHelper.Result getRowDataForEdit(longlRowId)

{

DatabaseOpenHelper.Result result = DatabaseOpenHelper.Result.errUnknown;

//get requested data row

Cursor cr = locateDataRow(lRowId);

if(cr ==null)

{

//如果返回為空 結果為errCantGetData

result = DatabaseOpenHelper.Result.errCantGetData;

}else{

if(cr.getCount() >0)

{

if(dataRow.GetValuesFromCursor(cr))

{

try

{

dataRow.GetValuesFromDataRow();

}catch(Exception e) {

returnDatabaseOpenHelper.Result.errCantGetValuesFromDataRow;

}

result = DatabaseOpenHelper.Result.Success;

}else{

//無法從表中取出数据

result = DatabaseOpenHelper.Result.errCantGetDataFromTable;

}

//关闭光标

cr.close();

}else{

//无法找到数据

result = DatabaseOpenHelper.Result.errCantFindData;

}

}

returnresult;

}

/** 得到這個表中的所有字段 **/

publicList getColumn() {

List ar =newArrayList();

try{

DataField[] fields = dataRow.GetTableDef();

for(DataField f : fields){

ar.add(f.GetName());

}

}catch(Exception e) {

e.printStackTrace();

}

returnar;

}

}

安装程序类Installating

[java]view plaincopy

publicclassInstallation {

privatestaticString sID =null;

privatestaticfinalString INSTALLATION ="INSTALLATION";

publicsynchronizedstaticString id(Context context) {

if(sID ==null) {

File installation =newFile(context.getFilesDir(), INSTALLATION);

try{

if(!installation.exists()){

writeInstallationFile(installation, context);

}

sID = readInstallationFile(installation);

}catch(Exception e) {

//throw new RuntimeException(e);

}

}

returnsID;

}

privatestaticString readInstallationFile(File installation)throwsIOException {

RandomAccessFile f =newRandomAccessFile(installation,"r");

byte[] bytes =newbyte[(int) f.length()];

f.readFully(bytes);

f.close();

returnnewString(bytes);

}

privatestaticvoidwriteInstallationFile(File installation, Context context)throwsIOException {

FileOutputStream out =newFileOutputStream(installation);

String id ="";

try{

id = Settings.Secure.getString(context.getContentResolver(),

Settings.Secure.ANDROID_ID);

id+=id;

}catch(Exception e){

id = UUID.randomUUID().toString();

}

out.write(id.getBytes());

out.close();

}

}

获取资源类SearchResource

[java]view plaincopy

publicclassSearchResource {

publicstaticintgetDrawableResId(Context cnt, String name)throwsNotFoundException {

intresid =0;

resid = cnt.getResources().getIdentifier(name,"drawable", cnt.getPackageName());

if(resid ==0)

resid = cnt.getResources().getIdentifier("transparent_background","drawable", cnt.getPackageName());

returnresid;

}

publicstaticintgetStringResId(Context cnt, String name)throwsNotFoundException {

intresid =0;

resid = cnt.getResources().getIdentifier(name,"string", cnt.getPackageName());

if(resid ==0)

resid = cnt.getResources().getIdentifier("empty_string","string", cnt.getPackageName());

returnresid;

}

publicstaticintgetLayoutResId(Context cnt, String name)throwsNotFoundException {

intresid =0;

resid = cnt.getResources().getIdentifier(name,"layout", cnt.getPackageName());

if(resid ==0)

resid = cnt.getResources().getIdentifier("empty_layout","layout", cnt.getPackageName());

returnresid;

}

publicstaticintgetItemResId(Context cnt, String name)throwsNotFoundException {

intresid = cnt.getResources().getIdentifier(name,"id", cnt.getPackageName());

returnresid;

}

publicstaticintgetAnimResId(Context cnt, String name)throwsNotFoundException {

intresid = cnt.getResources().getIdentifier(name,"anim", cnt.getPackageName());

returnresid;

}

publicstaticintgetAttrResId(Context cnt, String attrName)throwsNotFoundException {

intresid = cnt.getResources().getIdentifier(attrName,"attr", cnt.getPackageName());

returnresid;

}

publicstaticintgetStyleResId(Context cnt, String attrName)throwsNotFoundException {

intresid = cnt.getResources().getIdentifier(attrName,"style", cnt.getPackageName());

returnresid;

}

publicstaticintgetMenuResId(Context cnt, String name)throwsNotFoundException {

intresid = cnt.getResources().getIdentifier(name,"menu", cnt.getPackageName());

returnresid;

}

publicstaticint[] getStyleableArray(Context cnt, String name) {

returnnull;

}

}

发送短信类SendMessage

[java]view plaincopy

publicclassSendMessage {

privatestaticfinalString TAG ="SendMessage";

privateContext m_contect;

privateArrayList> m_ContactList;

privateArrayList> m_ContactListbuffer;

privateString m_strMessageContent;

privateintm_intMessageSendCount=0;

privateintm_intMessageSendTotalParts;

privateintm_intMessageSendParts;

publicstaticfinalString SENT ="com.commez.psmd.SMS_SENT";

publicstaticfinalString DELIVERED ="com.commez.psmd.SMS_DELIVERED";

privateArrayList m_phoneList;

privateListView m_ltvDialogContactList;

privateCustomDialogAdapter m_DialogAdapter;

privateDialog dialog;

privatebooleanm_isSendCancel;

privatestaticHandler m_handler =newHandler();

privateBroadcastReceiver m_bcrSend;

privateBroadcastReceiver m_bcrDelivred;

publicSendMessage(Context context, ArrayList> contactList,  String messageContent){

this.m_contect = context;

this.m_strMessageContent = messageContent;

m_ContactListbuffer =newArrayList>(contactList);

m_isSendCancel =false;

fillPhoneNumber();

}

publicvoidstartSendMessage(){

showSendingListDialog();

registerBroadCastReceivers();

m_intMessageSendCount =0;

sendSMS(m_phoneList.get(m_intMessageSendCount).toString(), m_strMessageContent);

}

privatevoidfillPhoneNumber(){

if(m_ContactListbuffer!=null){

m_ContactList =newArrayList>();

HashMap temp;

for(intj=0; j

temp=newHashMap();

if(m_ContactListbuffer.get(j).get("name")!=null)

temp.put("name", m_ContactListbuffer.get(j).get("name").toString());

if(m_ContactListbuffer.get(j).get("number")!=null)

temp.put("number", m_ContactListbuffer.get(j).get("number").toString());

if(m_ContactListbuffer.get(j).get("contentid")!=null)

temp.put("contentid", m_ContactListbuffer.get(j).get("contentid").toString());

if(j==m_intMessageSendCount)

temp.put("sendstatus","sending");

else

temp.put("sendstatus","unsend");

m_ContactList.add(temp);

}

m_phoneList =newArrayList();

for(inti=0; i

m_phoneList.add(m_ContactList.get(i).get("number").toString());

}

}

}

privatevoidsendNextMessage(){

if(thereAreSMSToSend()){

//m_phoneList.

//m_DialogAdapter.notifyDataSetChanged();

/*if(m_ContactList!=null)

m_ContactList.clear();

HashMap temp;

for(int j=0; j

temp=new HashMap();

if(m_ContactListbuffer.get(j).get("name")!=null)

temp.put("name", m_ContactListbuffer.get(j).get("name").toString());

if(m_ContactListbuffer.get(j).get("number")!=null)

temp.put("number", m_ContactListbuffer.get(j).get("number").toString());

if(m_ContactListbuffer.get(j).get("contentid")!=null)

temp.put("contentid", m_ContactListbuffer.get(j).get("contentid").toString());

if(j

temp.put("sendstatus", "sent");

else if(j==m_intMessageSendCount)

temp.put("sendstatus", "sending");

else

temp.put("sendstatus", "unsend");

m_ContactList.add(j,temp);

}*/

HashMap temp =newHashMap();

if(m_ContactListbuffer.get(m_intMessageSendCount).get("name")!=null)

temp.put("name", m_ContactListbuffer.get(m_intMessageSendCount).get("name").toString());

if(m_ContactListbuffer.get(m_intMessageSendCount).get("number")!=null)

temp.put("number", m_ContactListbuffer.get(m_intMessageSendCount).get("number").toString());

if(m_ContactListbuffer.get(m_intMessageSendCount).get("contentid")!=null)

temp.put("contentid", m_ContactListbuffer.get(m_intMessageSendCount).get("contentid").toString());

temp.put("sendstatus","sending");

m_ContactList.set(m_intMessageSendCount,temp);

sendSMS(m_phoneList.get(m_intMessageSendCount).toString(), m_strMessageContent);

m_DialogAdapter.notifyDataSetChanged();

}else{

Toast.makeText(m_contect,"All SMS have been sent",Toast.LENGTH_SHORT).show();

dialog.dismiss();

unRegisterBroadCastReceivers();

}

}

privatevoidunRegisterBroadCastReceivers() {

m_contect.unregisterReceiver(m_bcrSend);

m_contect.unregisterReceiver(m_bcrDelivred);

}

privatebooleanthereAreSMSToSend(){

returnm_intMessageSendCount < m_phoneList.size();

}

privatevoidsendSMS(String strPhoneNumber, String message){

SmsManager sms = SmsManager.getDefault();

ArrayList parts = sms.divideMessage(message);

m_intMessageSendTotalParts = parts.size();

ArrayList deliveryIntents =newArrayList();

ArrayList sentIntents =newArrayList();

PendingIntent sentPI = PendingIntent.getBroadcast(m_contect,0,newIntent(SENT),0);

PendingIntent deliveredPI = PendingIntent.getBroadcast(m_contect,0,newIntent(DELIVERED),0);

for(intj=0; j

sentIntents.add(sentPI);

deliveryIntents.add(deliveredPI);

}

m_intMessageSendParts =0;

/**************************************************************/

/*  SystemClock.sleep(50);

m_intMessageSendParts++;

if(m_intMessageSendParts == m_intMessageSendTotalParts){

m_intMessageSendCount++;

sendNextMessage();

m_DialogAdapter.notifyDataSetChanged();

}

/******************************************************************/

//  sms.sendMultipartTextMessage(strPhoneNumber, null, parts, sentIntents, deliveryIntents);

//m_handler.removeCallbacks(updatTimer);

//m_handler.postDelayed(updatTimer, 3000);

}

privateRunnable updatTimer =newRunnable() {

publicvoidrun() {

if(m_intMessageSendCount

HashMap temp =newHashMap();

if(m_ContactListbuffer.get(m_intMessageSendCount).get("name")!=null)

temp.put("name", m_ContactListbuffer.get(m_intMessageSendCount).get("name").toString());

if(m_ContactListbuffer.get(m_intMessageSendCount).get("number")!=null)

temp.put("number", m_ContactListbuffer.get(m_intMessageSendCount).get("number").toString());

if(m_ContactListbuffer.get(m_intMessageSendCount).get("contentid")!=null)

temp.put("contentid", m_ContactListbuffer.get(m_intMessageSendCount).get("contentid").toString());

temp.put("sendstatus","sent");

m_ContactList.set(m_intMessageSendCount,temp);

m_intMessageSendCount++;

sendNextMessage();

}

}

};

privatevoidregisterBroadCastReceivers() {

IntentFilter intentFilter =newIntentFilter(SENT);

m_bcrSend =newBroadcastReceiver() {

@Override

publicvoidonReceive(Context arg0, Intent arg1) {

switch(getResultCode()){

caseActivity.RESULT_OK:

m_intMessageSendParts++;

if(m_intMessageSendParts == m_intMessageSendTotalParts && !m_isSendCancel){

HashMap temp =newHashMap();

if(m_ContactListbuffer.get(m_intMessageSendCount).get("name")!=null)

temp.put("name", m_ContactListbuffer.get(m_intMessageSendCount).get("name").toString());

if(m_ContactListbuffer.get(m_intMessageSendCount).get("number")!=null)

temp.put("number", m_ContactListbuffer.get(m_intMessageSendCount).get("number").toString());

if(m_ContactListbuffer.get(m_intMessageSendCount).get("contentid")!=null)

temp.put("contentid", m_ContactListbuffer.get(m_intMessageSendCount).get("contentid").toString());

temp.put("sendstatus","sent");

m_ContactList.set(m_intMessageSendCount,temp);

m_intMessageSendCount++;

sendNextMessage();

}

//Toast.makeText(m_contect, "SMS sent",Toast.LENGTH_SHORT).show();

break;

caseSmsManager.RESULT_ERROR_GENERIC_FAILURE:

Toast.makeText(m_contect,"Generic failure",Toast.LENGTH_SHORT).show();

break;

caseSmsManager.RESULT_ERROR_NO_SERVICE:

Toast.makeText(m_contect,"No service",Toast.LENGTH_SHORT).show();

break;

caseSmsManager.RESULT_ERROR_NULL_PDU:

Toast.makeText(m_contect,"No PDU",Toast.LENGTH_SHORT).show();

break;

caseSmsManager.RESULT_ERROR_RADIO_OFF:

Toast.makeText(m_contect,"Radio off",Toast.LENGTH_SHORT).show();

break;

}

}

};

m_contect.registerReceiver(m_bcrSend, intentFilter);

IntentFilter intentFilter1 =newIntentFilter(DELIVERED);

m_bcrDelivred =newBroadcastReceiver() {

@Override

publicvoidonReceive(Context arg0, Intent arg1) {

switch(getResultCode()){

caseActivity.RESULT_OK:

break;

caseActivity.RESULT_CANCELED:

break;

}

}

};

m_contect.registerReceiver(m_bcrDelivred, intentFilter1);

/*m_contect.registerReceiver(new BroadcastReceiver(){

@Override

public void onReceive(Context arg0, Intent arg1) {

switch(getResultCode()){

case Activity.RESULT_OK:

m_intMessageSendParts++;

if(m_intMessageSendParts == m_intMessageSendTotalParts && !m_isSendCancel){

HashMap temp =new HashMap();

if(m_ContactListbuffer.get(m_intMessageSendCount).get("name")!=null)

temp.put("name", m_ContactListbuffer.get(m_intMessageSendCount).get("name").toString());

if(m_ContactListbuffer.get(m_intMessageSendCount).get("number")!=null)

temp.put("number", m_ContactListbuffer.get(m_intMessageSendCount).get("number").toString());

if(m_ContactListbuffer.get(m_intMessageSendCount).get("contentid")!=null)

temp.put("contentid", m_ContactListbuffer.get(m_intMessageSendCount).get("contentid").toString());

temp.put("sendstatus", "sent");

m_ContactList.set(m_intMessageSendCount,temp);

m_intMessageSendCount++;

sendNextMessage();

}

//Toast.makeText(m_contect, "SMS sent",Toast.LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_GENERIC_FAILURE:

Toast.makeText(m_contect, "Generic failure",Toast.LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_NO_SERVICE:

Toast.makeText(m_contect, "No service",Toast.LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_NULL_PDU:

Toast.makeText(m_contect, "No PDU",Toast.LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_RADIO_OFF:

Toast.makeText(m_contect, "Radio off",Toast.LENGTH_SHORT).show();

break;

}

}

}, new IntentFilter(SENT));

m_contect.registerReceiver(new BroadcastReceiver(){

@Override

public void onReceive(Context arg0, Intent arg1) {

switch(getResultCode()){

case Activity.RESULT_OK:

break;

case Activity.RESULT_CANCELED:

break;

}

}

}, new IntentFilter(DELIVERED));

*/

}

privatevoidshowSendingListDialog() {

LayoutInflater factory = LayoutInflater.from(m_contect);

View dialogView = factory.inflate(R.layout.sms_send_list,null);

m_ltvDialogContactList = (ListView) dialogView.findViewById(R.id.lv_sendlist);

setDialogAdapter();

TextView dialogContent = (TextView) dialogView.findViewById(R.id.dialog_sendlist_content);

dialogContent.setText(R.string.dtl_SendList);

Button rightButton = (Button) dialogView.findViewById(R.id.dialog_sendlist_rightbtn);

rightButton.setText(R.string.dmg_SendBackground);

Button leftButton = (Button) dialogView.findViewById(R.id.dialog_sendlist_leftbtn);

leftButton.setText(R.string.dmg_SendCancel);

rightButton.setOnClickListener(newOnClickListener() {

@Override

publicvoidonClick(View v) {

dialog.dismiss();

}

});

leftButton.setOnClickListener(newOnClickListener() {

@Override

publicvoidonClick(View v) {

dialog.dismiss();

}

});

dialog =newDialog(m_contect);

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

dialog.setCancelable(false);

dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

dialog.getWindow().setBackgroundDrawable(newColorDrawable(0));

dialog.setContentView(dialogView);

dialog.show();

/*dialog = new AlertDialog.Builder(m_contect).setTitle(R.string.dtl_SendList)

.setView(dialogView)

.setPositiveButton(R.string.dmg_SendCancel, new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

m_isSendCancel = true;

unRegisterBroadCastReceivers();

}})

.setNegativeButton(R.string.dmg_SendBackground, new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

}}).create();

dialog.show();*/

}

privatevoidsetDialogAdapter() {

m_DialogAdapter =newCustomDialogAdapter(m_contect, R.layout.sms_send_list_item, m_ContactList);

m_ltvDialogContactList.setAdapter(m_DialogAdapter);

}

privateclassCustomDialogAdapterextendsArrayAdapter> {

publicCustomDialogAdapter(Context context,inttextViewResourceId, ArrayList> Strings) {

super(context, textViewResourceId, Strings);

}

privateclassViewHolder{

TextView txvContact;

TextView txvSendStatus;

ProgressBar prgbSend;

}

ViewHolder viewHolder;

@Override

publicView getView(finalintposition, View convertView, ViewGroup parent) {

if(convertView==null){

LayoutInflater inflater = (LayoutInflater) m_contect.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

convertView = inflater.inflate(R.layout.sms_send_list_item,null);

viewHolder=newViewHolder();

viewHolder.txvContact=(TextView) convertView.findViewById(R.id.txvSendlistitem_name);

viewHolder.txvSendStatus=(TextView) convertView.findViewById(R.id.txvSendlistitem_status);

viewHolder.prgbSend=(ProgressBar) convertView.findViewById(R.id.pb_sending);

convertView.setTag(viewHolder);

}

viewHolder=(ViewHolder) convertView.getTag();

viewHolder.txvContact.setText(m_ContactList.get(position).get("number").toString());

String isSend = m_ContactList.get(position).get("sendstatus").toString();

if(isSend=="sent"){

viewHolder.prgbSend.setVisibility(View.GONE);

viewHolder.txvSendStatus.setVisibility(View.VISIBLE);

viewHolder.txvSendStatus.setText(R.string.dmg_Sent);

}elseif(isSend=="sending"){

viewHolder.prgbSend.setVisibility(View.VISIBLE);

viewHolder.txvSendStatus.setVisibility(View.GONE);

}elseif(isSend=="unsend"){

viewHolder.prgbSend.setVisibility(View.GONE);

viewHolder.txvSendStatus.setVisibility(View.VISIBLE);

viewHolder.txvSendStatus.setText(R.string.dmg_SendWait);

}

returnconvertView;

}

}

/*public static void sendMessage(Context context, String strAddress, String strMessage){

try {

Uri smsUri = Uri.parse("tel:123456");

Intent intent = new Intent(Intent.ACTION_VIEW, smsUri);

intent.putExtra("sms_body", "");

intent.setType("vnd.android-dir/mms-sms");

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(intent);

} catch (ActivityNotFoundException e) {

Log.e(TAG, "Send SMS failed", e);

}

}*/

}

时间字符串处理类1:

[java]view plaincopy

publicclassC_DateUtils {

privatestaticfinalString TAG = C_DateUtils.class.getSimpleName();

/**

* check date is today

* @param date

* @return

*/

publicstaticbooleanisToday(Date date){

returnisSameDate(newDate(), date);

}

/**

* check Date is same day

* @param baseDate

* @param thenDate

* @return

*/

publicstaticbooleanisSameDate(Date baseDate, Date thenDate){

Time time =newTime();

time.set(thenDate.getTime());

intthenYear = time.year;

intthenMonth = time.month;

intthenMonthDay = time.monthDay;

time.set(baseDate.getTime());

return(thenYear == time.year)

&& (thenMonth == time.month)

&& (thenMonthDay == time.monthDay);

}

/**

* caculate day counts between startDate and endDate

* @param startDate

* @param endDate

* @return

*/

publicstaticintdiffDays(Date startDate, Date endDate){

return(int)((endDate.getTime() - startDate.getTime()) / DateUtils.DAY_IN_MILLIS);

}

/**

* caculate week counts between startDate and endDate

* @param startDate

* @param endDate

* @return

*/

publicstaticintdiffWeeks(Date startDate, Date endDate){

return(int)((endDate.getTime() - startDate.getTime()) / DateUtils.WEEK_IN_MILLIS);

}

/**

* caculate month counts between startDate and endDate

* @param startDate

* @param endDate

* @return

*/

publicstaticintdiffMonths(Date startDate, Date endDate){

Time startTime =newTime();

startTime.set(startDate.getTime());

Time endTime =newTime();

endTime.set(endDate.getTime());

intdiffYears = endTime.year - startTime.year;

returndiffYears *12+ endTime.month - startTime.month;

}

/**

* caculate year counts between startDate and endDate

* @param startDate

* @param endDate

* @return

*/

publicstaticintdiffYears(Date startDate, Date endDate){

Time startTime =newTime();

startTime.set(startDate.getTime());

Time endTime =newTime();

endTime.set(endDate.getTime());

intdiffYears = endTime.year - startTime.year;

returndiffYears;

}

/**

* return date is Saturday or Sunday

* @param date

* @return

*/

publicstaticbooleanisWeekend(Date date){

Time time =newTime();

time.set(date.getTime());

return(time.weekDay == Time.SATURDAY || time.weekDay == Time.SUNDAY);

}

}

时间字符串处理类2:

[java]view plaincopy

/**

* 工具類

* @author KrisLight

*

*/

publicclassUtils

{

/**

* 透明度動畫變化持續時間

*/

publicstaticintANIM_ALPHA_DURATION =100;

/**

* 平移動畫持續時間

*/

publicstaticintANIM_TRANSLATE_DURATION =30;

/**

*  周別格式   EEEE

*/

privateSimpleDateFormat dateFormatWeekDay =newSimpleDateFormat("EEEE");

/**

*  月份格式    MMMM

*/

privateSimpleDateFormat dateFormatMonth =newSimpleDateFormat("MMMM");

/**

*  包括年,月,日,周的日期格式   EEEE, d MMMM yyyy

*/

privateSimpleDateFormat dateFormatLong =newSimpleDateFormat("EEEE, d MMMM yyyy");

/**

*  包括年,月,日的日期格式   dd-MM-yyyy

*/

privateSimpleDateFormat dateFormatShort =newSimpleDateFormat("dd-MM-yyyy");

/**

* Sql中的日期格式   dd-MM-yyyy kk:mm.ss

*/

privateSimpleDateFormat dateFormatSql =newSimpleDateFormat("dd-MM-yyyy kk:mm.ss");

//UTILS

publicUtils()

{

}

/**

* 得到周別的日期字符串

*/

publicString GetWeekDay(Calendar date)

{

returndateFormatWeekDay.format(date.getTime());

}

/**

* 得到月的日期字符串

*/

publicString GetMonth(Calendar date)

{

returndateFormatMonth.format(date.getTime());

}

/**

* 得到包括年,月,日,周的日期格式字符串

*/

publicString GetLongDate(Calendar date)

{

returndateFormatLong.format(date.getTime());

}

/**

* 得到包括年,月,日的日期格式字符串

*/

publicString GetShortDate(Calendar date)

{

returndateFormatShort.format(date.getTime());

}

/**

*

* @Function: pl.magot.vetch.ancal.Utils.GetLongTime

* @Description: 得到時和分

*

* @param date 日期

* @param b24HourMode  是否24小時制: true 是  false 否

* @return  由小時和分鐘組成的字符串 如: 12:20

*

* @version:v1.0

* @author:KrisLight

* @date:2013/9/4 下午4:51:27

*

* Modification History:

* Date         Author      Version     Description

* -----------------------------------------------------------------

* 2013/9/4    KrisLight      v1.0.0         create

*/

publicString GetLongTime(Calendar date,booleanb24HourMode)

{

String s ="";

if(b24HourMode)

{

//k: 24 小时制的小时     M: 小时中的分钟

s = String.format("%tk:%tM", date, date);

}else{

//l: 12 小时制的小时     M: 小时中的分钟

if(date.get(Calendar.AM_PM) ==0)//AM

s = String.format("%tl:%tM am", date, date, date.get(Calendar.AM_PM));

if(date.get(Calendar.AM_PM) ==1)//PM

s = String.format("%tl:%tM pm", date, date, date.get(Calendar.AM_PM));

}

returns;

}

/**

*

* @Function: pl.magot.vetch.ancal.Utils.SqlStrToDate

* @Description: 將用Sql語句查出來的日期字符串轉換成對應的日期Date

*

* @param s  sql format: "dd-MM-yyyy kk:mm.ss"

* @param dateOut 轉換成功的日期

* @param dateFail 轉換失敗默認的日期

* @return

*

* @version:v1.0

* @author:KrisLight

* @date:2013/9/4 下午5:07:40

*

* Modification History:

* Date         Author      Version     Description

* -----------------------------------------------------------------

* 2013/9/4    KrisLight      v1.0.0         create

*/

publicstaticCalendar SqlStrToDate(String s, Calendar dateOut, Calendar dateFail)

{

if(s.length() ==19)

{

intdd = Integer.parseInt(s.substring(0,2));

intMM = Integer.parseInt(s.substring(3,5));

intyyyy = Integer.parseInt(s.substring(6,10));

intkk = Integer.parseInt(s.substring(11,13));

intmm = Integer.parseInt(s.substring(14,16));

intss = Integer.parseInt(s.substring(17,19));

// set(int year, int month, int day, int hourOfDay, int minute, int second) 這裡月從0開始  1月對應的是0

dateOut.set(yyyy, MM -1, dd, kk, mm, ss);

returndateOut;

}

returndateFail;

}

/**

*

* @Function: pl.magot.vetch.ancal.Utils.DateToSqlStr

* @Description:將日期轉換成SQL中需要的日期格式

*

* @param date

* @return

*

* @version:v1.0

* @author:KrisLight

* @date:2013/9/4 下午5:11:29

*

* Modification History:

* Date         Author      Version     Description

* -----------------------------------------------------------------

* 2013/9/4    KrisLight      v1.0.0         create

*/

publicString DateToSqlStr(Calendar date)

{

returndateFormatSql.format(date.getTime());

}

/**

*  將時間轉換成秒

*/

publicstaticintGetTimeAsSeconds(Calendar date)

{

return(date.get(Calendar.HOUR_OF_DAY) *3600) +

date.get(Calendar.MINUTE) *60;

}

/**

*  清除日期

*/

publicstaticvoidClearCalendarTime(Calendar cal)

{

cal.clear(Calendar.MILLISECOND);

cal.clear(Calendar.SECOND);

cal.clear(Calendar.MINUTE);

cal.clear(Calendar.HOUR_OF_DAY);

}

/**

*  判斷日期是否相等

*/

publicstaticbooleanYearDaysEqual(Calendar calDate, Calendar calDateTo)

{

if(calDate.get(Calendar.YEAR) == calDateTo.get(Calendar.YEAR))

if(calDate.get(Calendar.MONTH) == calDateTo.get(Calendar.MONTH))

if(calDate.get(Calendar.DAY_OF_MONTH) == calDateTo.get(Calendar.DAY_OF_MONTH))

returntrue;

returnfalse;

}

/**

*  判斷前一個日期是否大於后一個

*/

publicstaticbooleanYearDaysGreater(Calendar calDate, Calendar calDateTo)

{

if(calDate.get(Calendar.YEAR) >= calDateTo.get(Calendar.YEAR))

if(calDate.get(Calendar.MONTH) >= calDateTo.get(Calendar.MONTH))

if(calDate.get(Calendar.DAY_OF_MONTH) >= calDateTo.get(Calendar.DAY_OF_MONTH))

returntrue;

returnfalse;

}

/**

* 判斷前一個時間是否等於或晚於後面一個時間

* 用於設置鬧鐘的時候與當前時間判斷

* 設置的鬧鈴時間必須晚於當前時間

*/

publicstaticbooleanIsTimeOverdued(Calendar calDate, Calendar calDueDate)

{

if((calDueDate.compareTo(calDate) ==0) || (calDueDate.compareTo(calDate) ==1))

returntrue;

returnfalse;

}

//compare time: for calendar view display

publicstaticbooleanIsInTimeRange(Calendar calDateStart, Calendar calDate,intiDurationInMinutes)

{

if(calDate.get(Calendar.HOUR_OF_DAY) == calDateStart.get(Calendar.HOUR_OF_DAY))

if(calDate.get(Calendar.MINUTE) >= calDateStart.get(Calendar.MINUTE))

if(calDate.get(Calendar.MINUTE) <= (calDateStart.get(Calendar.MINUTE) + iDurationInMinutes))

returntrue;

returnfalse;

}

/**

*  將時間轉換成long類型  形如: 200712122359

*/

publicstaticlongGetDateTimeKey(Calendar calDate)

{

longlYear = calDate.get(Calendar.YEAR) *100000000;

longlMonth = calDate.get(Calendar.MONTH) *1000000;

longlDay = calDate.get(Calendar.DAY_OF_MONTH) *10000;

longlHour = calDate.get(Calendar.HOUR_OF_DAY) *100;

longlMinute = calDate.get(Calendar.MINUTE);

returnlYear + lMonth + lDay + lHour + lMinute;

}

/**

*  首字母大寫

*/

publicstaticString CapitalizeFirstLetter(String sText)

{

returnsText.substring(0,1).toUpperCase() + sText.substring(1, sText.length()).toLowerCase();

}

/**

*  得到App版本

*/

publicstaticString getAppVersionName(Context ctx)

{

try

{

PackageInfo pi = ctx.getPackageManager().getPackageInfo("pl.magot.vetch.ancal",0);

returnpi.versionName;

}catch(NameNotFoundException e) {

}

return"";

}

/**

*

* @Function: com.light.mycal.util.Utils.join

* @Description: 集合中的元素以指定分隔符隔開

*

* @param list   集合List

* @param delim  分隔符

* @return  用分隔符隔開的集合元素字符串

*

* @version: v1.0

* @author: KrisLight

* @date: 2013/9/5 上午10:20:51

*

* Modification History:

* Date         Author      Version     Description

* -----------------------------------------------------------------

* 2013/9/5    KrisLight      v1.0.0         create

*/

publicstaticString join(List list, String delim) {

StringBuilder buf =newStringBuilder();

intnum = list.size();

for(inti =0; i < num; i++) {

if(i !=0){

buf.append(delim);

}

buf.append((String) list.get(i));

}

returnbuf.toString();

}

/**

*  開始alpha動畫

*/

publicstaticvoidstartAlphaAnimIn(View view)

{

AlphaAnimation anim =newAlphaAnimation(0.5F,1);

anim.setDuration(ANIM_ALPHA_DURATION);

anim.startNow();

view.startAnimation(anim);

}

/**

*  開始translate動畫

*/

publicstaticvoidstartTranslateAnimIn(View view)

{

TranslateAnimation anim =newTranslateAnimation(0,0, - view.getHeight(),0);

anim.setDuration(ANIM_TRANSLATE_DURATION);

anim.startNow();

view.startAnimation(anim);

}

}

图像处理类

1.图像缓存

[java]view plaincopy

publicclassBitmapCache {

privatestaticfinal

String TAG ="ImageCache";

privatestaticfinalint

DEFAULT_MEM_CACHE_SIZE =1024*1024*8;// 8MB

privatestaticfinalintDEFAULT_DISK_CACHE_SIZE =1024*

1024*20;// 20MB

// Compression settings when

writing images to disk cache

privatestaticfinal

CompressFormat DEFAULT_COMPRESS_FORMAT =

CompressFormat.JPEG;

privatestaticfinalint

DEFAULT_COMPRESS_QUALITY =70;

privatestaticfinal

intDISK_CACHE_INDEX =0;

// Constants to easily

toggle various caches

privatestaticfinalboolean

DEFAULT_MEM_CACHE_ENABLED =true;

privatestaticfinal

booleanDEFAULT_DISK_CACHE_ENABLED =true;

private

staticfinalbooleanDEFAULT_CLEAR_DISK_CACHE_ON_START =

false;

privatestaticfinalboolean

DEFAULT_INIT_DISK_CACHE_ON_CREATE =false;

private

LruDiskCache mDiskLruCache;

private

LruMemoryCache mMemoryCache;

private

ImageCacheParams mCacheParams;

privatefinalObject

mDiskCacheLock =newObject();

privateboolean

mDiskCacheStarting =true;

/**

* Creating a new

ImageCache object using the specified parameters.

*

* @param cacheParams The cache parameters to use to

initialize the cache

*/

publicBitmapCache

(ImageCacheParams cacheParams) {

init

(cacheParams);

}

/**

* Initialize the cache,

providing all parameters.

*

* @param cacheParams

The cache parameters to initialize the cache

*/

privatevoidinit(ImageCacheParams cacheParams) {

mCacheParams = cacheParams;

// Set up memory cache

if(mCacheParams.memoryCacheEnabled) {

mMemoryCache =newLruMemoryCache

(mCacheParams.memCacheSize) {

/**

* Measure item size in bytes rather than units

which is more practical

* for a bitmap

cache

*/

@Override

protectedintsizeOf(String key, Bitmap bitmap) {

returnBitmapCommonUtils.getBitmapSize

(bitmap);

}

};

}

// By default the disk cache is not initialized here as

it should be initialized

// on a separate thread

due to disk access.

if

(cacheParams.initDiskCacheOnCreate) {

// Set

up disk cache

initDiskCache();

}

}

/**

* Initializes the disk cache.  Note that this

includes disk access so this should not be

* executed

on the main/UI thread. By default an ImageCache does not

initialize the disk

* cache when it is created,

instead you should call initDiskCache() to initialize it

on a

* background thread.

*/

publicvoid

initDiskCache() {

// Set up disk cache

synchronized(mDiskCacheLock) {

if

(mDiskLruCache ==null|| mDiskLruCache.isClosed()) {

File diskCacheDir = mCacheParams.diskCacheDir;

if(mCacheParams.diskCacheEnabled &&

diskCacheDir !=null) {

if(!

diskCacheDir.exists()) {

diskCacheDir.mkdirs();

}

if(BitmapCommonUtils.getUsableSpace(diskCacheDir) >

mCacheParams.diskCacheSize) {

try

{

mDiskLruCache =

LruDiskCache.open(diskCacheDir,1,1,

mCacheParams.diskCacheSize);

}

catch(finalIOException e) {

mCacheParams.diskCacheDir =null;

Log.e(TAG,"initDiskCache - "+ e);

}

}

}

}

mDiskCacheStarting =false;

mDiskCacheLock.notifyAll();

}

}

/**

*

Adds a bitmap to both memory and disk cache.

* @param

data Unique identifier for the bitmap to store

*

@param bitmap The bitmap to store

*/

publicvoid

addBitmapToCache(String data, Bitmap bitmap) {

if

(data ==null|| bitmap ==null) {

return;

}

// Add to memory cache

if

(mMemoryCache !=null&& mMemoryCache.get(data) ==null)

{

mMemoryCache.put(data, bitmap);

}

synchronized(mDiskCacheLock) {

if

(mDiskLruCache !=null&& mDiskLruCache.getDirectory()!=

null) {

if(!

mDiskLruCache.getDirectory().exists())

mDiskLruCache.getDirectory().mkdirs();

finalString key =

FileNameGenerator.generator(data);

OutputStream out =null;

try{

LruDiskCache.Snapshot snapshot =

mDiskLruCache.get(key);

if(snapshot

==null) {

final

LruDiskCache.Editor editor = mDiskLruCache.edit(key);

if(editor !=null) {

out = editor.newOutputStream(DISK_CACHE_INDEX);

bitmap.compress(

mCacheParams.compressFormat,

mCacheParams.compressQuality, out);

editor.commit();

out.close();

}

}else{

snapshot.getInputStream

(DISK_CACHE_INDEX).close();

}

}catch(finalIOException e) {

Log.e(TAG,"addBitmapToCache - "+ e);

}

catch(Exception e) {

Log.e(TAG,

"addBitmapToCache - "+ e);

}finally{

try{

if(out !=

null) {

out.close();

}

}catch(IOException e)

{}

}

}

}

}

/**

* Get from memory cache.

*

* @param data Unique

identifier for which item to get

* @return The bitmap

if found in cache, null otherwise

*/

publicBitmap

getBitmapFromMemCache(String data) {

if

(mMemoryCache !=null) {

finalBitmap

memBitmap = mMemoryCache.get(data);

if

(memBitmap !=null) {

returnmemBitmap;

}

}

returnnull;

}

/**

*

@param data

* @return

*/

publicBitmap

getBitmapFromDiskCache(String data) {

final

String key = FileNameGenerator.generator(data);

synchronized(mDiskCacheLock) {

while

(mDiskCacheStarting) {

try{

mDiskCacheLock.wait();

}catch

(InterruptedException e) {}

}

if

(mDiskLruCache !=null) {

InputStream

inputStream =null;

try{

finalLruDiskCache.Snapshot snapshot =

mDiskLruCache.get(key);

if(snapshot

!=null) {

inputStream =

snapshot.getInputStream(DISK_CACHE_INDEX);

if(inputStream !=null) {

finalBitmap bitmap = BitmapFactory.decodeStream

(inputStream);

returnbitmap;

}

}

}catch(finalIOException e) {

Log.e(TAG,"getBitmapFromDiskCache - "+ e);

}finally{

try{

if(inputStream !=null) {

inputStream.close();

}

}catch(IOException e) {}

}

}

returnnull;

}

}

/**

*

Clears both the memory and disk cache associated with

this ImageCache object. Note that

* this includes

disk access so this should not be executed on the main/UI

thread.

*/

publicvoidclearCache() {

clearMemoryCache();

synchronized(mDiskCacheLock)

{

mDiskCacheStarting =true;

if

(mDiskLruCache !=null&& !mDiskLruCache.isClosed()) {

try{

mDiskLruCache.delete();

}catch

(IOException e) {

Log.e(TAG,

"clearCache - "+ e);

}

mDiskLruCache =null;

initDiskCache();

}

}

}

publicvoid

clearMemoryCache(){

if(mMemoryCache !=null) {

mMemoryCache.evictAll();

}

}

/**

*

Flushes the disk cache associated with this ImageCache

object. Note that this includes

* disk access so this

should not be executed on the main/UI thread.

*/

publicvoidflush() {

synchronized

(mDiskCacheLock) {

if(mDiskLruCache !=null)

{

try{

mDiskLruCache.flush();

}catch

(IOException e) {

Log.e(TAG, "flush -

" + e);

}

}

}

}

/**

* Closes the disk cache associated with this

ImageCache object. Note that this includes

* disk

access so this should not be executed on the main/UI

thread.

*/

publicvoidclose() {

synchronized(mDiskCacheLock) {

if

(mDiskLruCache !=null) {

try{

if(!mDiskLruCache.isClosed()) {

mDiskLruCache.close();

mDiskLruCache =null;

}

}catch(IOException e) {

Log.e(TAG,

"close - "+ e);

}

}

}

}

/**

* A holder class that contains cache

parameters.

*/

publicstaticclass

ImageCacheParams {

publicintmemCacheSize =

DEFAULT_MEM_CACHE_SIZE;

publicintdiskCacheSize =

DEFAULT_DISK_CACHE_SIZE;

publicFile diskCacheDir;

publicCompressFormat compressFormat =

DEFAULT_COMPRESS_FORMAT;

publicint

compressQuality = DEFAULT_COMPRESS_QUALITY;

public

booleanmemoryCacheEnabled = DEFAULT_MEM_CACHE_ENABLED;

publicbooleandiskCacheEnabled =

DEFAULT_DISK_CACHE_ENABLED;

publicboolean

clearDiskCacheOnStart =

DEFAULT_CLEAR_DISK_CACHE_ON_START;

publicboolean

initDiskCacheOnCreate =

DEFAULT_INIT_DISK_CACHE_ON_CREATE;

public

ImageCacheParams(File diskCacheDir) {

this.diskCacheDir = diskCacheDir;

}

publicImageCacheParams(String diskCacheDir) {

this.diskCacheDir =newFile(diskCacheDir);

}

/**

* @param context棿

*/

public

voidsetMemCacheSizePercent(Context context,float

percent) {

if(percent <0.05f || percent >

0.8f) {

thrownew

IllegalArgumentException("setMemCacheSizePercent -

percent must be "

+ "between0.05

and0.8(inclusive)");

}

memCacheSize = Math.round(percent * getMemoryClass

(context) *1024*1024);

}

publicvoidsetMemCacheSize(intmemCacheSize) {

this.memCacheSize = memCacheSize;

}

publicvoidsetDiskCacheSize(intdiskCacheSize) {

this.diskCacheSize = diskCacheSize;

}

privatestaticintgetMemoryClass(Context

context) {

return((ActivityManager)

context.getSystemService(

Context.ACTIVITY_SERVICE)).getMemoryClass();

}

}

}

图像处理类

[java]view plaincopy

publicclassBitmapCommonUtils {

privatestaticfinalString TAG ="BitmapCommonUtils";

/**

* @param context

* @return

*/

publicstaticFile getDiskCacheDir(Context context, String uniqueName) {

finalString cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ?

getExternalCacheDir(context).getPath() : context.getCacheDir().getPath();

returnnewFile(cachePath + File.separator + uniqueName);

}

/**

* @param bitmap

* @return

*/

publicstaticintgetBitmapSize(Bitmap bitmap) {

returnbitmap.getRowBytes() * bitmap.getHeight();

}

/**

* @param context

* @return

*/

publicstaticFile getExternalCacheDir(Context context) {

finalString cacheDir ="/Android/data/"+ context.getPackageName() +"/cache/";

returnnewFile(Environment.getExternalStorageDirectory().getPath() + cacheDir);

}

/**

* @param path

* @return

*/

publicstaticlonggetUsableSpace(File path) {

try{

finalStatFs stats =newStatFs(path.getPath());

return(long) stats.getBlockSize() * (long) stats.getAvailableBlocks();

}catch(Exception e) {

e.printStackTrace();

return-1;

}

}

}

图像Decoder类

[java]view plaincopy

publicclassBitmapDecoder {

privatestaticfinalString TAG ="BitmapDecoder";

privateBitmapDecoder(){}

publicstaticBitmap decodeSampledBitmapFromResource(Resources res,intresId,intreqWidth,intreqHeight) {

finalBitmapFactory.Options options =newBitmapFactory.Options();

options.inJustDecodeBounds =true;

options.inPurgeable =true;

BitmapFactory.decodeResource(res, resId, options);

options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

options.inJustDecodeBounds =false;

try{

returnBitmapFactory.decodeResource(res, resId, options);

}catch(OutOfMemoryError e) {

e.printStackTrace();

returnnull;

}

}

publicstaticBitmap decodeSampledBitmapFromFile(String filename,intreqWidth,intreqHeight) {

finalBitmapFactory.Options options =newBitmapFactory.Options();

options.inJustDecodeBounds =true;

options.inPurgeable =true;

BitmapFactory.decodeFile(filename, options);

options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

options.inJustDecodeBounds =false;

try{

returnBitmapFactory.decodeFile(filename, options);

}catch(OutOfMemoryError e) {

e.printStackTrace();

returnnull;

}

}

publicstaticBitmap decodeSampledBitmapFromDescriptor(FileDescriptor fileDescriptor,intreqWidth,intreqHeight) {

finalBitmapFactory.Options options =newBitmapFactory.Options();

options.inJustDecodeBounds =true;

options.inPurgeable =true;

BitmapFactory.decodeFileDescriptor(fileDescriptor,null, options);

options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

options.inJustDecodeBounds =false;

try{

returnBitmapFactory.decodeFileDescriptor(fileDescriptor,null, options);

}catch(OutOfMemoryError e) {

// Log.e(TAG, "decodeSampledBitmapFromDescriptor");

e.printStackTrace();

returnnull;

}

}

publicstaticintcalculateInSampleSize(BitmapFactory.Options options,intreqWidth,intreqHeight) {

finalintheight = options.outHeight;

finalintwidth = options.outWidth;

intinSampleSize =1;

if(height > reqHeight || width > reqWidth) {

if(width > height) {

inSampleSize = Math.round((float) height / (float) reqHeight);

}else{

inSampleSize = Math.round((float) width / (float) reqWidth);

}

finalfloattotalPixels = width * height;

finalfloattotalReqPixelsCap = reqWidth * reqHeight *2;

while(totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {

inSampleSize++;

}

}

returninSampleSize;

}

}

图像显示配置类

[java]view plaincopy

publicclassBitmapDisplayConfig {

privateintbitmapWidth;

privateintbitmapHeight;

privateAnimation animation;

privateintanimationType;

privateBitmap loadingBitmap;

privateBitmap loadfailBitmap;

publicintgetBitmapWidth() {

returnbitmapWidth;

}

publicvoidsetBitmapWidth(intbitmapWidth) {

this.bitmapWidth = bitmapWidth;

}

publicintgetBitmapHeight() {

returnbitmapHeight;

}

publicvoidsetBitmapHeight(intbitmapHeight) {

this.bitmapHeight = bitmapHeight;

}

publicAnimation getAnimation() {

returnanimation;

}

publicvoidsetAnimation(Animation animation) {

this.animation = animation;

}

publicintgetAnimationType() {

returnanimationType;

}

publicvoidsetAnimationType(intanimationType) {

this.animationType = animationType;

}

publicBitmap getLoadingBitmap() {

returnloadingBitmap;

}

publicvoidsetLoadingBitmap(Bitmap loadingBitmap) {

this.loadingBitmap = loadingBitmap;

}

publicBitmap getLoadfailBitmap() {

returnloadfailBitmap;

}

publicvoidsetLoadfailBitmap(Bitmap loadfailBitmap) {

this.loadfailBitmap = loadfailBitmap;

}

publicclassAnimationType{

publicstaticfinalintuserDefined =0;

publicstaticfinalintfadeIn =1;

}

}

图像流读取类

[java]view plaincopy

publicclassBitmapProcess {

privatestaticfinalString TAG ="BitmapProcess";

privatebooleanmHttpDiskCacheStarting =true;

privateintcacheSize;

privatestaticfinalintDEFAULT_CACHE_SIZE =20*1024*1024;// 20MB

privateLruDiskCache mOriginalDiskCache;

privatefinalObject mHttpDiskCacheLock =newObject();

privatestaticfinalintDISK_CACHE_INDEX =0;

privateFile mOriginalCacheDir;

privateDownloader downloader;

privatebooleanneverCalculate =false;

publicBitmapProcess(Downloader downloader,String filePath,intcacheSize) {

this.mOriginalCacheDir =newFile(filePath+"/original");

this.downloader = downloader;

if(cacheSize<=0)

cacheSize = DEFAULT_CACHE_SIZE;

this.cacheSize = cacheSize;

}

publicvoidconfigCalculateBitmap(booleanneverCalculate){

this.neverCalculate = neverCalculate;

}

publicBitmap processBitmap(String data, BitmapDisplayConfig config) {

finalString key = FileNameGenerator.generator(data);

FileDescriptor fileDescriptor =null;

FileInputStream fileInputStream =null;

LruDiskCache.Snapshot snapshot;

synchronized(mHttpDiskCacheLock) {

// Wait for disk cache to initialize

while(mHttpDiskCacheStarting) {

try{

mHttpDiskCacheLock.wait();

}catch(InterruptedException e) {

}

}

if(mOriginalDiskCache !=null) {

try{

snapshot = mOriginalDiskCache.get(key);

if(snapshot ==null) {

LruDiskCache.Editor editor = mOriginalDiskCache.edit(key);

if(editor !=null) {

if(downloader.downloadToLocalStreamByUrl(data,editor.newOutputStream(DISK_CACHE_INDEX))) {

editor.commit();

}else{

editor.abort();

}

}

snapshot = mOriginalDiskCache.get(key);

}

if(snapshot !=null) {

fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);

fileDescriptor = fileInputStream.getFD();

}

}catch(IOException e) {

Log.e(TAG,"processBitmap - "+ e);

}catch(IllegalStateException e) {

Log.e(TAG,"processBitmap - "+ e);

}finally{

if(fileDescriptor ==null&& fileInputStream !=null) {

try{

fileInputStream.close();

}catch(IOException e) {

}

}

}

}

}

Bitmap bitmap =null;

if(fileDescriptor !=null) {

if(neverCalculate)

bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);

else

bitmap = BitmapDecoder.decodeSampledBitmapFromDescriptor(fileDescriptor, config.getBitmapWidth(),config.getBitmapHeight());

}

if(fileInputStream !=null) {

try{

fileInputStream.close();

}catch(IOException e) {

}

}

returnbitmap;

}

publicvoidinitHttpDiskCache() {

if(!mOriginalCacheDir.exists()) {

mOriginalCacheDir.mkdirs();

}

synchronized(mHttpDiskCacheLock) {

if(BitmapCommonUtils.getUsableSpace(mOriginalCacheDir) > cacheSize) {

try{

mOriginalDiskCache = LruDiskCache.open(mOriginalCacheDir,1,1,cacheSize);

}catch(IOException e) {

mOriginalDiskCache =null;

}

}

mHttpDiskCacheStarting =false;

mHttpDiskCacheLock.notifyAll();

}

}

publicvoidclearCacheInternal() {

synchronized(mHttpDiskCacheLock) {

if(mOriginalDiskCache !=null&& !mOriginalDiskCache.isClosed()) {

try{

mOriginalDiskCache.delete();

}catch(IOException e) {

Log.e(TAG,"clearCacheInternal - "+ e);

}

mOriginalDiskCache =null;

mHttpDiskCacheStarting =true;

initHttpDiskCache();

}

}

}

publicvoidflushCacheInternal() {

synchronized(mHttpDiskCacheLock) {

if(mOriginalDiskCache !=null) {

try{

mOriginalDiskCache.flush();

}catch(IOException e) {

Log.e(TAG,"flush - "+ e);

}

}

}

}

publicvoidcloseCacheInternal() {

synchronized(mHttpDiskCacheLock) {

if(mOriginalDiskCache !=null) {

try{

if(!mOriginalDiskCache.isClosed()) {

mOriginalDiskCache.close();

mOriginalDiskCache =null;

}

}catch(IOException e) {

Log.e(TAG,"closeCacheInternal - "+ e);

}

}

}

}

}

下载类

[java]view plaincopy

publicinterfaceDownloader  {

publicbooleandownloadToLocalStreamByUrl(String urlString, OutputStream outputStream);

}

[java]view plaincopy

publicclassSimpleHttpDownloaderimplementsDownloader{

privatestaticfinalString TAG ="BitmapDownloader";

privatestaticfinalintIO_BUFFER_SIZE =8*1024;//8k

publicbooleandownloadToLocalStreamByUrl(String urlString, OutputStream outputStream) {

HttpURLConnection urlConnection =null;

BufferedOutputStream out =null;

FlushedInputStream in =null;

try{

finalURL url =newURL(urlString);

urlConnection = (HttpURLConnection) url.openConnection();

in =newFlushedInputStream(newBufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE));

out =newBufferedOutputStream(outputStream, IO_BUFFER_SIZE);

intb;

while((b = in.read()) != -1) {

out.write(b);

}

returntrue;

}catch(finalIOException e) {

Log.e(TAG,"Error in downloadBitmap - "+urlString +" : "+ e);

}finally{

if(urlConnection !=null) {

urlConnection.disconnect();

}

try{

if(out !=null) {

out.close();

}

if(in !=null) {

in.close();

}

}catch(finalIOException e) {}

}

returnfalse;

}

publicclassFlushedInputStreamextendsFilterInputStream {

publicFlushedInputStream(InputStream inputStream) {

super(inputStream);

}

@Override

publiclongskip(longn)throwsIOException {

longtotalBytesSkipped = 0L;

while(totalBytesSkipped < n) {

longbytesSkipped = in.skip(n - totalBytesSkipped);

if(bytesSkipped == 0L) {

intby_te = read();

if(by_te <0) {

break;// we reached EOF

}else{

bytesSkipped =1;// we read one byte

}

}

totalBytesSkipped += bytesSkipped;

}

returntotalBytesSkipped;

}

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容