常用工具类

来源:互联网 发布:域名那家继费便宜 编辑:程序博客网 时间:2024/04/19 19:27


出自 http://blog.csdn.net/krislight/article/details/11354119

首先Activity的抽象类 BaseActivity

[java] view plaincopy
  1. /** 
  2.  * Activity 基類 
  3.  * @author KrisLight 
  4.  * 
  5.  */  
  6. public abstract class BaseActivity extends Activity {  
  7.       
  8.     private static final String TAG = BaseActivity.class.getSimpleName();   
  9.     /** 
  10.      * 消息類型默認Default 
  11.      */  
  12.     public static int MSGTYPE_DEFAULT = 0;  
  13.     /** 
  14.      * 消息類型為Info 
  15.      */  
  16.     public static int MSGTYPE_INFO = 1;  
  17.     /** 
  18.      * 消息類型為Warning 
  19.      */  
  20.     public static int MSGTYPE_WARNING = 2;  
  21.     /** 
  22.      * 消息類型為Error 
  23.      */  
  24.     public static int MSGTYPE_ERROR = 3;  
  25.       
  26.   
  27.     @Override  
  28.     protected void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.     }  
  31.       
  32.     /**初始化**/  
  33.     protected abstract void init();  
  34.       
  35.     /** 初始化監聽器**/  
  36.     protected abstract void initListener();  
  37.       
  38.     /**  得到字符串資源 **/  
  39.     public String getResStr(int id)  
  40.     {  
  41.         return this.getResources().getString(id);  
  42.     }  
  43.   
  44.     /** 短暂显示Toast提示(来自res) **/  
  45.     protected void showShortToast(int resId) {  
  46.         Toast.makeText(this, getString(resId), Toast.LENGTH_SHORT).show();  
  47.     }  
  48.   
  49.     /** 短暂显示Toast提示(来自String) **/  
  50.     protected void showShortToast(String text) {  
  51.         Toast.makeText(this, text, Toast.LENGTH_SHORT).show();  
  52.     }  
  53.   
  54.     /** 长时间显示Toast提示(来自res) **/  
  55.     protected void showLongToast(int resId) {  
  56.         Toast.makeText(this, getString(resId), Toast.LENGTH_LONG).show();  
  57.     }  
  58.   
  59.     /** 长时间显示Toast提示(来自String) **/  
  60.     protected void showLongToast(String text) {  
  61.         Toast.makeText(this, text, Toast.LENGTH_LONG).show();  
  62.     }  
  63.   
  64.     /** Debug输出Log日志 **/  
  65.     protected void showLogDebug(String tag, String msg) {  
  66.         Log.d(tag, msg);  
  67.     }  
  68.   
  69.     /** Error输出Log日志 **/  
  70.     protected void showLogError(String tag, String msg) {  
  71.         Log.e(tag, msg);  
  72.     }  
  73.   
  74.     /** 通过Class跳转界面 **/  
  75.     protected void startActivity(Class<?> cls) {  
  76.         startActivity(cls, null);  
  77.     }  
  78.   
  79.     /** 含有Bundle通过Class跳转界面 **/  
  80.     protected void startActivity(Class<?> cls, Bundle bundle) {  
  81.         Intent intent = new Intent();  
  82.         intent.setClass(this, cls);  
  83.         if (bundle != null) {  
  84.             intent.putExtras(bundle);  
  85.         }  
  86.         if(intent.resolveActivity(getPackageManager()) != null){  
  87.             startActivity(intent);  
  88.         }else{  
  89.             showLogError(TAG, "there is no activity can handle this intent: "+intent.getAction().toString());  
  90.         }  
  91.         overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);  
  92.     }  
  93.   
  94.     /** 通过Action跳转界面 **/  
  95.     protected void startActivity(String action) {  
  96.         Intent intent = new Intent();  
  97.         intent.setAction(action);  
  98.         if(intent.resolveActivity(getPackageManager()) != null){  
  99.             startActivity(intent);  
  100.         }else{  
  101.             showLogError(TAG, "there is no activity can handle this intent: "+intent.getAction().toString());  
  102.         }  
  103.     }  
  104.       
  105.     /**含有Date通过Action跳转界面**/  
  106.     protected void startActivity(String action,Uri data) {  
  107.         Intent intent = new Intent();  
  108.         intent.setAction(action);  
  109.         intent.setData(data);  
  110.         if(intent.resolveActivity(getPackageManager()) != null){  
  111.             startActivity(intent);  
  112.         }else{  
  113.             showLogError(TAG, "there is no activity can handle this intent: "+intent.getAction().toString());  
  114.         }  
  115.     }  
  116.   
  117.     /** 含有Bundle通过Action跳转界面 **/  
  118.     protected void startActivity(String action, Bundle bundle) {  
  119.         Intent intent = new Intent();  
  120.         intent.setAction(action);  
  121.         if (bundle != null) {  
  122.             intent.putExtras(bundle);  
  123.         }  
  124.         if(intent.resolveActivity(getPackageManager()) != null){  
  125.             startActivity(intent);  
  126.         }else{  
  127.             showLogError(TAG, "there is no activity can handle this intent: "+intent.getAction().toString());  
  128.         }  
  129.         overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);  
  130.     }  
  131.   
  132.   
  133.     /** 含有标题、内容、两个按钮的对话框 **/  
  134.     protected void showAlertDialog(String title, String message,  
  135.             String positiveText,  
  136.             DialogInterface.OnClickListener onPositiveClickListener,  
  137.             String negativeText,  
  138.             DialogInterface.OnClickListener onNegativeClickListener) {  
  139.             AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle(title)  
  140.                 .setMessage(message)  
  141.                 .setPositiveButton(positiveText, onPositiveClickListener)  
  142.                 .setNegativeButton(negativeText, onNegativeClickListener).create();  
  143.             alertDialog.show();  
  144.     }  
  145.   
  146.     /** 含有标题、内容、图标、两个按钮的对话框 **/  
  147.     protected void showAlertDialog(String title, String message,  
  148.             int icon, String positiveText,  
  149.             DialogInterface.OnClickListener onPositiveClickListener,  
  150.             String negativeText,  
  151.             DialogInterface.OnClickListener onNegativeClickListener) {  
  152.         AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle(title)  
  153.                 .setMessage(message).setIcon(icon)  
  154.                 .setPositiveButton(positiveText, onPositiveClickListener)  
  155.                 .setNegativeButton(negativeText, onNegativeClickListener).create();  
  156.         alertDialog.show();  
  157.     }  
  158.       
  159.       
  160.     /** 
  161.      *  
  162.      * @Function: com.light.mycal.base.BaseActivity 
  163.      * @Description:根據不同的信息類型彈出不同等級的對話框 
  164.      * 
  165.      * @param i  資源id 
  166.      * @param iMsgType 信息類型 
  167.      * 
  168.      * @version:v1.0 
  169.      * @author:KrisLight 
  170.      * @date:2013/9/4 下午4:56:39 
  171.      * 
  172.      * Modification History: 
  173.      * Date         Author      Version     Description 
  174.      * ----------------------------------------------------------------- 
  175.      * 2013/9/4    KrisLight      v1.0.0         create 
  176.      */  
  177.     public void ShowMsgResStr(int i, int iMsgType)  
  178.     {  
  179.         String sTitle = getResStr(R.string.app_name);  
  180.         int iconId = 0;  
  181.         if (iMsgType == MSGTYPE_INFO)  
  182.         {  
  183.             sTitle = getResStr(R.string.msgTypeInfo);  
  184.             iconId = R.drawable.msgicon_info;  
  185.         }  
  186.         if (iMsgType == MSGTYPE_WARNING)  
  187.         {  
  188.             sTitle = getResStr(R.string.msgTypeWarning);  
  189.             iconId = R.drawable.msgicon_warning;  
  190.         }  
  191.         if (iMsgType == MSGTYPE_ERROR)  
  192.         {  
  193.             sTitle = getResStr(R.string.msgTypeError);  
  194.             iconId = R.drawable.msgicon_error;  
  195.         }                     
  196.         AlertDialog.Builder dlg = new AlertDialog.Builder(this);          
  197.         dlg.setMessage(getResStr(i));  
  198.         dlg.setPositiveButton(getResStr(R.string.msgBoxButtonOk), null);          
  199.         dlg.setTitle(sTitle);         
  200.         dlg.setIcon(iconId);          
  201.         dlg.create();  
  202.         dlg.show();  
  203.     }  
  204.   
  205.     /** 带有右进右出动画的退出 **/  
  206.     public void finish() {  
  207.         super.finish();  
  208.         overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);  
  209.     }  
  210.   
  211.     /** 默认退出 **/  
  212.     protected void defaultFinish() {  
  213.         super.finish();  
  214.     }  
  215. }  


配置文件工具Prefs

[java] view plaincopy
  1. public class Prefs {  
  2.       
  3.     /** Friend+'s Preference file name */  
  4.     public static final String PREF_FILE = "friends_plus_pref";  
  5.       
  6.     /** Preference key[authToken] */  
  7.     public static final String KEY_AUTH_TOKEN = "auth_token";  
  8.       
  9.     /** Preference key[clientId] */  
  10.     public static final String KEY_CLIENT_ID = "client_id";  
  11.       
  12.     /** Preference key[login_email] */  
  13.     public static final String KEY_LOGIN_EMAIL = "login_email";  
  14.       
  15.     /** Preference key[login_IMId] */  
  16.     public static final String KEY_LOGIN_IMID = "login_imid";  
  17.       
  18.     /** Preference key[login_name] */  
  19.     public static final String KEY_LOGIN_NAME = "login_name";  
  20.       
  21.     /** Preference key[last_update_contact_list] */  
  22.     public static final String KEY_LAST_UPDATE_CONTACT_LIST = "last_update_contact_list";  
  23.       
  24.     public static final String KEY_REGISTRATION_STEP = "registration_step";  
  25.       
  26.     public static final String REGISTRATION_STEP_AUTHENTICATE = "authenticate";  
  27.     public static final String KEY_REGISTRATION_AUTHEN_CODE = "authen_code";  
  28.       
  29.     /** 
  30.      * get the app's preference data 
  31.      *  
  32.      * @param context 
  33.      * @param prefKey preference key 
  34.      * @return 
  35.      */  
  36.     public static String getPreference(Context context, String prefKey) {  
  37.         return getPreference(context, prefKey, "");  
  38.     }  
  39.       
  40.     /** 
  41.      * get the app's preference data 
  42.      *  
  43.      * @param context 
  44.      * @param prefKey preference key 
  45.      * @param defVal default value 
  46.      * @return 
  47.      */  
  48.     public static String getPreference(Context context, String prefKey, String defVal) {  
  49.         if (TextUtils.isEmpty(prefKey))  
  50.             return null;  
  51.   
  52.         SharedPreferences prefs =   
  53.                 context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);  
  54.         return prefs.getString(prefKey, defVal);  
  55.     }  
  56.   
  57.     /** 
  58.      * write data to app's preference 
  59.      *  
  60.      * @param context 
  61.      * @param prefKey 
  62.      * @param prefValue 
  63.      */  
  64.     public static void savePreference(Context context, String prefKey, String prefValue) {  
  65.         if (TextUtils.isEmpty(prefKey))  
  66.             return;  
  67.         SharedPreferences.Editor editor =   
  68.                 context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit();  
  69.         editor.putString(prefKey, prefValue).commit();  
  70.     }  
  71.       
  72.     /** 
  73.      * remove preference value from app's preference file 
  74.      * @param context 
  75.      * @param prefKey 
  76.      */  
  77.     public static void removePreference(Context context, String prefKey){  
  78.         if (TextUtils.isEmpty(prefKey))  
  79.             return;  
  80.         SharedPreferences.Editor editor =  
  81.                 context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit();  
  82.         editor.remove(prefKey).commit();  
  83.     }  
  84.       
  85. }  

DBHelper类

[java] view plaincopy
  1. /** 
  2.  * DB工具類 
  3.  * @author KrisLight 
  4.  * 
  5.  */  
  6. public class DatabaseOpenHelper extends SQLiteOpenHelper  
  7. {  
  8.       
  9.     private static final String TAG = DatabaseOpenHelper.class.getSimpleName();  
  10.     /** 數據庫操作結果 **/  
  11.     public enum Result  
  12.     {  
  13.         /** 成功 **/  
  14.         Success,  
  15.         /**未知錯誤**/  
  16.         errUnknown,  
  17.         /**無法插入新數據**/  
  18.         errCantInsertNewData,   
  19.         /**無法更新數據**/  
  20.         errCantUpdateData,   
  21.         /**無法創建Table**/  
  22.         errCantCreateTable,   
  23.         /**無法訪問數據庫**/  
  24.         errNoDbAccess,  
  25.         /**無法從表中獲取數據**/  
  26.         errCantGetDataFromTable,      
  27.         /**無法查到數據**/  
  28.         errCantFindData,  
  29.         /**無法得到數據**/  
  30.         errCantGetData,   
  31.         /**無法刪除數據**/  
  32.         errCantDeleteData,  
  33.         /**表不存在**/  
  34.         errTableNotExists,  
  35.         /**不能為該字段指定值**/  
  36.         errCantSetValuesForDataRow,  
  37.         /**不能從該字段得到值**/  
  38.         errCantGetValuesFromDataRow,  
  39.     };  
  40.           
  41.     /** 表名 **/  
  42.     public static final String TABLE_NAME = "appointments";  
  43.     /** 臨時表名 **/  
  44.     public static final String TEMP_TABLE_NAME = "tempDb";  
  45.     
  46.     /** 數據庫名 **/  
  47.     private static final String DB_NAME = "MyCal.db";  
  48.     private SQLiteDatabase db = null;  
  49.     /** 版本号 **/  
  50.     private static final int DB_VERSION = 1;  
  51.     /**創建Table的結果**/  
  52.     private Result resultDbTablesCreated = Result.errUnknown;     
  53.       
  54.     public DatabaseOpenHelper(Context context, String name, CursorFactory factory,  
  55.             int version) {  
  56.         super(context, DB_NAME, factory, DB_VERSION);  
  57.     }  
  58.       
  59.     @Override  
  60.     public void onCreate(SQLiteDatabase sqLiteDatabase) {  
  61.         DataRow nDataRow = new NoteDataRow();  
  62.         String create_sql = getSqlTableDefinition(nDataRow.GetTableName(), nDataRow.GetTableDef());  
  63.         Log.d(TAG, "create_sql: ---------------------"+create_sql+ "------------");  
  64.         try{  
  65.           sqLiteDatabase.execSQL(create_sql);  
  66.           resultDbTablesCreated = DatabaseOpenHelper.Result.Success;                  
  67.         }catch (Exception e) {  
  68.           resultDbTablesCreated = DatabaseOpenHelper.Result.errCantCreateTable;   
  69.         }  
  70.           
  71.     }  
  72.       
  73.     /** 
  74.      * 得到創建表的SQL語句 
  75.      * @param sTableName 表名 
  76.      * @param vecTableDef 表的字段數組 
  77.      * @return 
  78.      */  
  79.     public String getSqlTableDefinition(String sTableName, DataField[] vecTableDef)  
  80.     {  
  81.         String def = "CREATE TABLE " + sTableName + " (";  
  82.         for (int i = 0; i < vecTableDef.length; i++)  
  83.         {  
  84.             def += vecTableDef[i].GetColumnDefinition();  
  85.             if (i < (vecTableDef.length - 1))  
  86.                 //中間逗號分隔  
  87.                 def += ", ";  
  88.         }     
  89.         def += ")";  
  90.         return def;  
  91.     }  
  92.       
  93.       
  94.     /* (non-Javadoc) 
  95.      * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int) 
  96.      */  
  97.     @Override  
  98.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  99.         switch (newVersion) {  
  100.           case 2:  
  101.             /** only add column on old table**/  
  102. //          String add_column_sql = getSqlTableAddColumn(TABLE_NAME,newColumn);  
  103. //          Log.d(TAG, "add_column_sql:--------------"+add_column_sql+"----------");  
  104. //          db.execSQL(add_column_sql);  
  105. //          break;  
  106.           case 3:  
  107.               //原來的字段集合  
  108.               List<String> columns = getColumns(db, TABLE_NAME);  
  109.               String rename_sql = getSqlTableRename(TABLE_NAME);  
  110.               Log.d(TAG, "rename_sql:--------------"+rename_sql+"----------");  
  111.               //重命名  
  112.               db.execSQL(rename_sql);  
  113.               //創建新表  
  114.               onCreate(db);  
  115.               //舊字段和新的字段求交集  
  116.               columns.retainAll(getColumns(db, TABLE_NAME));  
  117.               String cols = Utils.join(columns, ",");  
  118.               //將舊的數據插入到新表   
  119.               db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s from temp_%s", TABLE_NAME, cols, cols, TABLE_NAME));  
  120.               String drop_sql = getSqlTableDrop(TEMP_TABLE_NAME);  
  121.               Log.d(TAG, "drop_sql:--------------"+drop_sql+"----------");  
  122.               db.execSQL(drop_sql);  
  123.             break;  
  124.           default:  
  125.               String ds = getSqlTableDrop(TABLE_NAME);  
  126.               Log.d(TAG, "drop_sql:--------------"+ds+"----------");  
  127.             break;  
  128.         }  
  129.             
  130.   
  131.     }  
  132.       
  133.     /** 
  134.      *  得到重命名SQL 
  135.      */  
  136.     private String getSqlTableRename(String tableName){  
  137.           StringBuffer sb = new StringBuffer();  
  138.           sb.append("ALTER TABLE ");  
  139.           sb.append(tableName);  
  140.           sb.append(" RENAME TO temp_");  
  141.           sb.append(tableName);  
  142.           return sb.toString();  
  143.     }  
  144.       
  145.     /** 
  146.      *  得到刪除表SQL 
  147.      */  
  148.     private String getSqlTableDrop(String tableName){  
  149.           StringBuffer sb = new StringBuffer();  
  150.           sb.append("DROP TABLE IF EXISTS ");  
  151.           sb.append(tableName);  
  152.           return sb.toString();  
  153.     }  
  154.       
  155.     /** 
  156.      *  得到新增字段的表SQL 
  157.      */  
  158.     private String getSqlTableAddColumn(String tableName,String columnName){  
  159.           StringBuffer sb = new StringBuffer();  
  160.           sb.append("ALTER TABLE ");  
  161.           sb.append(tableName);  
  162.           sb.append(" ADD COLUMN ");  
  163.           sb.append(columnName);  
  164.           return sb.toString();  
  165.     }  
  166.       
  167.     /** 
  168.      *  得到這個Table中的所有字段組成的List集合 
  169.      */  
  170.     public static List<String> getColumns(SQLiteDatabase db, String tableName) {  
  171.         List<String> ar = null;  
  172.         Cursor c = null;  
  173.         try {  
  174.             //查一條數據得到所有字段  
  175.             c = db.rawQuery("select * from " + tableName + " limit 1"null);  
  176.             if (c != null) {  
  177.                 ar = new ArrayList<String>(Arrays.asList(c.getColumnNames()));  
  178.             }  
  179.         } catch (Exception e) {  
  180.             e.printStackTrace();  
  181.         } finally {  
  182.             if (c != null)  
  183.                 c.close();  
  184.         }  
  185.         return ar;  
  186.     }  
  187.   
  188.       
  189.     /** 
  190.      *  得到數據庫的名字 
  191.      *  
  192.      */  
  193.     public final String getName()  
  194.     {  
  195.         return DB_NAME;  
  196.     }  
  197.   
  198.     /** 得到錯誤信息描述 **/  
  199.     public static int getErrDesc(Result result)  
  200.     {  
  201.         int msgId = R.string.errUnknown;  
  202.         if (result == Result.errCantInsertNewData)  
  203.             msgId = R.string.errCantInsertNewData;  
  204.         if (result == Result.errCantUpdateData)  
  205.             msgId = R.string.errCantUpdateData;  
  206.         if (result == Result.errCantCreateTable)  
  207.             msgId = R.string.errCantCreateTable;  
  208.         if (result == Result.errNoDbAccess)  
  209.             msgId = R.string.errNoDbAccess;  
  210.         if (result == Result.errCantGetDataFromTable)  
  211.             msgId = R.string.errCantGetDataFromTable;  
  212.         if (result == Result.errCantFindData)  
  213.             msgId = R.string.errCantFindData;  
  214.         if (result == Result.errCantGetData)  
  215.             msgId = R.string.errCantGetData;  
  216.         if (result == Result.errCantDeleteData)  
  217.             msgId = R.string.errCantDeleteData;  
  218.         if (result == Result.errTableNotExists)  
  219.             msgId = R.string.errTableNotExists;  
  220.         if (result == Result.errCantSetValuesForDataRow)  
  221.             msgId = R.string.errCantSetValuesForDataRow;  
  222.         if (result == Result.errCantGetValuesFromDataRow)  
  223.             msgId = R.string.errCantGetValuesFromDataRow;                     
  224.         return msgId;  
  225.     }  
  226.           
  227.     /**關閉DB**/  
  228.     public void close()  
  229.     {  
  230.         if (isOpened())  
  231.             db.close();  
  232.     }  
  233.       
  234.     /**判斷DB是否打開**/  
  235.     public boolean isOpened()  
  236.     {  
  237.         if (db != null)  
  238.             return true;  
  239.         return false;  
  240.     }  
  241.       
  242.     /**得到DB寫操作類 **/  
  243.     public SQLiteDatabase getWriteSQLiteDb()  
  244.     {  
  245.         return getWritableDatabase();  
  246.     }  
  247.       
  248.     /**得到DB讀操作類 **/  
  249.     public SQLiteDatabase getReadSQLiteDb()  
  250.     {  
  251.         return getReadableDatabase();  
  252.     }  
  253.       
  254.     /**查詢Table是否存在**/  
  255.     public boolean isTableExists(String sTableName)  
  256.     {  
  257.         boolean bResult = false;  
  258.         if (isOpened())  
  259.         {  
  260.             String sql = "select name from sqlite_master where type = 'table' and name = '%s'";       
  261.             sql = String.format(sql, sTableName);             
  262.             Cursor cr = db.rawQuery(sql, null);                       
  263.             if (cr.getCount() > 0)  
  264.                 bResult = true;  
  265.             cr.close();  
  266.         }  
  267.         return bResult;  
  268.     }  
  269.       
  270.       
  271.     /** 建表是否成功 **/  
  272.     public boolean TablesCreated()  
  273.     {  
  274.         return resultDbTablesCreated == Result.Success;       
  275.     }  
  276.   
  277.     /** 判斷DB是否準備好了**/  
  278.     public synchronized boolean DatabaseReady()  
  279.     {  
  280.         return (isOpened() && TablesCreated());  
  281.     }  
  282.       
  283.     /** 返回創建表的結果 是成功還是失敗 **/  
  284.     public Result TablesCreationResult()  
  285.     {  
  286.         return resultDbTablesCreated;                 
  287.     }  
  288.   
  289.               
  290. }  

表中字段类DataField

[java] view plaincopy
  1. /** 
  2.  *  表中的字段類 
  3.  * @author KrisLight 
  4.  */  
  5. public class DataField  
  6. {  
  7.     //types   
  8.     /** Type枚举 如:INT,TEXT,BOOL**/  
  9.     public static enum Type { INT, TEXT, BOOL };  
  10.   
  11.     //fields   
  12.     /** Calendar實例 **/  
  13.     private Calendar dateOut = Calendar.getInstance();  
  14.       
  15.     //fields   
  16.     /** 對應的數據類型 **/  
  17.     private DataRow dataRow = null;  
  18.     /** 對應字段的值 **/  
  19.     private ContentValues values = null;  
  20.       
  21.     //fields  
  22.     /**字段索引**/  
  23.     private int index = 0;  
  24.     /** ContentValues存放鍵值對的鍵值 **/  
  25.     private String sName = "";  
  26.     /** 字段类型 从Type枚举中取一个类型的值 默認為Int **/  
  27.     private Type FieldType = Type.INT;  
  28.     /**是否可以為空**/  
  29.     private boolean bCanBeNull = true;  
  30.     /**是否是主鍵**/  
  31.     private boolean bPrimaryKey = false;  
  32.       
  33.       
  34.     //methods  
  35.     /** 
  36.      * 构造方法  
  37.      * @param index 索引 
  38.      * @param sName 字段名 
  39.      * @param FieldType 字段类型 
  40.      * @param bCanBeNull 是否为空 
  41.      * @param bPrimaryKey 是否为主键 
  42.      */  
  43.     public DataField(int index, String sName, Type FieldType, boolean bCanBeNull, boolean bPrimaryKey)  
  44.     {  
  45.         this.index = index;  
  46.         this.sName = sName;  
  47.         this.FieldType = FieldType;  
  48.         this.bCanBeNull = bCanBeNull;  
  49.         this.bPrimaryKey = bPrimaryKey;  
  50.     }  
  51.       
  52.     /** 
  53.      * 得到每一個字段描述 形如: "name int PRIMARY KEY Not Null" 
  54.      * @return 
  55.      */  
  56.     public String GetColumnDefinition()  
  57.     {  
  58.         String s = sName + " " + GetSqlType(FieldType);  
  59.         if (bPrimaryKey)  
  60.             s += " PRIMARY KEY";  
  61.         if (!bCanBeNull)  
  62.             s += " NOT NULL";  
  63.         return s;  
  64.     }  
  65.       
  66.     public Type GetType()  
  67.     {  
  68.         return FieldType;  
  69.     }  
  70.       
  71.     public int GetIndex()  
  72.     {  
  73.         return index;  
  74.     }  
  75.       
  76.     /** 根據SqlType返回真實的類型字段 注意BOOL對應的是Integer 其他類型的用Text **/  
  77.     public String GetSqlType(Type value)  
  78.     {  
  79.         switch (value)  
  80.         {  
  81.             case INT: return "INTEGER";  
  82.             case TEXT: return "TEXT";  
  83.             case BOOL: return "INTEGER";  
  84.         }  
  85.         return "TEXT";  
  86.     }  
  87.       
  88.     /** 设置这个字段对应的数据类型 **/  
  89.     public void SetParentRow(DataRow dataRow)  
  90.     {  
  91.         this.dataRow = dataRow;  
  92.         this.values = this.dataRow.GetContentValues();  
  93.     }  
  94.       
  95.     /** 得到字段的名字 **/  
  96.     public String GetName()  
  97.     {  
  98.         return sName;  
  99.     }  
  100.       
  101.     //getters  
  102.     /** 字符串类型的字段的值 **/  
  103.     public String asString()  
  104.     {  
  105.         return values.getAsString(sName);  
  106.     }  
  107.       
  108.     /** Long类型的字段的值 **/  
  109.     public long asLong()  
  110.     {  
  111.         return values.getAsLong(sName);  
  112.     }  
  113.       
  114.     /** Boolean类型的字段的值 **/  
  115.     public boolean asBoolean()  
  116.     {  
  117.         return (values.getAsLong(sName) == 1);  
  118.     }  
  119.       
  120.     /** 判断是否为Null **/  
  121.     public boolean isNull()  
  122.     {  
  123.         return (values.get(sName) == null);       
  124.     }  
  125.       
  126.     /** 将Long类型的日期类型转换成标准的日期时间 **/  
  127.     public Calendar asCalendar()  
  128.     {  
  129.         dateOut.setTimeInMillis(values.getAsLong(sName));  
  130.         return dateOut;   
  131.     }  
  132.   
  133.     //setters  
  134.     /** 设置字符串值 **/  
  135.     public void set(String value)  
  136.     {     
  137.         values.put(sName, value);  
  138.     }  
  139.       
  140.     /** 设置整型值 **/  
  141.     public void set(long value)  
  142.     {         
  143.         values.put(sName, value);  
  144.     }     
  145.   
  146.     /** 设置布尔值 **/  
  147.     public void set(boolean value)  
  148.     {  
  149.         int i = (value)?1:0;  
  150.         values.put(sName, i);         
  151.     }     
  152.   
  153.     /** 设置日期值 **/  
  154.     public void set(Calendar value)  
  155.     {  
  156.         values.put(sName, value.getTimeInMillis());  
  157.     }  
  158.   
  159.     /** 设置Null值 **/  
  160.     public void setNull()  
  161.     {  
  162.         values.put(sName, (String)null);  
  163.     }  
  164.       
  165. }  

数据原型类DataRow

[java] view plaincopy
  1. /** 
  2.  * 抽象的数据类型类, 
  3.  * 所有的数据原型都要继承这个类 
  4.  * @author KrisLight 
  5.  * 
  6.  */  
  7. public abstract class DataRow  
  8. {  
  9.     /** 这个类型对应表中的字段集合 **/  
  10.     private DataField[] vecTableDef = null;  
  11.     /** 这个类型对应表中的字段的值 用ContentValues形式存放 **/  
  12.     private ContentValues values = new ContentValues();  
  13.     /** 構造方法 **/  
  14.     public DataRow(){}  
  15.           
  16.     /** 
  17.      * 設置字段集合并綁定 
  18.      * @param vecTableDef 字段集合 
  19.      */  
  20.     public void SetTableDefinition(DataField[] vecTableDef)  
  21.     {  
  22.         this.vecTableDef = vecTableDef;       
  23.         UpdateDataFieldsParentRow(this);  
  24.     }  
  25.       
  26.     /** 將數據類型綁定其對應的所有字段 **/  
  27.     public void UpdateDataFieldsParentRow(DataRow row)  
  28.     {  
  29.         for (int i = 0; i < vecTableDef.length; i++)  
  30.             vecTableDef[i].SetParentRow(row);  
  31.     }  
  32.       
  33.     /** 拷貝另一個DataRow中的所有字段 **/  
  34.     public void CopyTableDefinition(DataRow data)  
  35.     {         
  36.         SetTableDefinition(data.vecTableDef);         
  37.     }  
  38.       
  39.     /** 得到表中的所有字段 **/  
  40.     public DataField[] GetTableDef()  
  41.     {  
  42.         return vecTableDef;  
  43.     }  
  44.       
  45.     /** 驗證方法 **/  
  46.     public boolean Validate()  
  47.     {  
  48.         return false;  
  49.     }  
  50.       
  51.     /** 清空ContentValues **/  
  52.     public void ClearContentValues()  
  53.     {  
  54.         values.clear();  
  55.     }  
  56.       
  57.     /** 得到ContentValues **/  
  58.     public ContentValues GetContentValues()  
  59.     {  
  60.         return values;  
  61.     }  
  62.   
  63.     /** 設置ContentValues **/  
  64.     public void SetContentValues(ContentValues values)  
  65.     {  
  66.         this.values = values;  
  67.         UpdateDataFieldsParentRow(this);  
  68.     }  
  69.       
  70.     /** 拷貝ContentValues **/  
  71.     public boolean CopyContentValues(ContentValues values)  
  72.     {  
  73.         this.values = values;  
  74.         UpdateDataFieldsParentRow(this);  
  75.         try  
  76.         {  
  77.             GetValuesFromDataRow();  
  78.             return true;  
  79.         } catch (Exception e) {  
  80.         }                     
  81.         return false;  
  82.     }  
  83.       
  84.     /** 根據索引取出字段 **/  
  85.     public DataField Value(int idx)  
  86.     {  
  87.         return vecTableDef[idx];  
  88.     }  
  89.       
  90.     /** 得到索引位置的字段名 **/  
  91.     public String fieldName(int idx)  
  92.     {  
  93.         return vecTableDef[idx].GetName();    
  94.     }     
  95.       
  96.     /** 查詢結果 遍歷Cursor結果集給對應的字段賦值 **/  
  97.     public boolean GetValuesFromCursor(Cursor cr)  
  98.     {  
  99.         if ((cr != null) && (cr.getPosition() != -1))  
  100.         {  
  101.             //遍歷  
  102.             for (int idx = 0; idx < vecTableDef.length; idx++)  
  103.             {  
  104.                 DataField field = Value(idx);  
  105.                 //check if null value  
  106.                 if (cr.isNull(idx))  
  107.                 {  
  108.                     //如果查出的值為空 ,設置為空  
  109.                     field.setNull();  
  110.                 } else {  
  111.                 //根據其對應的類型取值  
  112.                     final DataField.Type t = field.GetType();  
  113.                     //parse value by type  
  114.                     if (t == DataField.Type.INT)  
  115.                         field.set(cr.getLong(idx));  
  116.                     if (t == DataField.Type.TEXT)  
  117.                         field.set(cr.getString(idx));  
  118.                     if (t == DataField.Type.BOOL)  
  119.                         field.set((cr.getInt(idx) == 1)?true:false);  
  120.                 }                 
  121.             }  
  122.             return true;  
  123.         }  
  124.         return false;  
  125.     }  
  126.       
  127.     //sets fields values data (ContentValues values contener) from parent object fields  
  128.     /** 為字段賦值 **/  
  129.     public abstract void SetValuesForDataRow();  
  130.   
  131.     //gets data from fields values (ContentValues values contener) to parent object fields  
  132.     /** 得到這個數據類型對應的所有的字段的值 **/  
  133.     public abstract void GetValuesFromDataRow();  
  134.   
  135.     /** 得到表名 **/  
  136.     public abstract String GetTableName();    
  137.       
  138. }  
Table类

[java] view plaincopy
  1. /** 
  2.  * 數據庫中的表類 包含了该表对应的数据类型以及对表的增删改查操作方法 
  3.  * @author KrisLight 
  4.  */  
  5. public class DataTable  
  6. {  
  7.     /** 這個表綁定的數據類型 **/  
  8.     private DataRow dataRow = null;  
  9.     /** DB輔助類 **/  
  10.     private DatabaseOpenHelper helper;  
  11.   
  12.     /** 
  13.      * 更據DataRow來決定是哪一個Table 
  14.      * @param dataRow 
  15.      */  
  16.     public DataTable(DataRow dataRow,DatabaseOpenHelper helper)  
  17.     {  
  18.         this.dataRow = dataRow;  
  19.         this.helper = helper;  
  20.     }  
  21.       
  22.     /** 得到表名 **/  
  23.     public String getTableName()  
  24.     {  
  25.         return dataRow.GetTableName();  
  26.     }  
  27.       
  28.     //DataRow getter()  
  29.     public DataRow getDataRow()  
  30.     {  
  31.         return dataRow;  
  32.     }  
  33.                   
  34.     /** 基本的插入操作 **/  
  35.     public long insertValues()  
  36.     {  
  37.         long lRowId = helper.getWritableDatabase().insert(getTableName(), null, dataRow.GetContentValues());  
  38.         return lRowId;   
  39.     }  
  40.       
  41.     /** 基本的根據ID更新操作 **/  
  42.     public long updateValues(long lRowId)  
  43.     {  
  44.         String sWhere = String.format("_ID = %d", lRowId);  
  45.         long lRowsUpdated = helper.getWritableDatabase().update(getTableName(), dataRow.GetContentValues(), sWhere, null);  
  46.         return lRowsUpdated;  
  47.     }  
  48.     
  49.     /** 基本的根據ID刪除操作 **/  
  50.   public long deleteDataRow(long lRowId)  
  51.   {  
  52.         String sWhere = String.format("_ID = %d", lRowId);  
  53.         long lRowsUpdated = helper.getWritableDatabase().delete(getTableName(), sWhere, null);  
  54.         return lRowsUpdated;  
  55.   }  
  56.       
  57.   /** 基本的根據Id查詢表中的所有字段值 **/  
  58.     public Cursor locateDataRow(long lRowId)  
  59.     {  
  60.         List<String> columnNames = getColumn();  
  61.         String cols = Utils.join(columnNames, ",");  
  62.         final String s = "select %s from %s where _ID = %d";          
  63.         String sql = String.format(s, cols, getTableName(), lRowId);  
  64.         Cursor cr = helper.getReadableDatabase().rawQuery(sql, null);  
  65.         //if cursor valid, set first data row as current  
  66.         if ((cr != null) && (cr.getCount() > 0))  
  67.             cr.moveToFirst();  
  68.         return cr;  
  69.     }  
  70.       
  71.     /** 基本的根據類型和REF_ID查詢鬧鈴提醒功能表的所有字段數據 **/  
  72.     public Cursor locateAlarmDataRow(int iType, long lRefID)  
  73.     {  
  74.         List<String> columnNames = getColumn();  
  75.         String cols = Utils.join(columnNames, ",");  
  76.         final String s = "select %s from %s where Type = %d and RefID = %d";          
  77.         String sql = String.format(s, cols, getTableName(), iType, lRefID);  
  78.         Cursor cr = helper.getReadableDatabase().rawQuery(sql, null);  
  79.         if ((cr != null) && (cr.getCount() > 0))  
  80.             cr.moveToFirst();  
  81.         return cr;  
  82.     }     
  83.       
  84.     /** 
  85.      * 封装的saveOrUpdate操作 
  86.      * @param bInsertMode  是否是插入模式 為true的話是插入新的數據 為false則直接更新舊數據 
  87.      * @param lEditRowId   ID 
  88.      * @return 
  89.      */  
  90.     public DatabaseOpenHelper.Result updateData(boolean bInsertMode, long lEditRowId)  
  91.     {  
  92.         DatabaseOpenHelper.Result result = DatabaseOpenHelper.Result.errUnknown;  
  93.         if (helper.isOpened())  
  94.         {             
  95.             try  
  96.             {  
  97.                 //為字段賦值  
  98.                 dataRow.SetValuesForDataRow();  
  99.             } catch (Exception e) {  
  100.                 //異常就拋出錯誤信息 不能為數據類型的字段賦值  
  101.                 return DatabaseOpenHelper.Result.errCantSetValuesForDataRow;                      
  102.             }  
  103.             //select update mode  
  104.             if (bInsertMode)  
  105.             {  
  106.                 //insert new data row  
  107.                 long lRowId = insertValues();  
  108.                 if (lRowId > 0)  
  109.                 {  
  110.                     //插入成功  
  111.                     result = DatabaseOpenHelper.Result.Success;  
  112.                 } else {  
  113.                     //插入失敗  
  114.                     result = DatabaseOpenHelper.Result.errCantInsertNewData;  
  115.                 }  
  116.             } else {  
  117.                 //update existing data row  
  118.                 long lRowsUpdated = updateValues(lEditRowId);  
  119.                 if (lRowsUpdated == 1)  
  120.                 {  
  121.                     //更新成功  
  122.                     result = DatabaseOpenHelper.Result.Success;  
  123.                 } else {  
  124.                     //更新失敗  
  125.                     result = DatabaseOpenHelper.Result.errCantUpdateData;  
  126.                 }                                     
  127.             }  
  128.         } else {          
  129.             result = DatabaseOpenHelper.Result.errNoDbAccess;  
  130.         }  
  131.         return result;  
  132.     }  
  133.       
  134.     /** 封装的根據Id刪除 **/  
  135.     public DatabaseOpenHelper.Result deleteData(long iRowId)  
  136.     {         
  137.         DatabaseOpenHelper.Result result = DatabaseOpenHelper.Result.errUnknown;  
  138.         if (helper.isOpened())  
  139.         {             
  140.             if (helper.isTableExists(getTableName()))  
  141.             {  
  142.                 long lRowsDeleted = deleteDataRow(iRowId);  
  143.                 if (lRowsDeleted == 1)  
  144.                 {  
  145.                     result = DatabaseOpenHelper.Result.Success;  
  146.                 } else {  
  147.                     result = DatabaseOpenHelper.Result.errCantDeleteData;  
  148.                 }  
  149.             } else {  
  150.                 result = DatabaseOpenHelper.Result.errTableNotExists;  
  151.             }  
  152.         } else {          
  153.             result = DatabaseOpenHelper.Result.errNoDbAccess;  
  154.         }  
  155.         return result;        
  156.     }  
  157.       
  158.     /** 封装的根據ID查詢數據 **/  
  159.   public DatabaseOpenHelper.Result getRowDataForEdit(long lRowId)  
  160.   {  
  161.     DatabaseOpenHelper.Result result = DatabaseOpenHelper.Result.errUnknown;  
  162.         //get requested data row  
  163.         Cursor cr = locateDataRow(lRowId);  
  164.         if (cr == null)  
  165.         {  
  166.             //如果返回為空 結果為errCantGetData  
  167.             result = DatabaseOpenHelper.Result.errCantGetData;  
  168.         } else {  
  169.             if (cr.getCount() > 0)  
  170.             {  
  171.                 if (dataRow.GetValuesFromCursor(cr))  
  172.                 {  
  173.                     try  
  174.                     {  
  175.                         dataRow.GetValuesFromDataRow();  
  176.                     } catch (Exception e) {  
  177.                         return DatabaseOpenHelper.Result.errCantGetValuesFromDataRow;                     
  178.                     }                     
  179.                     result = DatabaseOpenHelper.Result.Success;  
  180.                 } else {  
  181.                     //無法從表中取出数据  
  182.                     result = DatabaseOpenHelper.Result.errCantGetDataFromTable;           
  183.                 }  
  184.                 //关闭光标  
  185.                 cr.close();  
  186.             } else {  
  187.                 //无法找到数据  
  188.                 result = DatabaseOpenHelper.Result.errCantFindData;  
  189.             }  
  190.         }  
  191.         return result;  
  192.   }  
  193.     
  194.     
  195.     /** 得到這個表中的所有字段 **/  
  196.     public List<String> getColumn() {  
  197.         List<String> ar = new ArrayList<String>();  
  198.         try {  
  199.                 DataField[] fields = dataRow.GetTableDef();  
  200.                 for(DataField f : fields){  
  201.                     ar.add(f.GetName());  
  202.                 }  
  203.         } catch (Exception e) {  
  204.             e.printStackTrace();  
  205.         }   
  206.         return ar;  
  207.     }  
  208. }  

安装程序类Installating

[java] view plaincopy
  1. public class Installation {  
  2.     private static String sID = null;  
  3.     private static final String INSTALLATION = "INSTALLATION";  
  4.   
  5.     public synchronized static String id(Context context) {  
  6.         if (sID == null) {    
  7.             File installation = new File(context.getFilesDir(), INSTALLATION);  
  8.             try {  
  9.                 if (!installation.exists()){  
  10.                     writeInstallationFile(installation, context);  
  11.                 }  
  12.                   
  13.                 sID = readInstallationFile(installation);  
  14.             } catch (Exception e) {  
  15.                 //throw new RuntimeException(e);  
  16.             }  
  17.         }  
  18.         return sID;  
  19.     }  
  20.   
  21.     private static String readInstallationFile(File installation) throws IOException {  
  22.         RandomAccessFile f = new RandomAccessFile(installation, "r");  
  23.         byte[] bytes = new byte[(int) f.length()];  
  24.         f.readFully(bytes);  
  25.         f.close();  
  26.         return new String(bytes);  
  27.     }  
  28.   
  29.     private static void writeInstallationFile(File installation, Context context) throws IOException {  
  30.           
  31.         FileOutputStream out = new FileOutputStream(installation);  
  32.           
  33.         String id = "";  
  34.           
  35.         try{  
  36.             id = Settings.Secure.getString(context.getContentResolver(),  
  37.                      Settings.Secure.ANDROID_ID);  
  38.               
  39.             id+=id;  
  40.               
  41.         }catch(Exception e){  
  42.             id = UUID.randomUUID().toString();  
  43.         }  
  44.           
  45.           
  46.           
  47.         out.write(id.getBytes());  
  48.         out.close();  
  49.     }  
  50. }  

获取资源类SearchResource

[java] view plaincopy
  1. public class SearchResource {  
  2.       
  3.     public static int getDrawableResId(Context cnt, String name) throws NotFoundException {  
  4.         int resid = 0;  
  5.         resid = cnt.getResources().getIdentifier(name, "drawable", cnt.getPackageName());  
  6.         if (resid == 0)  
  7.             resid = cnt.getResources().getIdentifier( "transparent_background""drawable", cnt.getPackageName());  
  8.         return resid;  
  9.     }  
  10.   
  11.     public static int getStringResId(Context cnt, String name) throws NotFoundException {  
  12.         int resid = 0;  
  13.         resid = cnt.getResources().getIdentifier(name, "string", cnt.getPackageName());  
  14.         if (resid == 0)  
  15.             resid = cnt.getResources().getIdentifier("empty_string""string", cnt.getPackageName());  
  16.         return resid;  
  17.     }  
  18.   
  19.     public static int getLayoutResId(Context cnt, String name) throws NotFoundException {  
  20.         int resid = 0;  
  21.         resid = cnt.getResources().getIdentifier(name, "layout", cnt.getPackageName());  
  22.         if (resid == 0)  
  23.             resid = cnt.getResources().getIdentifier("empty_layout","layout", cnt.getPackageName());  
  24.         return resid;  
  25.     }  
  26.       
  27.     public static int getItemResId(Context cnt, String name) throws NotFoundException {  
  28.         int resid = cnt.getResources().getIdentifier(name, "id", cnt.getPackageName());  
  29.         return resid;  
  30.     }  
  31.       
  32.     public static int getAnimResId(Context cnt, String name) throws NotFoundException {  
  33.         int resid = cnt.getResources().getIdentifier(name, "anim", cnt.getPackageName());  
  34.         return resid;  
  35.     }  
  36.       
  37.     public static int getAttrResId(Context cnt, String attrName) throws NotFoundException {  
  38.         int resid = cnt.getResources().getIdentifier(attrName, "attr", cnt.getPackageName());  
  39.         return resid;  
  40.     }  
  41.       
  42.     public static int getStyleResId(Context cnt, String attrName) throws NotFoundException {  
  43.         int resid = cnt.getResources().getIdentifier(attrName, "style", cnt.getPackageName());  
  44.         return resid;  
  45.     }  
  46.       
  47.     public static int getMenuResId(Context cnt, String name) throws NotFoundException {  
  48.         int resid = cnt.getResources().getIdentifier(name, "menu", cnt.getPackageName());  
  49.         return resid;  
  50.     }  
  51.       
  52.     public static int[] getStyleableArray(Context cnt, String name) {  
  53.         return null;  
  54.     }  
  55. }  

发送短信类SendMessage
[java] view plaincopy
  1. public class SendMessage {  
  2.     private static final String TAG = "SendMessage";  
  3.       
  4.     private Context m_contect;  
  5.     private ArrayList<HashMap<String, Object>> m_ContactList;  
  6.     private ArrayList<HashMap<String, Object>> m_ContactListbuffer;  
  7.   
  8.     private String m_strMessageContent;  
  9.     private int m_intMessageSendCount=0;  
  10.     private int m_intMessageSendTotalParts;  
  11.     private int m_intMessageSendParts;  
  12.     public static final String SENT = "com.commez.psmd.SMS_SENT";   
  13.     public static final String DELIVERED = "com.commez.psmd.SMS_DELIVERED";   
  14.       
  15.     private ArrayList<String> m_phoneList;  
  16.     private ListView m_ltvDialogContactList;  
  17.     private CustomDialogAdapter m_DialogAdapter;  
  18.     private Dialog dialog;  
  19.     private boolean m_isSendCancel;  
  20.     private static Handler m_handler = new Handler();  
  21.   
  22.     private BroadcastReceiver m_bcrSend;  
  23.     private BroadcastReceiver m_bcrDelivred;  
  24.   
  25.     public SendMessage(Context context, ArrayList<HashMap<String, Object>> contactList,  String messageContent){  
  26.         this.m_contect = context;  
  27.         this.m_strMessageContent = messageContent;  
  28.         m_ContactListbuffer = new ArrayList<HashMap<String,Object>>(contactList);  
  29.         m_isSendCancel = false;  
  30.         fillPhoneNumber();  
  31.     }  
  32.       
  33.     public void startSendMessage(){  
  34.         showSendingListDialog();  
  35.         registerBroadCastReceivers();  
  36.         m_intMessageSendCount = 0;  
  37.         sendSMS(m_phoneList.get(m_intMessageSendCount).toString(), m_strMessageContent);          
  38.     }  
  39.       
  40.     private void fillPhoneNumber(){  
  41.         if(m_ContactListbuffer!=null){  
  42.               
  43.             m_ContactList = new ArrayList<HashMap<String,Object>>();  
  44.               
  45.             HashMap<String , Object> temp;   
  46.             for(int j=0; j<m_ContactListbuffer.size(); j++){  
  47.                 temp=new HashMap<String, Object>();   
  48.                   
  49.                 if(m_ContactListbuffer.get(j).get("name")!=null)      
  50.                     temp.put("name", m_ContactListbuffer.get(j).get("name").toString());   
  51.                 if(m_ContactListbuffer.get(j).get("number")!=null)  
  52.                     temp.put("number", m_ContactListbuffer.get(j).get("number").toString());   
  53.                 if(m_ContactListbuffer.get(j).get("contentid")!=null)  
  54.                     temp.put("contentid", m_ContactListbuffer.get(j).get("contentid").toString());   
  55.   
  56.                 if(j==m_intMessageSendCount)  
  57.                     temp.put("sendstatus""sending");     
  58.                 else  
  59.                     temp.put("sendstatus""unsend");     
  60.                   
  61.                 m_ContactList.add(temp);                      
  62.             }  
  63.   
  64.             m_phoneList = new ArrayList<String>();  
  65.               
  66.             for(int i=0; i<m_ContactList.size(); i++){  
  67.                 m_phoneList.add(m_ContactList.get(i).get("number").toString());  
  68.             }  
  69.         }  
  70.     }  
  71.       
  72.     private void sendNextMessage(){  
  73.         if(thereAreSMSToSend()){  
  74.               
  75.             //m_phoneList.  
  76.                           
  77.             //m_DialogAdapter.notifyDataSetChanged();   
  78.             /*if(m_ContactList!=null) 
  79.                 m_ContactList.clear(); 
  80.              
  81.             HashMap<String , Object> temp;  
  82.             for(int j=0; j<m_ContactListbuffer.size(); j++){ 
  83.                 temp=new HashMap<String, Object>();  
  84.                  
  85.                 if(m_ContactListbuffer.get(j).get("name")!=null)     
  86.                     temp.put("name", m_ContactListbuffer.get(j).get("name").toString());  
  87.                 if(m_ContactListbuffer.get(j).get("number")!=null) 
  88.                     temp.put("number", m_ContactListbuffer.get(j).get("number").toString());  
  89.                 if(m_ContactListbuffer.get(j).get("contentid")!=null) 
  90.                     temp.put("contentid", m_ContactListbuffer.get(j).get("contentid").toString());  
  91.  
  92.                 if(j<m_intMessageSendCount) 
  93.                     temp.put("sendstatus", "sent");  
  94.                 else if(j==m_intMessageSendCount) 
  95.                     temp.put("sendstatus", "sending");  
  96.                 else 
  97.                     temp.put("sendstatus", "unsend");  
  98.  
  99.                 m_ContactList.add(j,temp);                       
  100.             }*/  
  101.               
  102.             HashMap<String , Object> temp =new HashMap<String, Object>();   
  103.             if(m_ContactListbuffer.get(m_intMessageSendCount).get("name")!=null)      
  104.                 temp.put("name", m_ContactListbuffer.get(m_intMessageSendCount).get("name").toString());   
  105.             if(m_ContactListbuffer.get(m_intMessageSendCount).get("number")!=null)  
  106.                 temp.put("number", m_ContactListbuffer.get(m_intMessageSendCount).get("number").toString());   
  107.             if(m_ContactListbuffer.get(m_intMessageSendCount).get("contentid")!=null)  
  108.                 temp.put("contentid", m_ContactListbuffer.get(m_intMessageSendCount).get("contentid").toString());   
  109.   
  110.             temp.put("sendstatus""sending");   
  111.             m_ContactList.set(m_intMessageSendCount,temp);   
  112.               
  113.             sendSMS(m_phoneList.get(m_intMessageSendCount).toString(), m_strMessageContent);  
  114.               
  115.             m_DialogAdapter.notifyDataSetChanged();       
  116.               
  117.         }else{  
  118.             Toast.makeText(m_contect, "All SMS have been sent",Toast.LENGTH_SHORT).show();  
  119.             dialog.dismiss();  
  120.             unRegisterBroadCastReceivers();  
  121.               
  122.         }  
  123.         }  
  124.       
  125.     private void unRegisterBroadCastReceivers() {  
  126.         m_contect.unregisterReceiver(m_bcrSend);  
  127.         m_contect.unregisterReceiver(m_bcrDelivred);              
  128.     }  
  129.       
  130.     private boolean thereAreSMSToSend(){  
  131.         return m_intMessageSendCount < m_phoneList.size();  
  132.     }  
  133.       
  134.     private void sendSMS(String strPhoneNumber, String message){  
  135.         SmsManager sms = SmsManager.getDefault();  
  136.         ArrayList<String> parts = sms.divideMessage(message);  
  137.         m_intMessageSendTotalParts = parts.size();  
  138.           
  139.         ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>();  
  140.         ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();  
  141.   
  142.         PendingIntent sentPI = PendingIntent.getBroadcast(m_contect, 0new Intent(SENT), 0);  
  143.         PendingIntent deliveredPI = PendingIntent.getBroadcast(m_contect, 0new Intent(DELIVERED), 0);  
  144.           
  145.         for(int j=0; j<m_intMessageSendTotalParts; j++){  
  146.             sentIntents.add(sentPI);  
  147.             deliveryIntents.add(deliveredPI);  
  148.         }  
  149.           
  150.         m_intMessageSendParts = 0;  
  151.         /**************************************************************/  
  152.     /*  SystemClock.sleep(50); 
  153.          
  154.         m_intMessageSendParts++; 
  155.         if(m_intMessageSendParts == m_intMessageSendTotalParts){ 
  156.             m_intMessageSendCount++; 
  157.             sendNextMessage(); 
  158.             m_DialogAdapter.notifyDataSetChanged();      
  159.         } 
  160.         /******************************************************************/  
  161.     //  sms.sendMultipartTextMessage(strPhoneNumber, null, parts, sentIntents, deliveryIntents);  
  162.           
  163.           
  164.         //m_handler.removeCallbacks(updatTimer);  
  165.         //m_handler.postDelayed(updatTimer, 3000);  
  166.     }  
  167.       
  168.     private Runnable updatTimer = new Runnable() {  
  169.         public void run() {  
  170.   
  171.             if(m_intMessageSendCount<m_ContactList.size()){  
  172.                   
  173.                 HashMap<String , Object> temp =new HashMap<String, Object>();   
  174.                 if(m_ContactListbuffer.get(m_intMessageSendCount).get("name")!=null)      
  175.                     temp.put("name", m_ContactListbuffer.get(m_intMessageSendCount).get("name").toString());   
  176.                 if(m_ContactListbuffer.get(m_intMessageSendCount).get("number")!=null)  
  177.                     temp.put("number", m_ContactListbuffer.get(m_intMessageSendCount).get("number").toString());   
  178.                 if(m_ContactListbuffer.get(m_intMessageSendCount).get("contentid")!=null)  
  179.                     temp.put("contentid", m_ContactListbuffer.get(m_intMessageSendCount).get("contentid").toString());   
  180.   
  181.                 temp.put("sendstatus""sent");   
  182.                 m_ContactList.set(m_intMessageSendCount,temp);        
  183.                   
  184.                 m_intMessageSendCount++;  
  185.                 sendNextMessage();  
  186.             }  
  187.         }  
  188.     };  
  189.       
  190.     private void registerBroadCastReceivers() {  
  191.           
  192.         IntentFilter intentFilter = new IntentFilter(SENT);  
  193.   
  194.         m_bcrSend = new BroadcastReceiver() {  
  195.             @Override  
  196.             public void onReceive(Context arg0, Intent arg1) {  
  197.                 switch(getResultCode()){  
  198.                   
  199.                 case Activity.RESULT_OK:  
  200.                     m_intMessageSendParts++;  
  201.                     if(m_intMessageSendParts == m_intMessageSendTotalParts && !m_isSendCancel){  
  202.                           
  203.                         HashMap<String , Object> temp =new HashMap<String, Object>();   
  204.                         if(m_ContactListbuffer.get(m_intMessageSendCount).get("name")!=null)      
  205.                             temp.put("name", m_ContactListbuffer.get(m_intMessageSendCount).get("name").toString());   
  206.                         if(m_ContactListbuffer.get(m_intMessageSendCount).get("number")!=null)  
  207.                             temp.put("number", m_ContactListbuffer.get(m_intMessageSendCount).get("number").toString());   
  208.                         if(m_ContactListbuffer.get(m_intMessageSendCount).get("contentid")!=null)  
  209.                             temp.put("contentid", m_ContactListbuffer.get(m_intMessageSendCount).get("contentid").toString());   
  210.   
  211.                         temp.put("sendstatus""sent");   
  212.                         m_ContactList.set(m_intMessageSendCount,temp);                        
  213.                           
  214.                         m_intMessageSendCount++;  
  215.                         sendNextMessage();  
  216.                     }                     
  217.                     //Toast.makeText(m_contect, "SMS sent",Toast.LENGTH_SHORT).show();  
  218.                       
  219.                     break;  
  220.                 case SmsManager.RESULT_ERROR_GENERIC_FAILURE:   
  221.                     Toast.makeText(m_contect, "Generic failure",Toast.LENGTH_SHORT).show();  
  222.                     break;   
  223.                 case SmsManager.RESULT_ERROR_NO_SERVICE:   
  224.                     Toast.makeText(m_contect, "No service",Toast.LENGTH_SHORT).show();  
  225.                     break;   
  226.                 case SmsManager.RESULT_ERROR_NULL_PDU:   
  227.                     Toast.makeText(m_contect, "No PDU",Toast.LENGTH_SHORT).show();  
  228.                     break;   
  229.                 case SmsManager.RESULT_ERROR_RADIO_OFF:  
  230.                     Toast.makeText(m_contect, "Radio off",Toast.LENGTH_SHORT).show();  
  231.                     break;   
  232.                 }                 
  233.             }     
  234.         };  
  235.           
  236.         m_contect.registerReceiver(m_bcrSend, intentFilter);    
  237.           
  238.           
  239.         IntentFilter intentFilter1 = new IntentFilter(DELIVERED);  
  240.   
  241.         m_bcrDelivred = new BroadcastReceiver() {  
  242.             @Override  
  243.             public void onReceive(Context arg0, Intent arg1) {  
  244.                 switch(getResultCode()){  
  245.                   
  246.                 case Activity.RESULT_OK:  
  247.                     break;  
  248.                 case Activity.RESULT_CANCELED:  
  249.                     break;  
  250.                 }                 
  251.             }     
  252.         };  
  253.         m_contect.registerReceiver(m_bcrDelivred, intentFilter1);    
  254.   
  255.           
  256.         /*m_contect.registerReceiver(new BroadcastReceiver(){ 
  257.  
  258.             @Override 
  259.             public void onReceive(Context arg0, Intent arg1) { 
  260.                 switch(getResultCode()){ 
  261.                  
  262.                 case Activity.RESULT_OK: 
  263.                     m_intMessageSendParts++; 
  264.                     if(m_intMessageSendParts == m_intMessageSendTotalParts && !m_isSendCancel){ 
  265.                          
  266.                         HashMap<String , Object> temp =new HashMap<String, Object>();  
  267.                         if(m_ContactListbuffer.get(m_intMessageSendCount).get("name")!=null)     
  268.                             temp.put("name", m_ContactListbuffer.get(m_intMessageSendCount).get("name").toString());  
  269.                         if(m_ContactListbuffer.get(m_intMessageSendCount).get("number")!=null) 
  270.                             temp.put("number", m_ContactListbuffer.get(m_intMessageSendCount).get("number").toString());  
  271.                         if(m_ContactListbuffer.get(m_intMessageSendCount).get("contentid")!=null) 
  272.                             temp.put("contentid", m_ContactListbuffer.get(m_intMessageSendCount).get("contentid").toString());  
  273.  
  274.                         temp.put("sendstatus", "sent");  
  275.                         m_ContactList.set(m_intMessageSendCount,temp);                       
  276.                          
  277.                         m_intMessageSendCount++; 
  278.                         sendNextMessage(); 
  279.                     }                    
  280.                     //Toast.makeText(m_contect, "SMS sent",Toast.LENGTH_SHORT).show(); 
  281.                      
  282.                     break; 
  283.                 case SmsManager.RESULT_ERROR_GENERIC_FAILURE:  
  284.                     Toast.makeText(m_contect, "Generic failure",Toast.LENGTH_SHORT).show(); 
  285.                     break;  
  286.                 case SmsManager.RESULT_ERROR_NO_SERVICE:  
  287.                     Toast.makeText(m_contect, "No service",Toast.LENGTH_SHORT).show(); 
  288.                     break;  
  289.                 case SmsManager.RESULT_ERROR_NULL_PDU:  
  290.                     Toast.makeText(m_contect, "No PDU",Toast.LENGTH_SHORT).show(); 
  291.                     break;  
  292.                 case SmsManager.RESULT_ERROR_RADIO_OFF: 
  293.                     Toast.makeText(m_contect, "Radio off",Toast.LENGTH_SHORT).show(); 
  294.                     break;  
  295.                 }                
  296.             }        
  297.         }, new IntentFilter(SENT)); 
  298.          
  299.         m_contect.registerReceiver(new BroadcastReceiver(){ 
  300.  
  301.             @Override 
  302.             public void onReceive(Context arg0, Intent arg1) { 
  303.                 switch(getResultCode()){ 
  304.                  
  305.                 case Activity.RESULT_OK: 
  306.                     break; 
  307.                 case Activity.RESULT_CANCELED: 
  308.                     break; 
  309.                 }                
  310.             }        
  311.         }, new IntentFilter(DELIVERED));     
  312.          
  313.         */  
  314.     }  
  315.   
  316.     private void showSendingListDialog() {  
  317.           
  318.         LayoutInflater factory = LayoutInflater.from(m_contect);  
  319.         View dialogView = factory.inflate(R.layout.sms_send_list, null);  
  320.         m_ltvDialogContactList = (ListView) dialogView.findViewById(R.id.lv_sendlist);  
  321.         setDialogAdapter();  
  322.                           
  323.         TextView dialogContent = (TextView) dialogView.findViewById(R.id.dialog_sendlist_content);  
  324.         dialogContent.setText(R.string.dtl_SendList);  
  325.         Button rightButton = (Button) dialogView.findViewById(R.id.dialog_sendlist_rightbtn);  
  326.         rightButton.setText(R.string.dmg_SendBackground);  
  327.         Button leftButton = (Button) dialogView.findViewById(R.id.dialog_sendlist_leftbtn);  
  328.         leftButton.setText(R.string.dmg_SendCancel);  
  329.           
  330.           
  331.         rightButton.setOnClickListener(new OnClickListener() {  
  332.             @Override  
  333.             public void onClick(View v) {  
  334.                 dialog.dismiss();  
  335.                   
  336.             }  
  337.         });  
  338.               
  339.         leftButton.setOnClickListener(new OnClickListener() {  
  340.             @Override  
  341.             public void onClick(View v) {  
  342.                 dialog.dismiss();  
  343.   
  344.             }  
  345.         });  
  346.           
  347.         dialog = new Dialog(m_contect);  
  348.         dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);  
  349.         dialog.setCancelable(false);  
  350.         dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);  
  351.         dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));  
  352.         dialog.setContentView(dialogView);  
  353.         dialog.show();  
  354.                   
  355.         /*dialog = new AlertDialog.Builder(m_contect).setTitle(R.string.dtl_SendList) 
  356.                 .setView(dialogView) 
  357.                 .setPositiveButton(R.string.dmg_SendCancel, new DialogInterface.OnClickListener() {      
  358.                     @Override 
  359.                     public void onClick(DialogInterface dialog, int which) { 
  360.                         m_isSendCancel = true; 
  361.                         unRegisterBroadCastReceivers(); 
  362.                     }}) 
  363.                 .setNegativeButton(R.string.dmg_SendBackground, new DialogInterface.OnClickListener() { 
  364.                                 @Override 
  365.                     public void onClick(DialogInterface dialog, int which) { 
  366.  
  367.                     }}).create(); 
  368.         dialog.show();*/  
  369.     }  
  370.       
  371.     private void setDialogAdapter() {  
  372.         m_DialogAdapter = new CustomDialogAdapter(m_contect, R.layout.sms_send_list_item, m_ContactList);   
  373.         m_ltvDialogContactList.setAdapter(m_DialogAdapter);  
  374.     }  
  375.       
  376.     private class CustomDialogAdapter extends ArrayAdapter<HashMap<String, Object>> {       
  377.           
  378.         public CustomDialogAdapter(Context context, int textViewResourceId, ArrayList<HashMap<String, Object>> Strings) {     
  379.             super(context, textViewResourceId, Strings);     
  380.         }         
  381.                   
  382.         private class ViewHolder{      
  383.             TextView txvContact;  
  384.             TextView txvSendStatus;  
  385.             ProgressBar prgbSend;  
  386.         }       
  387.           
  388.         ViewHolder viewHolder;       
  389.           
  390.         @Override    
  391.         public View getView(final int position, View convertView, ViewGroup parent) {        
  392.               
  393.             if(convertView==null){   
  394.                 LayoutInflater inflater = (LayoutInflater) m_contect.getSystemService( Context.LAYOUT_INFLATER_SERVICE );  
  395.                 convertView = inflater.inflate(R.layout.sms_send_list_item, null);   
  396.                 viewHolder=new ViewHolder();                  
  397.                 viewHolder.txvContact=(TextView) convertView.findViewById(R.id.txvSendlistitem_name);   
  398.                 viewHolder.txvSendStatus=(TextView) convertView.findViewById(R.id.txvSendlistitem_status);   
  399.                 viewHolder.prgbSend=(ProgressBar) convertView.findViewById(R.id.pb_sending);   
  400.               
  401.                 convertView.setTag(viewHolder);       
  402.             }   
  403.             viewHolder=(ViewHolder) convertView.getTag();                     
  404.             viewHolder.txvContact.setText(m_ContactList.get(position).get("number").toString());   
  405.               
  406.               
  407.             String isSend = m_ContactList.get(position).get("sendstatus").toString();  
  408.             if(isSend=="sent"){  
  409.                 viewHolder.prgbSend.setVisibility(View.GONE);  
  410.                 viewHolder.txvSendStatus.setVisibility(View.VISIBLE);  
  411.                 viewHolder.txvSendStatus.setText(R.string.dmg_Sent);  
  412.             }else if(isSend=="sending"){  
  413.             viewHolder.prgbSend.setVisibility(View.VISIBLE);  
  414.                 viewHolder.txvSendStatus.setVisibility(View.GONE);  
  415.             }else if(isSend=="unsend"){  
  416.                 viewHolder.prgbSend.setVisibility(View.GONE);  
  417.                 viewHolder.txvSendStatus.setVisibility(View.VISIBLE);  
  418.                 viewHolder.txvSendStatus.setText(R.string.dmg_SendWait);  
  419.             }  
  420.   
  421.             return convertView;     
  422.         }      
  423.     }   
  424.     /*public static void sendMessage(Context context, String strAddress, String strMessage){ 
  425.          
  426.         try {     
  427.              Uri smsUri = Uri.parse("tel:123456"); 
  428.              Intent intent = new Intent(Intent.ACTION_VIEW, smsUri); 
  429.              intent.putExtra("sms_body", ""); 
  430.              intent.setType("vnd.android-dir/mms-sms");  
  431.              intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  432.              context.startActivity(intent); 
  433.         } catch (ActivityNotFoundException e) { 
  434.  
  435.             Log.e(TAG, "Send SMS failed", e); 
  436.         } 
  437.  
  438.     }*/  
  439.   
  440. }  
时间字符串处理类1:

[java] view plaincopy
  1. public class C_DateUtils {  
  2.     private static final String TAG = C_DateUtils.class.getSimpleName();  
  3.       
  4.       
  5.     /** 
  6.      * check date is today 
  7.      * @param date 
  8.      * @return 
  9.      */  
  10.     public static boolean isToday(Date date){  
  11.         return isSameDate(new Date(), date);  
  12.     }  
  13.       
  14.     /** 
  15.      * check Date is same day 
  16.      * @param baseDate 
  17.      * @param thenDate 
  18.      * @return 
  19.      */  
  20.     public static boolean isSameDate(Date baseDate, Date thenDate){  
  21.         Time time = new Time();  
  22.         time.set(thenDate.getTime());  
  23.   
  24.         int thenYear = time.year;  
  25.         int thenMonth = time.month;  
  26.         int thenMonthDay = time.monthDay;  
  27.   
  28.         time.set(baseDate.getTime());  
  29.         return (thenYear == time.year)  
  30.                 && (thenMonth == time.month)  
  31.                 && (thenMonthDay == time.monthDay);  
  32.     }  
  33.       
  34.     /** 
  35.      * caculate day counts between startDate and endDate 
  36.      * @param startDate 
  37.      * @param endDate 
  38.      * @return 
  39.      */  
  40.     public static int diffDays(Date startDate, Date endDate){  
  41.         return (int)((endDate.getTime() - startDate.getTime()) / DateUtils.DAY_IN_MILLIS);  
  42.     }  
  43.       
  44.     /** 
  45.      * caculate week counts between startDate and endDate 
  46.      * @param startDate 
  47.      * @param endDate 
  48.      * @return 
  49.      */  
  50.     public static int diffWeeks(Date startDate, Date endDate){  
  51.         return (int)((endDate.getTime() - startDate.getTime()) / DateUtils.WEEK_IN_MILLIS);  
  52.     }  
  53.       
  54.     /** 
  55.      * caculate month counts between startDate and endDate 
  56.      * @param startDate 
  57.      * @param endDate 
  58.      * @return 
  59.      */  
  60.     public static int diffMonths(Date startDate, Date endDate){  
  61.         Time startTime = new Time();  
  62.         startTime.set(startDate.getTime());  
  63.         Time endTime = new Time();  
  64.         endTime.set(endDate.getTime());  
  65.         int diffYears = endTime.year - startTime.year;  
  66.           
  67.         return diffYears * 12 + endTime.month - startTime.month;  
  68.     }  
  69.       
  70.     /** 
  71.      * caculate year counts between startDate and endDate 
  72.      * @param startDate 
  73.      * @param endDate 
  74.      * @return 
  75.      */  
  76.     public static int diffYears(Date startDate, Date endDate){  
  77.         Time startTime = new Time();  
  78.         startTime.set(startDate.getTime());  
  79.         Time endTime = new Time();  
  80.         endTime.set(endDate.getTime());  
  81.         int diffYears = endTime.year - startTime.year;  
  82.         return diffYears;  
  83.     }  
  84.       
  85.     /** 
  86.      * return date is Saturday or Sunday 
  87.      * @param date 
  88.      * @return 
  89.      */  
  90.     public static boolean isWeekend(Date date){  
  91.         Time time = new Time();  
  92.         time.set(date.getTime());  
  93.         return (time.weekDay == Time.SATURDAY || time.weekDay == Time.SUNDAY);  
  94.     }  
  95.       
  96. }  

时间字符串处理类2:

[java] view plaincopy
  1. /** 
  2.  * 工具類 
  3.  * @author KrisLight 
  4.  * 
  5.  */  
  6. public class Utils   
  7. {  
  8.     /** 
  9.      * 透明度動畫變化持續時間 
  10.      */  
  11.     public static int ANIM_ALPHA_DURATION = 100;  
  12.     /** 
  13.      * 平移動畫持續時間 
  14.      */  
  15.     public static int ANIM_TRANSLATE_DURATION = 30;   
  16.       
  17.       
  18.     /** 
  19.      *  周別格式   EEEE 
  20.      */  
  21.     private SimpleDateFormat dateFormatWeekDay = new SimpleDateFormat("EEEE");  
  22.       
  23.     /** 
  24.      *  月份格式    MMMM 
  25.      */  
  26.     private SimpleDateFormat dateFormatMonth = new SimpleDateFormat("MMMM");  
  27.     /** 
  28.      *  包括年,月,日,周的日期格式   EEEE, d MMMM yyyy 
  29.      */  
  30.     private SimpleDateFormat dateFormatLong = new SimpleDateFormat("EEEE, d MMMM yyyy");  
  31.     /** 
  32.      *  包括年,月,日的日期格式   dd-MM-yyyy 
  33.      */  
  34.     private SimpleDateFormat dateFormatShort = new SimpleDateFormat("dd-MM-yyyy");  
  35.       
  36.     /** 
  37.      * Sql中的日期格式   dd-MM-yyyy kk:mm.ss 
  38.      */  
  39.     private SimpleDateFormat dateFormatSql = new SimpleDateFormat("dd-MM-yyyy kk:mm.ss");  
  40.   
  41.     //UTILS  
  42.     public Utils()  
  43.     {  
  44.     }  
  45.       
  46.     /** 
  47.      * 得到周別的日期字符串  
  48.      */  
  49.     public String GetWeekDay(Calendar date)  
  50.     {  
  51.         return dateFormatWeekDay.format(date.getTime());  
  52.     }  
  53.   
  54.     /** 
  55.      * 得到月的日期字符串  
  56.      */  
  57.   
  58.     public String GetMonth(Calendar date)  
  59.     {  
  60.         return dateFormatMonth.format(date.getTime());  
  61.     }  
  62.       
  63.     /** 
  64.      * 得到包括年,月,日,周的日期格式字符串  
  65.      */  
  66.     public String GetLongDate(Calendar date)  
  67.     {  
  68.         return dateFormatLong.format(date.getTime());  
  69.     }  
  70.       
  71.     /** 
  72.      * 得到包括年,月,日的日期格式字符串  
  73.      */  
  74.     public String GetShortDate(Calendar date)  
  75.     {  
  76.         return dateFormatShort.format(date.getTime());  
  77.     }  
  78.       
  79.     /** 
  80.      *  
  81.      * @Function: pl.magot.vetch.ancal.Utils.GetLongTime 
  82.      * @Description: 得到時和分 
  83.      * 
  84.      * @param date 日期 
  85.      * @param b24HourMode  是否24小時制: true 是  false 否 
  86.      * @return  由小時和分鐘組成的字符串 如: 12:20 
  87.      * 
  88.      * @version:v1.0 
  89.      * @author:KrisLight 
  90.      * @date:2013/9/4 下午4:51:27 
  91.      * 
  92.      * Modification History: 
  93.      * Date         Author      Version     Description 
  94.      * ----------------------------------------------------------------- 
  95.      * 2013/9/4    KrisLight      v1.0.0         create 
  96.      */  
  97.     public String GetLongTime(Calendar date, boolean b24HourMode)  
  98.     {  
  99.         String s = "";  
  100.         if (b24HourMode)  
  101.         {  
  102.             //k: 24 小时制的小时     M: 小时中的分钟  
  103.             s = String.format("%tk:%tM", date, date);  
  104.         } else {              
  105.             //l: 12 小时制的小时     M: 小时中的分钟  
  106.             if (date.get(Calendar.AM_PM) == 0//AM       
  107.                 s = String.format("%tl:%tM am", date, date, date.get(Calendar.AM_PM));  
  108.             if (date.get(Calendar.AM_PM) == 1//PM                       
  109.                 s = String.format("%tl:%tM pm", date, date, date.get(Calendar.AM_PM));  
  110.         }  
  111.         return s;   
  112.     }  
  113.   
  114.       
  115.     /** 
  116.      *  
  117.      * @Function: pl.magot.vetch.ancal.Utils.SqlStrToDate 
  118.      * @Description: 將用Sql語句查出來的日期字符串轉換成對應的日期Date 
  119.      * 
  120.      * @param s  sql format: "dd-MM-yyyy kk:mm.ss" 
  121.      * @param dateOut 轉換成功的日期 
  122.      * @param dateFail 轉換失敗默認的日期 
  123.      * @return 
  124.      * 
  125.      * @version:v1.0 
  126.      * @author:KrisLight 
  127.      * @date:2013/9/4 下午5:07:40 
  128.      * 
  129.      * Modification History: 
  130.      * Date         Author      Version     Description 
  131.      * ----------------------------------------------------------------- 
  132.      * 2013/9/4    KrisLight      v1.0.0         create 
  133.      */  
  134.     public static Calendar SqlStrToDate(String s, Calendar dateOut, Calendar dateFail)  
  135.     {  
  136.         if (s.length() == 19)  
  137.         {  
  138.             int dd = Integer.parseInt(s.substring(02));  
  139.             int MM = Integer.parseInt(s.substring(35));  
  140.             int yyyy = Integer.parseInt(s.substring(610));  
  141.             int kk = Integer.parseInt(s.substring(1113));  
  142.             int mm = Integer.parseInt(s.substring(1416));  
  143.             int ss = Integer.parseInt(s.substring(1719));  
  144.             // set(int year, int month, int day, int hourOfDay, int minute, int second) 這裡月從0開始  1月對應的是0  
  145.             dateOut.set(yyyy, MM - 1, dd, kk, mm, ss);  
  146.             return dateOut;  
  147.         }  
  148.         return dateFail;          
  149.     }  
  150.       
  151.       
  152.     /** 
  153.      *  
  154.      * @Function: pl.magot.vetch.ancal.Utils.DateToSqlStr 
  155.      * @Description:將日期轉換成SQL中需要的日期格式 
  156.      * 
  157.      * @param date 
  158.      * @return 
  159.      * 
  160.      * @version:v1.0 
  161.      * @author:KrisLight 
  162.      * @date:2013/9/4 下午5:11:29 
  163.      * 
  164.      * Modification History: 
  165.      * Date         Author      Version     Description 
  166.      * ----------------------------------------------------------------- 
  167.      * 2013/9/4    KrisLight      v1.0.0         create 
  168.      */  
  169.     public String DateToSqlStr(Calendar date)  
  170.     {  
  171.         return dateFormatSql.format(date.getTime());  
  172.     }  
  173.       
  174.     /** 
  175.      *  將時間轉換成秒 
  176.      */  
  177.     public static int GetTimeAsSeconds(Calendar date)  
  178.     {  
  179.         return (date.get(Calendar.HOUR_OF_DAY) * 3600) +  
  180.             date.get(Calendar.MINUTE) * 60;  
  181.     }  
  182.   
  183.     /** 
  184.      *  清除日期 
  185.      */  
  186.     public static void ClearCalendarTime(Calendar cal)  
  187.     {  
  188.         cal.clear(Calendar.MILLISECOND);  
  189.         cal.clear(Calendar.SECOND);  
  190.         cal.clear(Calendar.MINUTE);  
  191.         cal.clear(Calendar.HOUR_OF_DAY);  
  192.     }  
  193.       
  194.     /** 
  195.      *  判斷日期是否相等 
  196.      */  
  197.     public static boolean YearDaysEqual(Calendar calDate, Calendar calDateTo)  
  198.     {  
  199.         if (calDate.get(Calendar.YEAR) == calDateTo.get(Calendar.YEAR))  
  200.             if (calDate.get(Calendar.MONTH) == calDateTo.get(Calendar.MONTH))  
  201.                 if (calDate.get(Calendar.DAY_OF_MONTH) == calDateTo.get(Calendar.DAY_OF_MONTH))  
  202.                     return true;  
  203.         return false;  
  204.     }  
  205.   
  206.     /** 
  207.      *  判斷前一個日期是否大於后一個 
  208.      */  
  209.     public static boolean YearDaysGreater(Calendar calDate, Calendar calDateTo)  
  210.     {  
  211.         if (calDate.get(Calendar.YEAR) >= calDateTo.get(Calendar.YEAR))  
  212.             if (calDate.get(Calendar.MONTH) >= calDateTo.get(Calendar.MONTH))  
  213.                 if (calDate.get(Calendar.DAY_OF_MONTH) >= calDateTo.get(Calendar.DAY_OF_MONTH))  
  214.                     return true;  
  215.         return false;  
  216.     }  
  217.       
  218.     /** 
  219.      * 判斷前一個時間是否等於或晚於後面一個時間  
  220.      * 用於設置鬧鐘的時候與當前時間判斷 
  221.      * 設置的鬧鈴時間必須晚於當前時間 
  222.      */  
  223.     public static boolean IsTimeOverdued(Calendar calDate, Calendar calDueDate)  
  224.     {  
  225.         if ((calDueDate.compareTo(calDate) == 0) || (calDueDate.compareTo(calDate) == 1))  
  226.             return true;  
  227.         return false;  
  228.     }  
  229.       
  230.     //compare time: for calendar view display  
  231.     public static boolean IsInTimeRange(Calendar calDateStart, Calendar calDate, int iDurationInMinutes)  
  232.     {  
  233.         if (calDate.get(Calendar.HOUR_OF_DAY) == calDateStart.get(Calendar.HOUR_OF_DAY))  
  234.             if (calDate.get(Calendar.MINUTE) >= calDateStart.get(Calendar.MINUTE))  
  235.                 if (calDate.get(Calendar.MINUTE) <= (calDateStart.get(Calendar.MINUTE) + iDurationInMinutes))  
  236.                     return true;  
  237.         return false;  
  238.     }     
  239.       
  240.     /** 
  241.      *  將時間轉換成long類型  形如: 200712122359 
  242.      */  
  243.     public static long GetDateTimeKey(Calendar calDate)  
  244.     {  
  245.         long lYear = calDate.get(Calendar.YEAR) * 100000000;  
  246.         long lMonth = calDate.get(Calendar.MONTH) * 1000000;  
  247.         long lDay = calDate.get(Calendar.DAY_OF_MONTH) * 10000;  
  248.         long lHour = calDate.get(Calendar.HOUR_OF_DAY) * 100;  
  249.         long lMinute = calDate.get(Calendar.MINUTE);  
  250.         return lYear + lMonth + lDay + lHour + lMinute;  
  251.     }  
  252.   
  253.     /** 
  254.      *  首字母大寫 
  255.      */  
  256.     public static String CapitalizeFirstLetter(String sText)  
  257.     {  
  258.         return sText.substring(0,1).toUpperCase() + sText.substring(1, sText.length()).toLowerCase();  
  259.     }  
  260.   
  261.     /** 
  262.      *  得到App版本 
  263.      */  
  264.     public static String getAppVersionName(Context ctx)  
  265.     {  
  266.         try  
  267.         {  
  268.             PackageInfo pi = ctx.getPackageManager().getPackageInfo("pl.magot.vetch.ancal"0);  
  269.             return pi.versionName;  
  270.         } catch (NameNotFoundException e) {  
  271.         }  
  272.         return "";  
  273.     }  
  274.       
  275.       
  276.     /** 
  277.      *  
  278.      * @Function: com.light.mycal.util.Utils.join 
  279.      * @Description: 集合中的元素以指定分隔符隔開 
  280.      * 
  281.      * @param list   集合List 
  282.      * @param delim  分隔符 
  283.      * @return  用分隔符隔開的集合元素字符串 
  284.      * 
  285.      * @version: v1.0 
  286.      * @author: KrisLight 
  287.      * @date: 2013/9/5 上午10:20:51 
  288.      * 
  289.      * Modification History: 
  290.      * Date         Author      Version     Description 
  291.      * ----------------------------------------------------------------- 
  292.      * 2013/9/5    KrisLight      v1.0.0         create 
  293.      */  
  294.     public static String join(List<String> list, String delim) {  
  295.         StringBuilder buf = new StringBuilder();  
  296.         int num = list.size();  
  297.         for (int i = 0; i < num; i++) {  
  298.             if (i != 0){  
  299.                 buf.append(delim);  
  300.             }  
  301.             buf.append((String) list.get(i));  
  302.         }  
  303.         return buf.toString();  
  304.     }  
  305.       
  306.     /** 
  307.      *  開始alpha動畫 
  308.      */  
  309.   public static void startAlphaAnimIn(View view)  
  310.   {  
  311.         AlphaAnimation anim = new AlphaAnimation(0.5F, 1);  
  312.         anim.setDuration(ANIM_ALPHA_DURATION);  
  313.         anim.startNow();  
  314.         view.startAnimation(anim);  
  315.   }  
  316.     
  317.     /** 
  318.      *  開始translate動畫 
  319.      */  
  320.   public static void startTranslateAnimIn(View view)  
  321.   {  
  322.         TranslateAnimation anim = new TranslateAnimation(00, - view.getHeight(), 0);  
  323.         anim.setDuration(ANIM_TRANSLATE_DURATION);  
  324.         anim.startNow();  
  325.         view.startAnimation(anim);  
  326.   }    
  327.       
  328. }  

图像处理类 

1.图像缓存


[java] view plaincopy
  1. public class BitmapCache {  
  2.       
  3.     private static final   
  4.   
  5. String TAG = "ImageCache";  
  6.   
  7.     private static final int   
  8.   
  9. DEFAULT_MEM_CACHE_SIZE = 1024 * 1024 * 8// 8MB  
  10.   
  11.       
  12.   
  13. private static final int DEFAULT_DISK_CACHE_SIZE = 1024 *   
  14.   
  15. 1024 * 20// 20MB  
  16.   
  17.     // Compression settings when   
  18.   
  19. writing images to disk cache  
  20.     private static final   
  21.   
  22. CompressFormat DEFAULT_COMPRESS_FORMAT =   
  23.   
  24. CompressFormat.JPEG;  
  25.     private static final int   
  26.   
  27. DEFAULT_COMPRESS_QUALITY = 70;  
  28.     private static final   
  29.   
  30. int DISK_CACHE_INDEX = 0;  
  31.   
  32.     // Constants to easily   
  33.   
  34. toggle various caches  
  35.     private static final boolean   
  36.   
  37. DEFAULT_MEM_CACHE_ENABLED = true;  
  38.     private static final   
  39.   
  40. boolean DEFAULT_DISK_CACHE_ENABLED = true;  
  41.     private   
  42.   
  43. static final boolean DEFAULT_CLEAR_DISK_CACHE_ON_START =   
  44.   
  45. false;  
  46.     private static final boolean   
  47.   
  48. DEFAULT_INIT_DISK_CACHE_ON_CREATE = false;  
  49.   
  50.     private   
  51.   
  52. LruDiskCache mDiskLruCache;  
  53.     private   
  54.   
  55. LruMemoryCache<String, Bitmap> mMemoryCache;  
  56.     private   
  57.   
  58. ImageCacheParams mCacheParams;  
  59.     private final Object   
  60.   
  61. mDiskCacheLock = new Object();  
  62.     private boolean   
  63.   
  64. mDiskCacheStarting = true;  
  65.   
  66.     /** 
  67.      * Creating a new  
  68.  
  69. ImageCache object using the specified parameters. 
  70.      * 
  71.     
  72.  
  73.   * @param cacheParams The cache parameters to use to  
  74.  
  75. initialize the cache 
  76.      */  
  77.     public BitmapCache  
  78.   
  79. (ImageCacheParams cacheParams) {  
  80.         init  
  81.   
  82. (cacheParams);  
  83.     }  
  84.   
  85.   
  86.     /** 
  87.      * Initialize the cache,  
  88.  
  89. providing all parameters. 
  90.      * 
  91.      * @param cacheParams  
  92.  
  93. The cache parameters to initialize the cache 
  94.      */  
  95.       
  96.   
  97. private void init(ImageCacheParams cacheParams) {  
  98.           
  99.   
  100. mCacheParams = cacheParams;  
  101.   
  102.         // Set up memory cache  
  103.    
  104.   
  105.        if (mCacheParams.memoryCacheEnabled) {  
  106.               
  107.   
  108. mMemoryCache = new LruMemoryCache<String, Bitmap>  
  109.   
  110. (mCacheParams.memCacheSize) {  
  111.                 /** 
  112.            
  113.  
  114.        * Measure item size in bytes rather than units  
  115.  
  116. which is more practical 
  117.                  * for a bitmap  
  118.  
  119. cache 
  120.                  */  
  121.                 @Override  
  122.            
  123.   
  124.        protected int sizeOf(String key, Bitmap bitmap) {  
  125.     
  126.   
  127.                   return BitmapCommonUtils.getBitmapSize  
  128.   
  129. (bitmap);  
  130.                 }  
  131.             };  
  132.         }  
  133.   
  134.           
  135.   
  136. // By default the disk cache is not initialized here as   
  137.   
  138. it should be initialized  
  139.         // on a separate thread   
  140.   
  141. due to disk access.  
  142.         if   
  143.   
  144. (cacheParams.initDiskCacheOnCreate) {  
  145.             // Set   
  146.   
  147. up disk cache  
  148.             initDiskCache();  
  149.         }  
  150.     }  
  151.   
  152.      
  153.   
  154.  /** 
  155.      * Initializes the disk cache.  Note that this  
  156.  
  157. includes disk access so this should not be 
  158.      * executed  
  159.  
  160. on the main/UI thread. By default an ImageCache does not  
  161.  
  162. initialize the disk 
  163.      * cache when it is created,  
  164.  
  165. instead you should call initDiskCache() to initialize it  
  166.  
  167. on a 
  168.      * background thread. 
  169.      */  
  170.     public void   
  171.   
  172. initDiskCache() {  
  173.         // Set up disk cache  
  174.           
  175.   
  176. synchronized (mDiskCacheLock) {  
  177.             if   
  178.   
  179. (mDiskLruCache == null || mDiskLruCache.isClosed()) {  
  180.        
  181.   
  182.            File diskCacheDir = mCacheParams.diskCacheDir;  
  183.    
  184.   
  185.                if (mCacheParams.diskCacheEnabled &&   
  186.   
  187. diskCacheDir != null) {  
  188.                     if (!  
  189.   
  190. diskCacheDir.exists()) {  
  191.                           
  192.   
  193. diskCacheDir.mkdirs();  
  194.                     }  
  195.                  
  196.   
  197.      if (BitmapCommonUtils.getUsableSpace(diskCacheDir) >   
  198.   
  199. mCacheParams.diskCacheSize) {  
  200.                         try   
  201.   
  202. {  
  203.                             mDiskLruCache =   
  204.   
  205. LruDiskCache.open(diskCacheDir, 11,   
  206.   
  207. mCacheParams.diskCacheSize);  
  208.                         }   
  209.   
  210. catch (final IOException e) {  
  211.                               
  212.   
  213. mCacheParams.diskCacheDir = null;  
  214.                            
  215.   
  216.    Log.e(TAG, "initDiskCache - " + e);  
  217.                       
  218.   
  219.     }  
  220.                     }  
  221.                 }  
  222.             }  
  223.     
  224.   
  225.           mDiskCacheStarting = false;  
  226.               
  227.   
  228. mDiskCacheLock.notifyAll();  
  229.         }  
  230.     }  
  231.   
  232.     /** 
  233.      *  
  234.  
  235. Adds a bitmap to both memory and disk cache. 
  236.      * @param  
  237.  
  238. data Unique identifier for the bitmap to store 
  239.      *  
  240.  
  241. @param bitmap The bitmap to store 
  242.      */  
  243.     public void   
  244.   
  245. addBitmapToCache(String data, Bitmap bitmap) {  
  246.         if   
  247.   
  248. (data == null || bitmap == null) {  
  249.             return;  
  250.        
  251.   
  252.    }  
  253.   
  254.         // Add to memory cache  
  255.         if   
  256.   
  257. (mMemoryCache != null && mMemoryCache.get(data) == null)   
  258.   
  259. {  
  260.             mMemoryCache.put(data, bitmap);  
  261.         }  
  262.   
  263.        
  264.   
  265.    synchronized (mDiskCacheLock) {  
  266.            if   
  267.   
  268. (mDiskLruCache != null && mDiskLruCache.getDirectory()!=   
  269.   
  270. null ) {  
  271.                   
  272.                 if(!  
  273.   
  274. mDiskLruCache.getDirectory().exists())  
  275.                       
  276.   
  277. mDiskLruCache.getDirectory().mkdirs();  
  278.                   
  279.     
  280.   
  281.               final String key =   
  282.   
  283. FileNameGenerator.generator(data);  
  284.                   
  285.   
  286. OutputStream out = null;  
  287.                 try {  
  288.                
  289.   
  290.        LruDiskCache.Snapshot snapshot =   
  291.   
  292. mDiskLruCache.get(key);  
  293.                     if (snapshot   
  294.   
  295. == null) {  
  296.                         final   
  297.   
  298. LruDiskCache.Editor editor = mDiskLruCache.edit(key);  
  299.        
  300.   
  301.                    if (editor != null) {  
  302.                     
  303.   
  304.           out = editor.newOutputStream(DISK_CACHE_INDEX);  
  305.    
  306.   
  307.                            bitmap.compress(  
  308.                  
  309.   
  310.                      mCacheParams.compressFormat,   
  311.   
  312. mCacheParams.compressQuality, out);  
  313.                          
  314.   
  315.      editor.commit();  
  316.                               
  317.   
  318. out.close();  
  319.                         }  
  320.                       
  321.   
  322. else {  
  323.                         snapshot.getInputStream  
  324.   
  325. (DISK_CACHE_INDEX).close();  
  326.                     }  
  327.             
  328.   
  329.       } catch (final IOException e) {  
  330.                       
  331.   
  332. Log.e(TAG, "addBitmapToCache - " + e);  
  333.                 }   
  334.   
  335. catch (Exception e) {  
  336.                     Log.e(TAG,   
  337.   
  338. "addBitmapToCache - " + e);  
  339.                 } finally {  
  340.       
  341.   
  342.                 try {  
  343.                         if (out !=   
  344.   
  345. null) {  
  346.                             out.close();  
  347.              
  348.   
  349.              }  
  350.                     } catch (IOException e)   
  351.   
  352. {}  
  353.                 }  
  354.             }  
  355.         }  
  356.     }  
  357.   
  358.     /** 
  359.       
  360.  
  361. * Get from memory cache. 
  362.      * 
  363.      * @param data Unique  
  364.  
  365. identifier for which item to get 
  366.      * @return The bitmap  
  367.  
  368. if found in cache, null otherwise 
  369.      */  
  370.     public Bitmap   
  371.   
  372. getBitmapFromMemCache(String data) {  
  373.         if   
  374.   
  375. (mMemoryCache != null) {  
  376.             final Bitmap   
  377.   
  378. memBitmap = mMemoryCache.get(data);  
  379.             if   
  380.   
  381. (memBitmap != null) {  
  382.                 return memBitmap;  
  383.       
  384.   
  385.         }  
  386.         }  
  387.         return null;  
  388.     }  
  389.   
  390.     /** 
  391.      *  
  392.  
  393. @param data 
  394.      * @return 
  395.      */  
  396.     public Bitmap   
  397.   
  398. getBitmapFromDiskCache(String data) {  
  399.         final   
  400.   
  401. String key = FileNameGenerator.generator(data);  
  402.           
  403.   
  404. synchronized (mDiskCacheLock) {  
  405.             while   
  406.   
  407. (mDiskCacheStarting) {  
  408.                 try {  
  409.                  
  410.   
  411.      mDiskCacheLock.wait();  
  412.                 } catch   
  413.   
  414. (InterruptedException e) {}  
  415.             }  
  416.             if   
  417.   
  418. (mDiskLruCache != null) {  
  419.                 InputStream   
  420.   
  421. inputStream = null;  
  422.                 try {  
  423.                     
  424.   
  425.   final LruDiskCache.Snapshot snapshot =   
  426.   
  427. mDiskLruCache.get(key);  
  428.                     if (snapshot   
  429.   
  430. != null) {  
  431.                         inputStream =   
  432.   
  433. snapshot.getInputStream(DISK_CACHE_INDEX);  
  434.                   
  435.   
  436.         if (inputStream != null) {  
  437.                           
  438.   
  439.     final Bitmap bitmap = BitmapFactory.decodeStream  
  440.   
  441. (inputStream);  
  442.                             return bitmap;  
  443.     
  444.   
  445.                       }  
  446.                     }  
  447.                 
  448.   
  449.   } catch (final IOException e) {  
  450.                       
  451.   
  452. Log.e(TAG, "getBitmapFromDiskCache - " + e);  
  453.                 
  454.   
  455.   } finally {  
  456.                     try {  
  457.                       
  458.   
  459.     if (inputStream != null) {  
  460.                               
  461.   
  462. inputStream.close();  
  463.                         }  
  464.                
  465.   
  466.        } catch (IOException e) {}  
  467.                 }  
  468.           
  469.   
  470.     }  
  471.             return null;  
  472.         }  
  473.     }  
  474.   
  475.     /** 
  476.      *  
  477.  
  478. Clears both the memory and disk cache associated with  
  479.  
  480. this ImageCache object. Note that 
  481.      * this includes  
  482.  
  483. disk access so this should not be executed on the main/UI  
  484.  
  485. thread. 
  486.      */  
  487.     public void clearCache() {  
  488.           
  489.   
  490. clearMemoryCache();  
  491.         synchronized (mDiskCacheLock)   
  492.   
  493. {  
  494.             mDiskCacheStarting = true;  
  495.             if   
  496.   
  497. (mDiskLruCache != null && !mDiskLruCache.isClosed()) {  
  498.       
  499.   
  500.             try {  
  501.                       
  502.   
  503. mDiskLruCache.delete();  
  504.                 } catch   
  505.   
  506. (IOException e) {  
  507.                     Log.e(TAG,   
  508.   
  509. "clearCache - " + e);  
  510.                 }  
  511.                   
  512.   
  513. mDiskLruCache = null;  
  514.                 initDiskCache();  
  515.        
  516.   
  517.        }  
  518.         }  
  519.     }  
  520.       
  521.     public void   
  522.   
  523. clearMemoryCache(){  
  524.         if (mMemoryCache != null) {  
  525.          
  526.   
  527.      mMemoryCache.evictAll();  
  528.         }  
  529.     }  
  530.   
  531.     /** 
  532.      *  
  533.  
  534. Flushes the disk cache associated with this ImageCache  
  535.  
  536. object. Note that this includes 
  537.      * disk access so this  
  538.  
  539. should not be executed on the main/UI thread. 
  540.      */  
  541.       
  542.   
  543. public void flush() {  
  544.         synchronized   
  545.   
  546. (mDiskCacheLock) {  
  547.             if (mDiskLruCache != null)   
  548.   
  549. {  
  550.                 try {  
  551.                       
  552.   
  553. mDiskLruCache.flush();  
  554.                 } catch   
  555.   
  556. (IOException e) {  
  557.                     Log.e(TAG, "flush -   
  558.   
  559. " + e);  
  560.                 }  
  561.             }  
  562.         }  
  563.     }  
  564.   
  565.       
  566.   
  567. /** 
  568.      * Closes the disk cache associated with this  
  569.  
  570. ImageCache object. Note that this includes 
  571.      * disk  
  572.  
  573. access so this should not be executed on the main/UI  
  574.  
  575. thread. 
  576.      */  
  577.     public void close() {  
  578.           
  579.   
  580. synchronized (mDiskCacheLock) {  
  581.             if   
  582.   
  583. (mDiskLruCache != null) {  
  584.                 try {  
  585.               
  586.   
  587.         if (!mDiskLruCache.isClosed()) {  
  588.                     
  589.   
  590.       mDiskLruCache.close();  
  591.                           
  592.   
  593. mDiskLruCache = null;  
  594.                     }  
  595.                   
  596.   
  597. catch (IOException e) {  
  598.                     Log.e(TAG,   
  599.   
  600. "close - " + e);  
  601.                 }  
  602.             }  
  603.         }  
  604.      
  605.   
  606.  }  
  607.   
  608.     /** 
  609.      * A holder class that contains cache  
  610.  
  611. parameters. 
  612.      */  
  613.     public static class   
  614.   
  615. ImageCacheParams {  
  616.         public int memCacheSize =   
  617.   
  618. DEFAULT_MEM_CACHE_SIZE;  
  619.         public int diskCacheSize =   
  620.   
  621. DEFAULT_DISK_CACHE_SIZE;  
  622.         public File diskCacheDir;  
  623.    
  624.   
  625.        public CompressFormat compressFormat =   
  626.   
  627. DEFAULT_COMPRESS_FORMAT;  
  628.         public int   
  629.   
  630. compressQuality = DEFAULT_COMPRESS_QUALITY;  
  631.         public   
  632.   
  633. boolean memoryCacheEnabled = DEFAULT_MEM_CACHE_ENABLED;  
  634.      
  635.   
  636.      public boolean diskCacheEnabled =   
  637.   
  638. DEFAULT_DISK_CACHE_ENABLED;  
  639.         public boolean   
  640.   
  641. clearDiskCacheOnStart =   
  642.   
  643. DEFAULT_CLEAR_DISK_CACHE_ON_START;  
  644.         public boolean   
  645.   
  646. initDiskCacheOnCreate =   
  647.   
  648. DEFAULT_INIT_DISK_CACHE_ON_CREATE;  
  649.   
  650.   
  651.         public   
  652.   
  653. ImageCacheParams(File diskCacheDir) {  
  654.               
  655.   
  656. this.diskCacheDir = diskCacheDir;  
  657.         }  
  658.           
  659.           
  660.   
  661. public ImageCacheParams(String diskCacheDir) {  
  662.               
  663.   
  664. this.diskCacheDir = new File(diskCacheDir);  
  665.         }  
  666.   
  667.         
  668.   
  669.   /** 
  670.          * @param context棿 
  671.          */  
  672.         public   
  673.   
  674. void setMemCacheSizePercent(Context context, float   
  675.   
  676. percent) {  
  677.             if (percent < 0.05f || percent >   
  678.   
  679. 0.8f) {  
  680.                 throw new   
  681.   
  682. IllegalArgumentException("setMemCacheSizePercent -   
  683.   
  684. percent must be "  
  685.                         + "between 0.05   
  686.   
  687. and 0.8 (inclusive)");  
  688.             }  
  689.               
  690.   
  691. memCacheSize = Math.round(percent * getMemoryClass  
  692.   
  693. (context) * 1024 * 1024);  
  694.         }  
  695.           
  696.           
  697.           
  698.   
  699. public void setMemCacheSize(int memCacheSize) {  
  700.               
  701.   
  702. this.memCacheSize = memCacheSize;  
  703.         }  
  704.   
  705.           
  706.   
  707. public void setDiskCacheSize(int diskCacheSize) {  
  708.           
  709.   
  710.     this.diskCacheSize = diskCacheSize;  
  711.         }  
  712.   
  713.       
  714.   
  715.     private static int getMemoryClass(Context   
  716.   
  717. context) {  
  718.             return ((ActivityManager)   
  719.   
  720. context.getSystemService(  
  721.                       
  722.   
  723. Context.ACTIVITY_SERVICE)).getMemoryClass();  
  724.         }  
  725.       
  726.   
  727. }  
  728.   
  729.       
  730.   
  731. }  

图像处理类

[java] view plaincopy
  1. public class BitmapCommonUtils {  
  2.       
  3.     private static final String TAG = "BitmapCommonUtils";  
  4.       
  5.     /** 
  6.      * @param context 
  7.      * @return 
  8.      */  
  9.     public static File getDiskCacheDir(Context context, String uniqueName) {  
  10.         final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ?   
  11.                         getExternalCacheDir(context).getPath() : context.getCacheDir().getPath();  
  12.   
  13.         return new File(cachePath + File.separator + uniqueName);  
  14.     }  
  15.   
  16.     
  17.   
  18.     /** 
  19.      * @param bitmap 
  20.      * @return 
  21.      */  
  22.     public static int getBitmapSize(Bitmap bitmap) {  
  23.         return bitmap.getRowBytes() * bitmap.getHeight();  
  24.     }  
  25.   
  26.   
  27.    /** 
  28.     * @param context 
  29.     * @return 
  30.     */  
  31.     public static File getExternalCacheDir(Context context) {  
  32.         final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";  
  33.         return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);  
  34.     }  
  35.   
  36.     /** 
  37.      * @param path 
  38.      * @return 
  39.      */  
  40.     public static long getUsableSpace(File path) {  
  41.         try{  
  42.              final StatFs stats = new StatFs(path.getPath());  
  43.              return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();  
  44.         }catch (Exception e) {  
  45.               
  46.             e.printStackTrace();  
  47.             return -1;  
  48.         }  
  49.          
  50.     }  
  51.   
  52. }  
图像Decoder类

[java] view plaincopy
  1. public class BitmapDecoder {  
  2.     private static final String TAG = "BitmapDecoder";  
  3.     private BitmapDecoder(){}  
  4.   
  5.     public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,int reqWidth, int reqHeight) {  
  6.   
  7.         final BitmapFactory.Options options = new BitmapFactory.Options();  
  8.         options.inJustDecodeBounds = true;  
  9.         options.inPurgeable = true;  
  10.         BitmapFactory.decodeResource(res, resId, options);  
  11.         options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);  
  12.         options.inJustDecodeBounds = false;  
  13.         try {  
  14.               return BitmapFactory.decodeResource(res, resId, options);  
  15.         } catch (OutOfMemoryError e) {  
  16.              e.printStackTrace();  
  17.              return null;  
  18.         }  
  19.     }  
  20.   
  21.     public static Bitmap decodeSampledBitmapFromFile(String filename,int reqWidth, int reqHeight) {  
  22.         final BitmapFactory.Options options = new BitmapFactory.Options();  
  23.         options.inJustDecodeBounds = true;  
  24.         options.inPurgeable = true;  
  25.         BitmapFactory.decodeFile(filename, options);  
  26.         options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);  
  27.         options.inJustDecodeBounds = false;  
  28.         try {  
  29.               return BitmapFactory.decodeFile(filename, options);  
  30.         } catch (OutOfMemoryError e) {  
  31.              e.printStackTrace();  
  32.              return null;  
  33.         }  
  34.     }  
  35.   
  36.     public static Bitmap decodeSampledBitmapFromDescriptor(FileDescriptor fileDescriptor, int reqWidth, int reqHeight) {  
  37.   
  38.         final BitmapFactory.Options options = new BitmapFactory.Options();  
  39.         options.inJustDecodeBounds = true;  
  40.         options.inPurgeable = true;  
  41.         BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);  
  42.         options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);  
  43.         options.inJustDecodeBounds = false;  
  44.         try {  
  45.              return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);  
  46.         } catch (OutOfMemoryError e) {  
  47.             // Log.e(TAG, "decodeSampledBitmapFromDescriptor");  
  48.              e.printStackTrace();  
  49.              return null;  
  50.         }  
  51.     }  
  52.   
  53.     public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {  
  54.         final int height = options.outHeight;  
  55.         final int width = options.outWidth;  
  56.         int inSampleSize = 1;  
  57.   
  58.         if (height > reqHeight || width > reqWidth) {  
  59.             if (width > height) {  
  60.                 inSampleSize = Math.round((float) height / (float) reqHeight);  
  61.             } else {  
  62.                 inSampleSize = Math.round((float) width / (float) reqWidth);  
  63.             }  
  64.   
  65.             final float totalPixels = width * height;  
  66.   
  67.             final float totalReqPixelsCap = reqWidth * reqHeight * 2;  
  68.   
  69.             while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {  
  70.                 inSampleSize++;  
  71.             }  
  72.         }  
  73.         return inSampleSize;  
  74.     }  
  75. }  
图像显示配置类

[java] view plaincopy
  1. public class BitmapDisplayConfig {  
  2.       
  3.       
  4.     private int bitmapWidth;  
  5.     private int bitmapHeight;  
  6.       
  7.     private Animation animation;  
  8.       
  9.     private int animationType;  
  10.     private Bitmap loadingBitmap;  
  11.     private Bitmap loadfailBitmap;  
  12.       
  13.   
  14.     public int getBitmapWidth() {  
  15.         return bitmapWidth;  
  16.     }  
  17.   
  18.     public void setBitmapWidth(int bitmapWidth) {  
  19.         this.bitmapWidth = bitmapWidth;  
  20.     }  
  21.   
  22.     public int getBitmapHeight() {  
  23.         return bitmapHeight;  
  24.     }  
  25.   
  26.     public void setBitmapHeight(int bitmapHeight) {  
  27.         this.bitmapHeight = bitmapHeight;  
  28.     }  
  29.   
  30.     public Animation getAnimation() {  
  31.         return animation;  
  32.     }  
  33.   
  34.     public void setAnimation(Animation animation) {  
  35.         this.animation = animation;  
  36.     }  
  37.   
  38.     public int getAnimationType() {  
  39.         return animationType;  
  40.     }  
  41.   
  42.     public void setAnimationType(int animationType) {  
  43.         this.animationType = animationType;  
  44.     }  
  45.   
  46.     public Bitmap getLoadingBitmap() {  
  47.         return loadingBitmap;  
  48.     }  
  49.   
  50.     public void setLoadingBitmap(Bitmap loadingBitmap) {  
  51.         this.loadingBitmap = loadingBitmap;  
  52.     }  
  53.   
  54.     public Bitmap getLoadfailBitmap() {  
  55.         return loadfailBitmap;  
  56.     }  
  57.   
  58.     public void setLoadfailBitmap(Bitmap loadfailBitmap) {  
  59.         this.loadfailBitmap = loadfailBitmap;  
  60.     }  
  61.   
  62.       
  63.     public class AnimationType{  
  64.         public static final int userDefined = 0;  
  65.         public static final int fadeIn = 1;  
  66.     }  
  67.   
  68. }  


图像流读取类

[java] view plaincopy
  1. public class BitmapProcess {  
  2.     private static final String TAG = "BitmapProcess";  
  3.     private boolean mHttpDiskCacheStarting = true;  
  4.     private int cacheSize;  
  5.     private static final int DEFAULT_CACHE_SIZE = 20 * 1024 * 1024// 20MB  
  6.   
  7.     private LruDiskCache mOriginalDiskCache;  
  8.     private final Object mHttpDiskCacheLock = new Object();  
  9.     private static final int DISK_CACHE_INDEX = 0;  
  10.   
  11.     private File mOriginalCacheDir;  
  12.     private Downloader downloader;  
  13.       
  14.     private boolean neverCalculate = false;  
  15.   
  16.     public BitmapProcess(Downloader downloader,String filePath,int cacheSize) {  
  17.         this.mOriginalCacheDir = new File(filePath+"/original");  
  18.         this.downloader = downloader;  
  19.         if(cacheSize<=0)  
  20.             cacheSize = DEFAULT_CACHE_SIZE;  
  21.         this.cacheSize = cacheSize;  
  22.     }  
  23.       
  24.     public void configCalculateBitmap(boolean neverCalculate){  
  25.         this.neverCalculate = neverCalculate;  
  26.     }  
  27.   
  28.     public Bitmap processBitmap(String data, BitmapDisplayConfig config) {  
  29.         final String key = FileNameGenerator.generator(data);  
  30.         FileDescriptor fileDescriptor = null;  
  31.         FileInputStream fileInputStream = null;  
  32.         LruDiskCache.Snapshot snapshot;  
  33.         synchronized (mHttpDiskCacheLock) {  
  34.             // Wait for disk cache to initialize  
  35.             while (mHttpDiskCacheStarting) {  
  36.                 try {  
  37.                     mHttpDiskCacheLock.wait();  
  38.                 } catch (InterruptedException e) {  
  39.                 }  
  40.             }  
  41.   
  42.             if (mOriginalDiskCache != null) {  
  43.                 try {  
  44.                     snapshot = mOriginalDiskCache.get(key);  
  45.                     if (snapshot == null) {  
  46.                         LruDiskCache.Editor editor = mOriginalDiskCache.edit(key);  
  47.                         if (editor != null) {  
  48.                             if (downloader.downloadToLocalStreamByUrl(data,editor.newOutputStream(DISK_CACHE_INDEX))) {  
  49.                                 editor.commit();  
  50.                             } else {  
  51.                                 editor.abort();  
  52.                             }  
  53.                         }  
  54.                         snapshot = mOriginalDiskCache.get(key);  
  55.                     }  
  56.                     if (snapshot != null) {  
  57.                         fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);  
  58.                         fileDescriptor = fileInputStream.getFD();  
  59.                     }  
  60.                 } catch (IOException e) {  
  61.                     Log.e(TAG, "processBitmap - " + e);  
  62.                 } catch (IllegalStateException e) {  
  63.                     Log.e(TAG, "processBitmap - " + e);  
  64.                 } finally {  
  65.                     if (fileDescriptor == null && fileInputStream != null) {  
  66.                         try {  
  67.                             fileInputStream.close();  
  68.                         } catch (IOException e) {  
  69.                         }  
  70.                     }  
  71.                 }  
  72.             }  
  73.         }  
  74.   
  75.         Bitmap bitmap = null;  
  76.         if (fileDescriptor != null) {  
  77.             if(neverCalculate)  
  78.                 bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);  
  79.             else  
  80.                 bitmap = BitmapDecoder.decodeSampledBitmapFromDescriptor(fileDescriptor, config.getBitmapWidth(),config.getBitmapHeight());  
  81.         }  
  82.         if (fileInputStream != null) {  
  83.             try {  
  84.                 fileInputStream.close();  
  85.             } catch (IOException e) {  
  86.             }  
  87.         }  
  88.         return bitmap;  
  89.     }  
  90.   
  91.     public void initHttpDiskCache() {  
  92.         if (!mOriginalCacheDir.exists()) {  
  93.             mOriginalCacheDir.mkdirs();  
  94.         }  
  95.         synchronized (mHttpDiskCacheLock) {  
  96.             if (BitmapCommonUtils.getUsableSpace(mOriginalCacheDir) > cacheSize) {  
  97.                 try {  
  98.                     mOriginalDiskCache = LruDiskCache.open(mOriginalCacheDir, 11,cacheSize);  
  99.                 } catch (IOException e) {  
  100.                     mOriginalDiskCache = null;  
  101.                 }  
  102.             }  
  103.             mHttpDiskCacheStarting = false;  
  104.             mHttpDiskCacheLock.notifyAll();  
  105.         }  
  106.     }  
  107.   
  108.     public void clearCacheInternal() {  
  109.         synchronized (mHttpDiskCacheLock) {  
  110.             if (mOriginalDiskCache != null && !mOriginalDiskCache.isClosed()) {  
  111.                 try {  
  112.                     mOriginalDiskCache.delete();  
  113.                 } catch (IOException e) {  
  114.                     Log.e(TAG, "clearCacheInternal - " + e);  
  115.                 }  
  116.                 mOriginalDiskCache = null;  
  117.                 mHttpDiskCacheStarting = true;  
  118.                 initHttpDiskCache();  
  119.             }  
  120.         }  
  121.     }  
  122.   
  123.     public void flushCacheInternal() {  
  124.         synchronized (mHttpDiskCacheLock) {  
  125.             if (mOriginalDiskCache != null) {  
  126.                 try {  
  127.                     mOriginalDiskCache.flush();  
  128.                 } catch (IOException e) {  
  129.                     Log.e(TAG, "flush - " + e);  
  130.                 }  
  131.             }  
  132.         }  
  133.     }  
  134.   
  135.     public void closeCacheInternal() {  
  136.         synchronized (mHttpDiskCacheLock) {  
  137.             if (mOriginalDiskCache != null) {  
  138.                 try {  
  139.                     if (!mOriginalDiskCache.isClosed()) {  
  140.                         mOriginalDiskCache.close();  
  141.                         mOriginalDiskCache = null;  
  142.                     }  
  143.                 } catch (IOException e) {  
  144.                     Log.e(TAG, "closeCacheInternal - " + e);  
  145.                 }  
  146.             }  
  147.         }  
  148.     }  
  149.       
  150.       
  151. }  

下载类

[java] view plaincopy
  1. public interface Downloader  {  
  2.       
  3.     public boolean downloadToLocalStreamByUrl(String urlString, OutputStream outputStream);  
  4. }  


[java] view plaincopy
  1. public class SimpleHttpDownloader implements Downloader{  
  2.       
  3.     private static final String TAG = "BitmapDownloader";  
  4.       
  5.     private static final int IO_BUFFER_SIZE = 8 * 1024//8k  
  6.       
  7.      public boolean downloadToLocalStreamByUrl(String urlString, OutputStream outputStream) {  
  8.             HttpURLConnection urlConnection = null;  
  9.             BufferedOutputStream out = null;  
  10.             FlushedInputStream in = null;  
  11.   
  12.             try {  
  13.                 final URL url = new URL(urlString);  
  14.                 urlConnection = (HttpURLConnection) url.openConnection();  
  15.                 in = new FlushedInputStream(new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE));  
  16.                 out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);  
  17.   
  18.                 int b;  
  19.                 while ((b = in.read()) != -1) {  
  20.                     out.write(b);  
  21.                 }  
  22.                 return true;  
  23.             } catch (final IOException e) {  
  24.                 Log.e(TAG, "Error in downloadBitmap - "+urlString +" : " + e);  
  25.             } finally {  
  26.                 if (urlConnection != null) {  
  27.                     urlConnection.disconnect();  
  28.                 }  
  29.                 try {  
  30.                     if (out != null) {  
  31.                         out.close();  
  32.                     }  
  33.                     if (in != null) {  
  34.                         in.close();  
  35.                     }  
  36.                 } catch (final IOException e) {}  
  37.             }  
  38.             return false;  
  39.         }  
  40.   
  41.           
  42.         public class FlushedInputStream extends FilterInputStream {  
  43.   
  44.             public FlushedInputStream(InputStream inputStream) {  
  45.                 super(inputStream);  
  46.             }  
  47.   
  48.             @Override  
  49.             public long skip(long n) throws IOException {  
  50.                 long totalBytesSkipped = 0L;  
  51.                 while (totalBytesSkipped < n) {  
  52.                     long bytesSkipped = in.skip(n - totalBytesSkipped);  
  53.                     if (bytesSkipped == 0L) {  
  54.                         int by_te = read();  
  55.                         if (by_te < 0) {  
  56.                             break// we reached EOF  
  57.                         } else {  
  58.                             bytesSkipped = 1// we read one byte  
  59.                         }  
  60.                     }  
  61.                     totalBytesSkipped += bytesSkipped;  
  62.                 }  
  63.                 return totalBytesSkipped;  
  64.             }  
  65.         }  
  66. }  
出自:http://blog.csdn.net/krislight/article/details/11354119
0 0
原创粉丝点击