Compare commits

..

6 Commits

Author SHA1 Message Date
zgx 1d573de296 张稼辉的博客
2 months ago
zgx bdcf780c23 周高雄的博客
2 months ago
zgx 9715e1eec1 运行结果
2 months ago
zgx b580a8984d 报告
2 months ago
zgx ac5ef22e71 111
4 months ago
zgx aa8ad9e67c 111
4 months ago

@ -1 +0,0 @@
1111

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 233 KiB

Binary file not shown.

@ -16,7 +16,7 @@
package net.micode.notes.data;//导入包 package net.micode.notes.data;//导入包
import android.content.Context;// import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Data;
@ -24,32 +24,19 @@ import android.telephony.PhoneNumberUtils;
import android.util.Log; import android.util.Log;
import java.util.HashMap; import java.util.HashMap;
/**
* public class Contact {//创建类
*/
public class Contact {
// 静态缓存,用于存储电话号码与对应联系人名称的映射关系,避免重复查询数据库
private static HashMap<String, String> sContactCache; private static HashMap<String, String> sContactCache;
// 日志标签
private static final String TAG = "Contact"; private static final String TAG = "Contact";
// 查询条件模板:
// 1. 使用PHONE_NUMBERS_EQUAL比较电话号码考虑格式差异
// 2. 数据类型为电话条目
// 3. 限制raw_contact_id必须在phone_lookup表中匹配指定最小匹配长度的记录
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN " + " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id " + "(SELECT raw_contact_id "
+ " FROM phone_lookup" + " FROM phone_lookup"
+ " WHERE min_match = '+')"; + " WHERE min_match = '+')";
/**
*
* @param context 访
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) { public static String getContact(Context context, String phoneNumber) {
// 初始化缓存
if(sContactCache == null) { if(sContactCache == null) {
sContactCache = new HashMap<String, String>(); sContactCache = new HashMap<String, String>();
} }
@ -57,30 +44,26 @@ public class Contact {
if(sContactCache.containsKey(phoneNumber)) { if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber); return sContactCache.get(phoneNumber);
} }
// 优先从缓存中获取
String selection = CALLER_ID_SELECTION.replace("+", String selection = CALLER_ID_SELECTION.replace("+",
// 构造完整查询条件:替换最小匹配长度参数
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 通过内容解析器查询联系人数据库
Cursor cursor = context.getContentResolver().query( Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,// 访问组合联系人数据 Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },// 查询显示名字段 new String [] { Phone.DISPLAY_NAME },
selection,// 动态生成的查询条件 selection,
new String[] { phoneNumber },// 查询参数(原始电话号码) new String[] { phoneNumber },
null);// 排序方式(无) null);
// 处理查询结果
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
// 获取第一条记录的显示名称
String name = cursor.getString(0); String name = cursor.getString(0);
// 更新缓存
sContactCache.put(phoneNumber, name); sContactCache.put(phoneNumber, name);
return name; return name;
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString()); Log.e(TAG, " Cursor get string error " + e.toString());
return null; return null;
} finally { } finally {
cursor.close();// 确保关闭Cursor释放资源 cursor.close();
} }
} else { } else {
Log.d(TAG, "No contact matched with number:" + phoneNumber); Log.d(TAG, "No contact matched with number:" + phoneNumber);

@ -14,77 +14,266 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.data;//导入包 package net.micode.notes.data;
import android.content.Context;// import android.net.Uri;
import android.database.Cursor; public class Notes {//定义类
import android.provider.ContactsContract.CommonDataKinds.Phone; public static final String AUTHORITY = "micode_notes";
import android.provider.ContactsContract.Data; public static final String TAG = "Notes";
import android.telephony.PhoneNumberUtils; public static final int TYPE_NOTE = 0;
import android.util.Log; public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
import java.util.HashMap;
/** /**
* * Following IDs are system folders' identifiers
*/ * {@link Notes#ID_ROOT_FOLDER } is default folder
public class Contact { * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
// 静态缓存,用于存储电话号码与对应联系人名称的映射关系,避免重复查询数据库 * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
private static HashMap<String, String> sContactCache; */
// 日志标签 public static final int ID_ROOT_FOLDER = 0;
private static final String TAG = "Contact"; public static final int ID_TEMPARAY_FOLDER = -1;
// 查询条件模板: public static final int ID_CALL_RECORD_FOLDER = -2;
// 1. 使用PHONE_NUMBERS_EQUAL比较电话号码考虑格式差异 public static final int ID_TRASH_FOLER = -3;
// 2. 数据类型为电话条目
// 3. 限制raw_contact_id必须在phone_lookup表中匹配指定最小匹配长度的记录 public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
+ " AND " + Data.RAW_CONTACT_ID + " IN " public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
+ "(SELECT raw_contact_id " public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
+ " FROM phone_lookup" public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
+ " WHERE min_match = '+')";
/** public static final int TYPE_WIDGET_INVALIDE = -1;
* public static final int TYPE_WIDGET_2X = 0;
* @param context 访 public static final int TYPE_WIDGET_4X = 1;
* @param phoneNumber
* @return null public static class DataConstants {
*/ public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static String getContact(Context context, String phoneNumber) { public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
// 初始化缓存
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
} }
if(sContactCache.containsKey(phoneNumber)) { /**
return sContactCache.get(phoneNumber); * Uri to query all notes and folders
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri to query data
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
public interface NoteColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
*/
public static final String SNIPPET = "snippet";
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
* For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P> Type: INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
*/
public static final String TYPE = "type";
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id";
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P> Type : INTEGER (long) </P>
*/
public static final String VERSION = "version";
} }
// 优先从缓存中获取
String selection = CALLER_ID_SELECTION.replace("+", public interface DataColumns {
// 构造完整查询条件:替换最小匹配长度参数 /**
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); * The unique ID for a row
// 通过内容解析器查询联系人数据库 * <P> Type: INTEGER (long) </P>
Cursor cursor = context.getContentResolver().query( */
Data.CONTENT_URI,// 访问组合联系人数据 public static final String ID = "_id";
new String [] { Phone.DISPLAY_NAME },// 查询显示名字段
selection,// 动态生成的查询条件 /**
new String[] { phoneNumber },// 查询参数(原始电话号码) * The MIME type of the item represented by this row.
null);// 排序方式(无) * <P> Type: Text </P>
// 处理查询结果 */
if (cursor != null && cursor.moveToFirst()) { public static final String MIME_TYPE = "mime_type";
try {
// 获取第一条记录的显示名称 /**
String name = cursor.getString(0); * The reference id to note that this data belongs to
// 更新缓存 * <P> Type: INTEGER (long) </P>
sContactCache.put(phoneNumber, name); */
return name; public static final String NOTE_ID = "note_id";
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString()); /**
return null; * Created data for note or folder
} finally { * <P> Type: INTEGER (long) </P>
cursor.close();// 确保关闭Cursor释放资源 */
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Data's content
* <P> Type: TEXT </P>
*/
public static final String CONTENT = "content";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA1 = "data1";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA2 = "data2";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA3 = "data3";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA5 = "data5";
} }
} else {
Log.d(TAG, "No contact matched with number:" + phoneNumber); public static final class TextNote implements DataColumns {
return null; /**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
*/
public static final String MODE = DATA1;
public static final int MODE_CHECK_LIST = 1;
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
} }
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
*/
public static final String CALL_DATE = DATA1;
/**
* Phone number for this record
* <P> Type: TEXT </P>
*/
public static final String PHONE_NUMBER = DATA3;
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
} }
} }

@ -25,69 +25,63 @@ import android.util.Log;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
/**
*
*
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper { public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 数据库元数据配置 private static final String DB_NAME = "note.db";
private static final String DB_NAME = "note.db";// 数据库文件名
private static final int DB_VERSION = 4;
private static final int DB_VERSION = 4;// 当前数据库版本
// 表名常量接口
public interface TABLE { public interface TABLE {
public static final String NOTE = "note";// 主表:存储笔记元信息(标题、创建时间、父目录等) public static final String NOTE = "note";
public static final String DATA = "data";// 数据表:存储笔记具体内容及扩展数据 public static final String DATA = "data";
} }
private static final String TAG = "NotesDatabaseHelper";// 日志标签 private static final String TAG = "NotesDatabaseHelper";
private static NotesDatabaseHelper mInstance;
private static NotesDatabaseHelper mInstance; // 单例实例
// Note表建表语句
private static final String CREATE_NOTE_TABLE_SQL = private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" + "CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +// 笔记唯一标识 NoteColumns.ID + " INTEGER PRIMARY KEY," +
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +// 所属文件夹ID树形结构 NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +// 提醒时间(毫秒时间戳) NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +// 背景颜色标识 NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +// 是否有附件0/1布尔值 NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +// 最后修改时间 NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + // 子项数量(用于文件夹) NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +// 内容摘要 NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + // 笔记类型(普通笔记、文件夹等) NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +// 关联的小部件ID NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +// 小部件类型 NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +// 同步标识 NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +// 本地修改标记 NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +// 原始父目录(用于同步) NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +// Google Task关联ID NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 数据版本号(乐观锁) NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")"; ")";
// Data表建表语句
private static final String CREATE_DATA_TABLE_SQL = private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" + "CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +// 数据项唯一标识 DataColumns.ID + " INTEGER PRIMARY KEY," +
DataColumns.MIME_TYPE + " TEXT NOT NULL," +// MIME类型文本、清单、媒体等 DataColumns.MIME_TYPE + " TEXT NOT NULL," +
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联的笔记ID DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +// 同步创建时间 NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +// 同步修改时间 NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +// 主要内容存储 DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA1 + " INTEGER," +// 扩展字段1类型相关数据 DataColumns.DATA1 + " INTEGER," +
DataColumns.DATA2 + " INTEGER," +// 扩展字段2如清单项状态 DataColumns.DATA2 + " INTEGER," +
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +// 扩展字段3如地理位置 DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +// 扩展字段4如附件路径 DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +// 扩展字段5保留字段 DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")"; ")";
// 数据表索引加速按笔记ID查询数据项
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " + "CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
// 触发器:当更新笔记的父目录时,增加新文件夹的计数
// 场景示例把笔记A从文件夹X移动到文件夹Y时Y的计数+1
/** /**
* Increase folder's note count when move note to the folder * Increase folder's note count when move note to the folder
*/ */
@ -99,8 +93,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END"; " END";
// 触发器:当更新笔记的父目录时,减少原文件夹的计数
// 场景示例同上移动操作时X的计数-1需>0时生效
/** /**
* Decrease folder's note count when move note from folder * Decrease folder's note count when move note from folder
*/ */
@ -113,7 +106,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END"; " END";
// 触发器:插入新笔记时增加所在文件夹的计数
/** /**
* Increase folder's note count when insert new note to the folder * Increase folder's note count when insert new note to the folder
*/ */
@ -125,7 +118,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END"; " END";
// 触发器:删除笔记时减少原文件夹的计数(防止负数)
/** /**
* Decrease folder's note count when delete note from the folder * Decrease folder's note count when delete note from the folder
*/ */
@ -138,42 +131,33 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" + " AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END"; " END";
/**
* NOTE
* datanotesnippet
*/
/** /**
* Update note's content when insert data with type {@link DataConstants#NOTE} * Update note's content when insert data with type {@link DataConstants#NOTE}
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " + "CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA + " AFTER INSERT ON " + TABLE.DATA +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +// 仅处理普通笔记类型 " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" + " BEGIN" +
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +// 使用新插入的内容更新摘要 " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +// 通过NOTE_ID关联 " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END"; " END";
/**
* NOTE
*
*/
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has changed * Update note's content when data with {@link DataConstants#NOTE} type has changed
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " + "CREATE TRIGGER update_note_content_on_update " +
" AFTER UPDATE ON " + TABLE.DATA + " AFTER UPDATE ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +// 仅处理原类型为笔记的记录 " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" + " BEGIN" +
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +// 同步最新内容到摘要 " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END"; " END";
/**
* NOTE
*
*/
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted * Update note's content when data with {@link DataConstants#NOTE} type has deleted
*/ */
@ -183,14 +167,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" + " BEGIN" +
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=''" +// 清空摘要内容 " SET " + NoteColumns.SNIPPET + "=''" +
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
" END"; " END";
/**
*
* notedata
*
*/
/** /**
* Delete datas belong to note which has been deleted * Delete datas belong to note which has been deleted
*/ */
@ -199,13 +179,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" + " BEGIN" +
" DELETE FROM " + TABLE.DATA + " DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +// 根据被删除笔记ID清理数据 " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" END"; " END";
/**
*
*
* delete_data_on_delete
*/
/** /**
* Delete notes belong to folder which has been deleted * Delete notes belong to folder which has been deleted
*/ */
@ -214,33 +190,22 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" AFTER DELETE ON " + TABLE.NOTE + " AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" + " BEGIN" +
" DELETE FROM " + TABLE.NOTE + " DELETE FROM " + TABLE.NOTE +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +// 删除所有父目录为被删文件夹的笔记 " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END"; " END";
/**
*
*
*
*/
/** /**
* Move notes belong to folder which has been moved to trash folder * Move notes belong to folder which has been moved to trash folder
*/ */
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " + "CREATE TRIGGER folder_move_notes_on_trash " +
" AFTER UPDATE ON " + TABLE.NOTE + " AFTER UPDATE ON " + TABLE.NOTE +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +// 检测是否移动到回收站 " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" BEGIN" + " BEGIN" +
" UPDATE " + TABLE.NOTE + " UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +// 批量更新子项父目录为回收站 " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + // 选择原父目录下的所有笔记 " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END"; " END";
/**
*
*
* 1. ID_CALL_RECORD_FOLDER
* 2. ID_ROOT_FOLDER
* 3. ID_TEMPARAY_FOLDER
* 4. ID_TRASH_FOLER
*/
public NotesDatabaseHelper(Context context) { public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION); super(context, DB_NAME, null, DB_VERSION);
} }
@ -272,14 +237,14 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
private void createSystemFolder(SQLiteDatabase db) { private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
// 插入通话记录文件夹
/** /**
* call record foler for call notes * call record foler for call notes
*/ */
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);// 标记为系统文件夹 values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
// 插入根文件夹(默认笔记存储位置)
/** /**
* root folder which is default folder * root folder which is default folder
*/ */
@ -287,7 +252,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
// 插入临时文件夹(用于笔记移动操作时的暂存区)
/** /**
* temporary folder which is used for moving note * temporary folder which is used for moving note
*/ */
@ -295,7 +260,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
// 插入回收站(软删除数据存储位置)
/** /**
* create trash folder * create trash folder
*/ */
@ -328,13 +293,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
} }
return mInstance; return mInstance;
} }
/**
*
*
* V1 V2
* V2 V3Google Task +
* V3 V4
*/
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
createNoteTable(db); createNoteTable(db);
@ -345,72 +304,57 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false; boolean reCreateTriggers = false;
boolean skipV2 = false; boolean skipV2 = false;
// V1到V2升级策略完全重建表结构
if (oldVersion == 1) { if (oldVersion == 1) {
upgradeToV2(db); upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3// 包含V2到V3的升级逻辑 skipV2 = true; // this upgrade including the upgrade from v2 to v3
oldVersion++; oldVersion++;
} }
// V2到V3升级策略非破坏性升级
if (oldVersion == 2 && !skipV2) { if (oldVersion == 2 && !skipV2) {
upgradeToV3(db); upgradeToV3(db);
reCreateTriggers = true;// 需要重建触发器 reCreateTriggers = true;
oldVersion++; oldVersion++;
} }
// V3到V4升级策略添加版本字段
if (oldVersion == 3) { if (oldVersion == 3) {
upgradeToV4(db); upgradeToV4(db);
oldVersion++; oldVersion++;
} }
// 重建触发器(当表结构变化可能影响触发器时)
if (reCreateTriggers) { if (reCreateTriggers) {
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db);
} }
// 版本检查容错
if (oldVersion != newVersion) { if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails"); + "fails");
} }
} }
/**
* V2
*
* 1.
* 2.
* 3.
*/
private void upgradeToV2(SQLiteDatabase db) { private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
createNoteTable(db); createNoteTable(db);
createDataTable(db); createDataTable(db);
} }
/**
* V3
*
* 1.
* 2. GTASK_IDGoogle Tasks
* 3.
*/
private void upgradeToV3(SQLiteDatabase db) { private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers// 移除旧版的时间更新触发器 // drop unused triggers
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id// 添加Google Task关联字段 // add a column for gtask id
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''"); + " TEXT NOT NULL DEFAULT ''");
// add a trash system folder// 插入回收站系统文件夹 // add a trash system folder
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
} }
/**
* V4
* VERSION
*/
private void upgradeToV4(SQLiteDatabase db) { private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0"); + " INTEGER NOT NULL DEFAULT 0");

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.data; package net.micode.notes.data;//111
import android.app.SearchManager; import android.app.SearchManager;
@ -34,26 +34,22 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* ContentProvider
* CRUD
*/
public class NotesProvider extends ContentProvider { public class NotesProvider extends ContentProvider {
// URI匹配器用于路由不同数据请求
private static final UriMatcher mMatcher; private static final UriMatcher mMatcher;
private NotesDatabaseHelper mHelper;// 数据库帮助类实例 private NotesDatabaseHelper mHelper;
private static final String TAG = "NotesProvider";
private static final String TAG = "NotesProvider";// 日志标签 private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4;
private static final int URI_NOTE = 1;// 笔记集合操作 private static final int URI_SEARCH = 5;
private static final int URI_NOTE_ITEM = 2; // 单个笔记操作 private static final int URI_SEARCH_SUGGEST = 6;
private static final int URI_DATA = 3;// 数据项集合操作
private static final int URI_DATA_ITEM = 4;// 单个数据项操作
private static final int URI_SEARCH = 5; // 全文搜索
private static final int URI_SEARCH_SUGGEST = 6;// 搜索建议
// 初始化URI匹配规则
static { static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
@ -61,37 +57,30 @@ public class NotesProvider extends ContentProvider {
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
// 系统搜索建议标准URI
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
} }
/**
*
* -
* - x'0A'SQLite
*/
/** /**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result, * x'0A' represents the '\n' character in sqlite. For title and content in the search result,
* we will trim '\n' and white space in order to show more information. * we will trim '\n' and white space in order to show more information.
*/ */
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","// 原始ID private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","// 建议项携带数据 + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","// 主文本 + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," // 副文本 + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","// 建议图标 + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","// 点击动作 + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; // 数据类型 + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 笔记片段搜索SQL查询排除回收站且类型为普通笔记
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"// 模糊查询 + " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER// 过滤回收站 + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; // 仅普通笔记类型 + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override @Override
public boolean onCreate() { public boolean onCreate() {
// 初始化数据库帮助类(单例模式)
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext());
return true; return true;
} }
@ -102,53 +91,47 @@ public class NotesProvider extends ContentProvider {
Cursor c = null; Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase(); SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null; String id = null;
// 根据URI类型路由处理
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: // 查询所有笔记 case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
break; break;
case URI_NOTE_ITEM:// 查询单个笔记 case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id// 从URI路径获取ID c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder);
break; break;
case URI_DATA:// 查询所有数据项 case URI_DATA:
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
break; break;
case URI_DATA_ITEM:// 查询单个数据项 case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder);
break; break;
case URI_SEARCH:// 处理搜索请求 case URI_SEARCH:
case URI_SEARCH_SUGGEST: // 处理搜索建议请求 case URI_SEARCH_SUGGEST:
// 验证参数完整性
if (sortOrder != null || projection != null) { if (sortOrder != null || projection != null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
} }
// 解析搜索关键词
String searchString = null; String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
// 从建议URI路径获取content://auth/search_suggest_query/关键词
if (uri.getPathSegments().size() > 1) { if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1); searchString = uri.getPathSegments().get(1);
} }
} else { } else {
// 从查询参数获取content://auth/search?pattern=关键词
searchString = uri.getQueryParameter("pattern"); searchString = uri.getQueryParameter("pattern");
} }
if (TextUtils.isEmpty(searchString)) { if (TextUtils.isEmpty(searchString)) {
return null; // 空搜索直接返回 return null;
} }
try { try {
// 构造模糊查询参数(前后加%
searchString = String.format("%%%s%%", searchString); searchString = String.format("%%%s%%", searchString);
// 执行原始SQL查询参数化防止注入
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString }); new String[] { searchString });
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
@ -158,27 +141,21 @@ public class NotesProvider extends ContentProvider {
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// 设置数据变更通知URI重要使CursorLoader能自动刷新
if (c != null) { if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri); c.setNotificationUri(getContext().getContentResolver(), uri);
} }
return c; return c;
} }
/**
*
* @param uri URInotedata
* @param values
* @return URI
*/
@Override @Override
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0; long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: // 插入新笔记 case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values); insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break; break;
case URI_DATA: // 插入笔记关联数据 case URI_DATA:
if (values.containsKey(DataColumns.NOTE_ID)) { if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID); noteId = values.getAsLong(DataColumns.NOTE_ID);
} else { } else {
@ -189,55 +166,50 @@ public class NotesProvider extends ContentProvider {
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// Notify the note uri// 发送数据变更通知 // Notify the note uri
if (noteId > 0) {// 通知笔记URI变更触发CursorLoader刷新 if (noteId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
} }
// Notify the data uri// 通知数据URI变更 // Notify the data uri
if (dataId > 0) { if (dataId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
} }
// 返回新创建项的完整URI如content://auth/note/123
return ContentUris.withAppendedId(uri, insertedId); return ContentUris.withAppendedId(uri, insertedId);
} }
/**
*
* @param uri URI
* @return
*/
@Override @Override
public int delete(Uri uri, String selection, String[] selectionArgs) { public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0; int count = 0;
String id = null; String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;// 标记是否删除的是data表数据 boolean deleteData = false;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE:// 删除多个笔记 case URI_NOTE:
// 防止删除系统文件夹ID>0的条件
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs); count = db.delete(TABLE.NOTE, selection, selectionArgs);
break; break;
case URI_NOTE_ITEM:// 删除单个笔记 case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
/** /**
* ID that smaller than 0 is system folder which is not allowed to * ID that smaller than 0 is system folder which is not allowed to
* trash * trash
*/ */
long noteId = Long.valueOf(id); // 系统文件夹ID<=0不允许删除 long noteId = Long.valueOf(id);
if (noteId <= 0) { if (noteId <= 0) {
break; break;
} }
count = db.delete(TABLE.NOTE, count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break; break;
case URI_DATA:// 删除多个数据项 case URI_DATA:
count = db.delete(TABLE.DATA, selection, selectionArgs); count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true; deleteData = true;
break; break;
case URI_DATA_ITEM:// 删除单个数据项 case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA, count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
@ -246,44 +218,37 @@ public class NotesProvider extends ContentProvider {
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// 发送通知(数据变更可能影响笔记显示)
if (count > 0) { if (count > 0) {
if (deleteData) { if (deleteData) {
// 数据变更需要通知笔记列表更新
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
} // 通知当前URI对应的数据变更 }
getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(uri, null);
} }
return count; return count;
} }
/**
*
* @param uri URI
* @param values
* @return
*/
@Override @Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0; int count = 0;
String id = null; String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false;// 标记是否更新data表 boolean updateData = false;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: // 批量更新笔记 case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs); increaseNoteVersion(-1, selection, selectionArgs);
count = db.update(TABLE.NOTE, values, selection, selectionArgs); count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break; break;
case URI_NOTE_ITEM: // 更新单个笔记 case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs);
break; break;
case URI_DATA: // 更新多个数据项 case URI_DATA:
count = db.update(TABLE.DATA, values, selection, selectionArgs); count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true; updateData = true;
break; break;
case URI_DATA_ITEM:// 更新单个数据项 case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs);
@ -292,31 +257,20 @@ public class NotesProvider extends ContentProvider {
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// 发送数据变更通知
if (count > 0) { if (count > 0) {
if (updateData) { if (updateData) {
// 数据变更需要更新关联笔记
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
} }
getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(uri, null);
} }
return count; return count;
} }
/**
*
* @param selection
* @return
*/
private String parseSelection(String selection) { private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
} }
/**
*
* @param id ID-1
* @param selection
* @param selectionArgs
*/
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120); StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE "); sql.append("UPDATE ");
@ -324,13 +278,13 @@ public class NotesProvider extends ContentProvider {
sql.append(" SET "); sql.append(" SET ");
sql.append(NoteColumns.VERSION); sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 "); sql.append("=" + NoteColumns.VERSION + "+1 ");
// 构造WHERE条件
if (id > 0 || !TextUtils.isEmpty(selection)) { if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE "); sql.append(" WHERE ");
} }
if (id > 0) { if (id > 0) {
sql.append(NoteColumns.ID + "=" + String.valueOf(id)); sql.append(NoteColumns.ID + "=" + String.valueOf(id));
} // 处理选择条件(手动替换参数防止注入) }
if (!TextUtils.isEmpty(selection)) { if (!TextUtils.isEmpty(selection)) {
String selectString = id > 0 ? parseSelection(selection) : selection; String selectString = id > 0 ? parseSelection(selection) : selection;
for (String args : selectionArgs) { for (String args : selectionArgs) {
@ -338,13 +292,13 @@ public class NotesProvider extends ContentProvider {
} }
sql.append(selectString); sql.append(selectString);
} }
// 执行原生SQL更新绕过常规更新流程
mHelper.getWritableDatabase().execSQL(sql.toString()); mHelper.getWritableDatabase().execSQL(sql.toString());
} }
@Override @Override
public String getType(Uri uri) { public String getType(Uri uri) {
// TODO Auto-generated method stub// 根据URI返回MIME类型当前未实现 // TODO Auto-generated method stub
return null; return null;
} }

@ -1,130 +1,158 @@
* Activity /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package net.micode.notes.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import java.io.IOException;
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId; // 当前提醒关联的笔记ID private long mNoteId;
private String mSnippet; // 笔记内容摘要 private String mSnippet;
private static final int SNIPPET_PREW_MAX_LEN = 60; // 摘要最大显示长度 private static final int SNIPPET_PREW_MAX_LEN = 60;
MediaPlayer mPlayer; // 媒体播放器实例 MediaPlayer mPlayer;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
// 界面设置 requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题栏
final Window win = getWindow(); final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // 支持锁屏显示 win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// 屏幕唤醒策略(仅在屏幕关闭时生效)
if (!isScreenOn()) { if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON // 保持屏幕常亮 win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON // 点亮屏幕 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON // 允许锁屏 | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); // 调整窗口布局 | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
} }
// 数据初始化
Intent intent = getIntent(); Intent intent = getIntent();
try { try {
// 从Intent URI解析笔记ID格式content://xxx/notes/123
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 从数据库获取原始内容
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
// 截取前60字符超长显示省略符 mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
? mSnippet.substring(0, SNIPPET_PREW_MAX_LEN)
+ getResources().getString(R.string.notelist_string_info)
: mSnippet; : mSnippet;
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
e.printStackTrace(); e.printStackTrace();
return; // 数据异常直接退出 return;
} }
// 媒体播放初始化
mPlayer = new MediaPlayer(); mPlayer = new MediaPlayer();
// 检查笔记有效性(未被删除)
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog(); // 展示提醒对话框 showActionDialog();
playAlarmSound(); // 播放提醒音 playAlarmSound();
} else { } else {
finish(); // 笔记不存在则结束 finish();
} }
} }
// 屏幕状态检测
private boolean isScreenOn() { private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn(); // 使用电源服务判断屏幕状态 return pm.isScreenOn();
} }
// 播放提醒铃声
private void playAlarmSound() { private void playAlarmSound() {
// 获取系统默认闹钟铃声
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 静音模式兼容处理
int silentModeStreams = Settings.System.getInt(getContentResolver(), int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 判断静音模式是否影响闹钟音量
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams); mPlayer.setAudioStreamType(silentModeStreams);
} else { } else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); // 使用闹钟音量通道 mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
} }
// 播放设置
try { try {
mPlayer.setDataSource(this, url); // 设置铃声源 mPlayer.setDataSource(this, url);
mPlayer.prepare(); // 预加载资源 mPlayer.prepare();
mPlayer.setLooping(true); // 循环播放 mPlayer.setLooping(true);
mPlayer.start(); // 开始播放 mPlayer.start();
} catch (IllegalArgumentException | SecurityException } catch (IllegalArgumentException e) {
| IllegalStateException | IOException e) { // TODO Auto-generated catch block
e.printStackTrace(); // 捕获多种媒体播放异常 e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
} }
// 显示操作对话框
private void showActionDialog() { private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this); AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.app_name); // 设置应用名为标题 dialog.setTitle(R.string.app_name);
dialog.setMessage(mSnippet); // 显示内容摘要 dialog.setMessage(mSnippet);
// 主操作按钮(确认)
dialog.setPositiveButton(R.string.notealert_ok, this); dialog.setPositiveButton(R.string.notealert_ok, this);
// 仅在屏幕亮起时显示"进入"按钮
if (isScreenOn()) { if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this); dialog.setNegativeButton(R.string.notealert_enter, this);
} }
dialog.show().setOnDismissListener(this); // 绑定对话框关闭监听 dialog.show().setOnDismissListener(this);
} }
// 对话框按钮点击处理
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
switch (which) { switch (which) {
case DialogInterface.BUTTON_NEGATIVE: // "进入"按钮 case DialogInterface.BUTTON_NEGATIVE:
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW); // 查看模式 intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递笔记ID intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent); // 跳转编辑页面 startActivity(intent);
break;
default:
break; break;
// 确认按钮无需特别处理,默认关闭
} }
} }
// 对话框关闭回调
public void onDismiss(DialogInterface dialog) { public void onDismiss(DialogInterface dialog) {
stopAlarmSound(); // 停止铃声 stopAlarmSound();
finish(); // 关闭当前Activity finish();
} }
// 停止并释放媒体资源
private void stopAlarmSound() { private void stopAlarmSound() {
if (mPlayer != null) { if (mPlayer != null) {
mPlayer.stop(); // 停止播放 mPlayer.stop();
mPlayer.release(); // 释放资源 mPlayer.release();
mPlayer = null; // 防止内存泄漏 mPlayer = null;
} }
} }
} }

@ -1,149 +1,153 @@
* 12/24 /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package net.micode.notes.ui;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import net.micode.notes.R;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.NumberPicker;
public class DateTimePicker extends FrameLayout { public class DateTimePicker extends FrameLayout {
// 默认启用状态
private static final boolean DEFAULT_ENABLE_STATE = true; private static final boolean DEFAULT_ENABLE_STATE = true;
// 时间格式常量 private static final int HOURS_IN_HALF_DAY = 12;
private static final int HOURS_IN_HALF_DAY = 12; // 半日小时数AM/PM制 private static final int HOURS_IN_ALL_DAY = 24;
private static final int HOURS_IN_ALL_DAY = 24; // 全日小时数24小时制 private static final int DAYS_IN_ALL_WEEK = 7;
private static final int DAYS_IN_ALL_WEEK = 7; // 日期选择范围(一周) private static final int DATE_SPINNER_MIN_VAL = 0;
private static final int DATE_SPINNER_MIN_VAL = 0; // 日期选择器最小值 private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; // 日期选择器最大值 private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; // 24小时制小时最小值 private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; // 24小时制小时最大值 private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; // 12小时制小时最小值 private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; // 12小时制小时最大值 private static final int MINUT_SPINNER_MIN_VAL = 0;
private static final int MINUT_SPINNER_MIN_VAL = 0; // 分钟最小值 private static final int MINUT_SPINNER_MAX_VAL = 59;
private static final int MINUT_SPINNER_MAX_VAL = 59; // 分钟最大值 private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MIN_VAL = 0; // AM/PM最小值 private static final int AMPM_SPINNER_MAX_VAL = 1;
private static final int AMPM_SPINNER_MAX_VAL = 1; // AM/PM最大值
private final NumberPicker mDateSpinner;
// UI控件 private final NumberPicker mHourSpinner;
private final NumberPicker mDateSpinner; // 日期选择器 private final NumberPicker mMinuteSpinner;
private final NumberPicker mHourSpinner; // 小时选择器 private final NumberPicker mAmPmSpinner;
private final NumberPicker mMinuteSpinner; // 分钟选择器 private Calendar mDate;
private final NumberPicker mAmPmSpinner; // AM/PM选择器
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
// 数据存储
private Calendar mDate; // 当前选择的日期时间 private boolean mIsAm;
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; // 日期显示文本缓存
private boolean mIsAm; // 是否为上午 private boolean mIs24HourView;
private boolean mIs24HourView; // 是否24小时制
private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 控件启用状态 private boolean mIsEnabled = DEFAULT_ENABLE_STATE;
private boolean mInitialising; // 初始化标志位
private boolean mInitialising;
// 监听器接口
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
}
private OnDateTimeChangedListener mOnDateTimeChangedListener; private OnDateTimeChangedListener mOnDateTimeChangedListener;
// 日期变更监听器 private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
private NumberPicker.OnValueChangeListener mOnDateChangedListener =
new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 计算日期差值并更新Calendar对象
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl(); // 刷新日期显示 updateDateControl();
onDateTimeChanged(); // 触发回调 onDateTimeChanged();
} }
}; };
// 小时变更监听器(处理跨日逻辑) private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
private NumberPicker.OnValueChangeListener mOnHourChangedListener =
new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false; boolean isDateChanged = false;
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
// 12小时制特殊处理
if (!mIs24HourView) { if (!mIs24HourView) {
// 处理AM/PM自动切换 if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
if ((!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) ||
(mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1)) {
mIsAm = !mIsAm;
updateAmPmControl();
}
// 处理跨日情况
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY && !mIsAm) {
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true; isDateChanged = true;
} else if (oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1 && mIsAm) { } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1); cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true; isDateChanged = true;
} }
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;
updateAmPmControl();
}
} else { } else {
// 24小时制跨日处理
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true; isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1); cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true; isDateChanged = true;
} }
} }
// 更新小时数值
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY); int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour); mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged();
// 处理日期变更
if (isDateChanged) { if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR)); setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH)); setCurrentMonth(cal.get(Calendar.MONTH));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH)); setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
} }
onDateTimeChanged();
} }
}; };
// 分钟变更监听器(处理小时进位) private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener =
new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int min = mMinuteSpinner.getMinValue(); int minValue = mMinuteSpinner.getMinValue();
int max = mMinuteSpinner.getMaxValue(); int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0; int offset = 0;
if (oldVal == maxValue && newVal == minValue) {
// 处理分钟循环滚动 offset += 1;
if (oldVal == max && newVal == min) { // 59->00 } else if (oldVal == minValue && newVal == maxValue) {
offset += 1; // 增加1小时 offset -= 1;
} else if (oldVal == min && newVal == max) { // 00->59
offset -= 1; // 减少1小时
} }
// 更新小时
if (offset != 0) { if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset); mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour()); mHourSpinner.setValue(getCurrentHour());
updateDateControl(); updateDateControl();
// 自动切换AM/PM显示
int newHour = getCurrentHourOfDay(); int newHour = getCurrentHourOfDay();
mIsAm = (newHour < HOURS_IN_HALF_DAY); if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
updateAmPmControl();
} else {
mIsAm = true;
updateAmPmControl(); updateAmPmControl();
} }
}
// 设置分钟值
mDate.set(Calendar.MINUTE, newVal); mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
// AM/PM切换监听器 private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener =
new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm; mIsAm = !mIsAm;
// 调整小时数值
if (mIsAm) { if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else { } else {
@ -154,7 +158,11 @@ public class DateTimePicker extends FrameLayout {
} }
}; };
// 构造函数组 public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
}
public DateTimePicker(Context context) { public DateTimePicker(Context context) {
this(context, System.currentTimeMillis()); this(context, System.currentTimeMillis());
} }
@ -163,59 +171,55 @@ public class DateTimePicker extends FrameLayout {
this(context, date, DateFormat.is24HourFormat(context)); this(context, date, DateFormat.is24HourFormat(context));
} }
// 主构造函数
public DateTimePicker(Context context, long date, boolean is24HourView) { public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context); super(context);
// 初始化时间对象
mDate = Calendar.getInstance(); mDate = Calendar.getInstance();
mInitialising = true; // 设置初始化标志 mInitialising = true;
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
// 加载布局
inflate(context, R.layout.datetime_picker, this); inflate(context, R.layout.datetime_picker, this);
// 初始化日期选择器
mDateSpinner = (NumberPicker) findViewById(R.id.date); mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
// 初始化小时选择器
mHourSpinner = (NumberPicker) findViewById(R.id.hour); mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
// 初始化分钟选择器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL); mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL); mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100); // 长按加速间隔 mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// 初始化AM/PM选择器 String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
String[] ampmStrings = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL); mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
mAmPmSpinner.setDisplayedValues(ampmStrings); // 设置AM/PM本地化文本 mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// 初始化显示状态 // update controls to initial state
updateDateControl(); // 更新日期显示 updateDateControl();
updateHourControl(); // 更新小时显示 updateHourControl();
updateAmPmControl(); // 更新AM/PM显示 updateAmPmControl();
set24HourView(is24HourView); // 设置时间格式
setCurrentDate(date); // 设置初始时间 set24HourView(is24HourView);
// 设置控件启用状态 // set to current time
setEnabled(mIsEnabled); setCurrentDate(date);
mInitialising = false; // 结束初始化
setEnabled(isEnabled());
// set the content descriptions
mInitialising = false;
} }
// 启用/禁用控件
@Override @Override
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) return; if (mIsEnabled == enabled) {
return;
}
super.setEnabled(enabled); super.setEnabled(enabled);
// 级联设置子控件状态
mDateSpinner.setEnabled(enabled); mDateSpinner.setEnabled(enabled);
mMinuteSpinner.setEnabled(enabled); mMinuteSpinner.setEnabled(enabled);
mHourSpinner.setEnabled(enabled); mHourSpinner.setEnabled(enabled);
@ -223,23 +227,259 @@ public class DateTimePicker extends FrameLayout {
mIsEnabled = enabled; mIsEnabled = enabled;
} }
// 获取当前时间(毫秒) @Override
public boolean isEnabled() {
return mIsEnabled;
}
/**
* Get the current date in millis
*
* @return the current date in millis
*/
public long getCurrentDateInTimeMillis() { public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis(); return mDate.getTimeInMillis();
} }
// 设置当前时间(毫秒) /**
* Set the current date
*
* @param date The current date in millis
*/
public void setCurrentDate(long date) { public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date); cal.setTimeInMillis(date);
setCurrentDate( setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.YEAR), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
cal.get(Calendar.MONTH), }
cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY), /**
cal.get(Calendar.MINUTE) * Set the current date
); *
* @param year The current year
* @param month The current month
* @param dayOfMonth The current dayOfMonth
* @param hourOfDay The current hourOfDay
* @param minute The current minute
*/
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
setCurrentHour(hourOfDay);
setCurrentMinute(minute);
}
/**
* Get current year
*
* @return The current year
*/
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
} }
/**
* Set current year
*
* @param year The current year
*/
public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) {
return;
}
mDate.set(Calendar.YEAR, year);
updateDateControl();
onDateTimeChanged();
} }
/**
* Get current month in the year
*
* @return The current month in the year
*/
public int getCurrentMonth() {
return mDate.get(Calendar.MONTH);
}
/**
* Set current month in the year
*
* @param month The month in the year
*/
public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) {
return;
}
mDate.set(Calendar.MONTH, month);
updateDateControl();
onDateTimeChanged();
}
/**
* Get current day of the month
*
* @return The day of the month
*/
public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH);
}
/**
* Set current day of the month
*
* @param dayOfMonth The day of the month
*/
public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) {
return;
}
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateControl();
onDateTimeChanged();
}
/**
* Get current hour in 24 hour mode, in the range (0~23)
* @return The current hour in 24 hour mode
*/
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}
private int getCurrentHour() {
if (mIs24HourView){
return getCurrentHourOfDay();
} else {
int hour = getCurrentHourOfDay();
if (hour > HOURS_IN_HALF_DAY) {
return hour - HOURS_IN_HALF_DAY;
} else {
return hour == 0 ? HOURS_IN_HALF_DAY : hour;
}
}
}
/**
* Set current hour in 24 hour mode, in the range (0~23)
*
* @param hourOfDay
*/
public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return;
}
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
if (!mIs24HourView) {
if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false;
if (hourOfDay > HOURS_IN_HALF_DAY) {
hourOfDay -= HOURS_IN_HALF_DAY;
}
} else {
mIsAm = true;
if (hourOfDay == 0) {
hourOfDay = HOURS_IN_HALF_DAY;
}
}
updateAmPmControl();
}
mHourSpinner.setValue(hourOfDay);
onDateTimeChanged();
}
/**
* Get currentMinute
*
* @return The Current Minute
*/
public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE);
}
/**
* Set current minute
*/
public void setCurrentMinute(int minute) {
if (!mInitialising && minute == getCurrentMinute()) {
return;
}
mMinuteSpinner.setValue(minute);
mDate.set(Calendar.MINUTE, minute);
onDateTimeChanged();
}
/**
* @return true if this is in 24 hour view else false.
*/
public boolean is24HourView () {
return mIs24HourView;
}
/**
* Set whether in 24 hour or AM/PM mode.
*
* @param is24HourView True for 24 hour mode. False for AM/PM mode.
*/
public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) {
return;
}
mIs24HourView = is24HourView;
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay();
updateHourControl();
setCurrentHour(hour);
updateAmPmControl();
}
private void updateDateControl() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
mDateSpinner.setDisplayedValues(null);
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1);
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
}
mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate();
}
private void updateAmPmControl() {
if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE);
} else {
int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE);
}
}
private void updateHourControl() {
if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
} else {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
}
}
/**
* Set the callback that indicates the 'Set' button has been pressed.
* @param callback the callback, if null will do nothing
*/
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback;
}
private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}
}
}

@ -1,119 +1,224 @@
NoteItemData.java /*
/** * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
public class NoteItemData { public class NoteItemData {
// 构造方法:从数据库游标初始化笔记数据 static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID,
NoteColumns.SNIPPET,
NoteColumns.TYPE,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
};
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private boolean mHasAttachment;
private long mModifiedDate;
private int mNotesCount;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private String mName;
private String mPhoneNumber;
private boolean mIsLastItem;
private boolean mIsFirstItem;
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;
public NoteItemData(Context context, Cursor cursor) { public NoteItemData(Context context, Cursor cursor) {
// 基础字段初始化 mId = cursor.getLong(ID_COLUMN);
mId = cursor.getLong(ID_COLUMN); // 获取笔记唯一ID mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); // 提醒时间戳0表示无提醒 mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); // 背景颜色标识ID mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); // 创建时间戳 mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
mHasAttachment = cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0; // 是否有附件(布尔值转换) mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); // 最后修改时间戳 mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); // 关联笔记数量(用于文件夹类型) mParentId = cursor.getLong(PARENT_ID_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN); // 父文件夹ID mSnippet = cursor.getString(SNIPPET_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN) // 内容摘要 mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
.replace(NoteEditActivity.TAG_CHECKED, "") // 去除完成状态标记符号 NoteEditActivity.TAG_UNCHECKED, "");
.replace(NoteEditActivity.TAG_UNCHECKED, ""); mType = cursor.getInt(TYPE_COLUMN);
mType = cursor.getInt(TYPE_COLUMN); // 类型(笔记/文件夹/系统项) mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); // 关联小部件ID mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); // 小部件类型
mPhoneNumber = "";
// 通话记录特殊处理 if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = ""; // 初始化电话号码
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { // 判断是否为通话记录类型
// 通过内容解析器获取通话号码
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) { // 有效号码处理 if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber); // 从通讯录获取联系人名称 mName = Contact.getContact(context, mPhoneNumber);
mName = (mName != null) ? mName : mPhoneNumber; // 无联系人时显示号码 if (mName == null) {
mName = mPhoneNumber;
}
} }
} }
// 名称空值保护 if (mName == null) {
mName = (mName != null) ? mName : ""; // 确保名称字段不为null mName = "";
}
checkPostion(cursor); // 执行位置状态分析 checkPostion(cursor);
} }
// 位置状态分析方法(确定列表项显示样式)
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast(); // 是否列表最后一项 mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst(); // 是否列表首项 mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1); // 是否唯一项 mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false; // 重置多项跟随状态 mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false; // 重置单项跟随状态 mIsOneNoteFollowingFolder = false;
// 仅普通笔记需要检查文件夹跟随状态
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition(); // 记录当前位置 int position = cursor.getPosition();
if (cursor.moveToPrevious()) { // 查看前一项数据 if (cursor.moveToPrevious()) {
int prevType = cursor.getInt(TYPE_COLUMN); if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
// 判断前项是否为文件夹类型 || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
if (prevType == Notes.TYPE_FOLDER || prevType == Notes.TYPE_SYSTEM) {
// 根据剩余项数量判断跟随类型
if (cursor.getCount() > (position + 1)) { if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true; // 多个笔记跟随文件夹 mIsMultiNotesFollowingFolder = true;
} else { } else {
mIsOneNoteFollowingFolder = true; // 单个笔记跟随文件夹 mIsOneNoteFollowingFolder = true;
} }
} }
// 游标归位安全检查
if (!cursor.moveToNext()) { if (!cursor.moveToNext()) {
throw new IllegalStateException("游标无法返回原位"); throw new IllegalStateException("cursor move to previous but can't move back");
} }
} }
} }
} }
// ====================== 属性访问方法 ====================== public boolean isOneFollowingFolder() {
public boolean isOneFollowingFolder() { // 是否是单个跟随文件夹的笔记
return mIsOneNoteFollowingFolder; return mIsOneNoteFollowingFolder;
} }
public boolean isMultiFollowingFolder() { // 是否属于多笔记组中的第一个 public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder; return mIsMultiNotesFollowingFolder;
} }
public boolean isLast() { // 是否列表最后一项 public boolean isLast() {
return mIsLastItem; return mIsLastItem;
} }
public String getCallName() { // 获取通话记录联系人名称 public String getCallName() {
return mName; // 格式:联系人名 或 电话号码 return mName;
} }
public boolean isFirst() { // 是否列表首项 public boolean isFirst() {
return mIsFirstItem; return mIsFirstItem;
} }
public boolean isSingle() { // 是否唯一列表项 public boolean isSingle() {
return mIsOnlyOneItem; return mIsOnlyOneItem;
} }
public long getId() { // 获取数据库主键ID public long getId() {
return mId; return mId;
} }
// ...其他标准getter方法略... public long getAlertDate() {
return mAlertDate;
}
public boolean hasAlert() { // 判断是否存在有效提醒 public long getCreatedDate() {
return mAlertDate > 0; // 时间戳大于0表示有提醒 return mCreatedDate;
} }
public boolean isCallRecord() { // 是否是通话记录类型 public boolean hasAttachment() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); return mHasAttachment;
} }
// ====================== 静态工具方法 ====================== public long getModifiedDate() {
public static int getNoteType(Cursor cursor) { // 快速获取笔记类型 return mModifiedDate;
return cursor.getInt(TYPE_COLUMN); // 直接访问类型字段列
} }
public int getBgColorId() {
return mBgColorId;
} }
public long getParentId() {
return mParentId;
}
public int getNotesCount() {
return mNotesCount;
}
public long getFolderId () {
return mParentId;
}
public int getType() {
return mType;
}
public int getWidgetType() {
return mWidgetType;
}
public int getWidgetId() {
return mWidgetId;
}
public String getSnippet() {
return mSnippet;
}
public boolean hasAlert() {
return (mAlertDate > 0);
}
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}

@ -1,167 +1,184 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import net.micode.notes.data.Notes;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
public class NotesListAdapter extends CursorAdapter { public class NotesListAdapter extends CursorAdapter {
// 日志标签
private static final String TAG = "NotesListAdapter"; private static final String TAG = "NotesListAdapter";
private Context mContext; // 上下文对象 private Context mContext;
private HashMap<Integer, Boolean> mSelectedIndex; // 存储选中位置的映射表(位置 -> 选中状态) private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount; // 普通笔记总数(排除文件夹) private int mNotesCount;
private boolean mChoiceMode; // 是否处于多选模式 private boolean mChoiceMode;
// 小部件属性封装类
public static class AppWidgetAttribute { public static class AppWidgetAttribute {
public int widgetId; // 小部件ID public int widgetId;
public int widgetType; // 小部件类型 public int widgetType;
} };
// 构造函数
public NotesListAdapter(Context context) { public NotesListAdapter(Context context) {
super(context, null); // 初始化CursorAdapter super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>(); // 初始化选中状态容器 mSelectedIndex = new HashMap<Integer, Boolean>();
mContext = context; // 保存上下文引用 mContext = context;
mNotesCount = 0; // 初始化笔记数量 mNotesCount = 0;
} }
// 创建新列表项视图
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); // 实例化自定义列表项视图 return new NotesListItem(context);
} }
// 绑定数据到列表项视图
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) { // 类型安全检查 if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor); // 创建数据包装对象 NoteItemData itemData = new NoteItemData(context, cursor);
// 绑定数据到视图,传递多选模式和选中状态 ((NotesListItem) view).bind(context, itemData, mChoiceMode,
((NotesListItem) view).bind(context, itemData, mChoiceMode, isSelectedItem(cursor.getPosition())); isSelectedItem(cursor.getPosition()));
} }
} }
// 设置指定位置选中状态
public void setCheckedItem(final int position, final boolean checked) { public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked); // 更新选中状态映射表 mSelectedIndex.put(position, checked);
notifyDataSetChanged(); // 触发视图刷新 notifyDataSetChanged();
} }
// 检查是否处于多选模式
public boolean isInChoiceMode() { public boolean isInChoiceMode() {
return mChoiceMode; // 返回当前多选模式状态 return mChoiceMode;
} }
// 切换多选模式
public void setChoiceMode(boolean mode) { public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); // 清空选中记录 mSelectedIndex.clear();
mChoiceMode = mode; // 更新多选模式状态 mChoiceMode = mode;
} }
// 全选/取消全选操作
public void selectAll(boolean checked) { public void selectAll(boolean checked) {
Cursor cursor = getCursor(); // 获取数据游标 Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) { // 遍历所有数据项 for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) { // 移动游标到指定位置 if (cursor.moveToPosition(i)) {
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { // 仅处理普通笔记类型 if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked); // 设置选中状态 setCheckedItem(i, checked);
} }
} }
} }
} }
// 获取选中项ID集合
public HashSet<Long> getSelectedItemIds() { public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>(); // 创建ID集合 HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) { // 遍历选中项 for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position)) { // 检查选中状态 if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position); // 获取数据库ID Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) { // 过滤根文件夹ID if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen"); Log.d(TAG, "Wrong item id, should not happen");
} else { } else {
itemSet.add(id); // 添加有效ID到集合 itemSet.add(id);
} }
} }
} }
return itemSet; // 返回结果集合
return itemSet;
} }
// 获取选中项的小部件属性
public HashSet<AppWidgetAttribute> getSelectedWidget() { public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) { // 遍历选中位置 for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position)) { // 检查选中状态 if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position); // 获取对应游标 Cursor c = (Cursor) getItem(position);
if (c != null) { if (c != null) {
AppWidgetAttribute widget = new AppWidgetAttribute(); // 创建属性对象 AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c); // 包装数据 NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId(); // 设置小部件ID widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType(); // 设置小部件类型 widget.widgetType = item.getWidgetType();
itemSet.add(widget); // 添加到集合 itemSet.add(widget);
/**
* Don't close cursor here, only the adapter could close it
*/
} else { } else {
Log.e(TAG, "Invalid cursor"); // 错误日志记录 Log.e(TAG, "Invalid cursor");
return null; // 返回空值 return null;
} }
} }
} }
return itemSet; // 返回结果集合 return itemSet;
} }
// 统计选中项数量
public int getSelectedCount() { public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values(); // 获取所有状态值 Collection<Boolean> values = mSelectedIndex.values();
if (values == null) return 0; // 空值保护 if (null == values) {
Iterator<Boolean> iter = values.iterator(); // 创建迭代器 return 0;
int count = 0; // 计数器初始化 }
while (iter.hasNext()) { // 遍历状态集合 Iterator<Boolean> iter = values.iterator();
if (iter.next()) count++; // 统计选中状态数量 int count = 0;
while (iter.hasNext()) {
if (true == iter.next()) {
count++;
}
} }
return count; // 返回总数 return count;
} }
// 检查是否全选
public boolean isAllSelected() { public boolean isAllSelected() {
int checkedCount = getSelectedCount(); // 获取当前选中数 int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount); // 比较总数 return (checkedCount != 0 && checkedCount == mNotesCount);
} }
// 检查指定位置是否选中
public boolean isSelectedItem(final int position) { public boolean isSelectedItem(final int position) {
Boolean result = mSelectedIndex.get(position); // 获取选中状态 if (null == mSelectedIndex.get(position)) {
return result != null ? result : false; // 空值安全处理 return false;
}
return mSelectedIndex.get(position);
} }
// 数据变更回调
@Override @Override
protected void onContentChanged() { protected void onContentChanged() {
super.onContentChanged(); // 调用父类方法 super.onContentChanged();
calcNotesCount(); // 重新计算笔记数量 calcNotesCount();
} }
// 切换数据游标
@Override @Override
public void changeCursor(Cursor cursor) { public void changeCursor(Cursor cursor) {
super.changeCursor(cursor); // 调用父类方法 super.changeCursor(cursor);
calcNotesCount(); // 重新计算笔记数量 calcNotesCount();
} }
// 计算普通笔记数量
private void calcNotesCount() { private void calcNotesCount() {
mNotesCount = 0; // 重置计数器 mNotesCount = 0;
for (int i = 0; i < getCount(); i++) { // 遍历所有数据项 for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i); // 获取游标对象 Cursor c = (Cursor) getItem(i);
if (c != null) { if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { // 类型检查 if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++; // 计数普通笔记 mNotesCount++;
} }
} else { } else {
Log.e(TAG, "Invalid cursor"); // 错误日志 Log.e(TAG, "Invalid cursor");
return; // 提前退出 return;
}
} }
} }
} }

@ -1,77 +1,92 @@
// 自定义列表项控件继承LinearLayout实现复合视图 /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout {
// 声明视图组件 private ImageView mAlert;
private ImageView mAlert; // 提醒图标(时钟/通话记录图标) private TextView mTitle;
private TextView mTitle; // 主标题(笔记内容/文件夹名) private TextView mTime;
private TextView mTime; // 时间显示(相对时间格式) private TextView mCallName;
private TextView mCallName; // 来电人姓名(通话记录专用) private NoteItemData mItemData;
private NoteItemData mItemData; // 数据模型对象 private CheckBox mCheckBox;
private CheckBox mCheckBox; // 多选框(用于选择模式)
// 构造函数
public NotesListItem(Context context) { public NotesListItem(Context context) {
super(context); super(context);
inflate(context, R.layout.note_item, this); // 加载布局note_item.xml到当前视图 inflate(context, R.layout.note_item, this);
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
// 初始化视图组件 mTitle = (TextView) findViewById(R.id.tv_title);
mAlert = (ImageView) findViewById(R.id.iv_alert_icon); // 提醒图标 mTime = (TextView) findViewById(R.id.tv_time);
mTitle = (TextView) findViewById(R.id.tv_title); // 主标题文本 mCallName = (TextView) findViewById(R.id.tv_name);
mTime = (TextView) findViewById(R.id.tv_time); // 时间文本 mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
mCallName = (TextView) findViewById(R.id.tv_name); // 来电人姓名
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); // 系统预定义checkbox ID
} }
// 数据绑定方法(核心逻辑) public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
public void bind(Context context, NoteItemData data,
boolean choiceMode, boolean checked) {
// 处理多选模式显示
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE); // 仅普通笔记显示复选框 mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked); // 设置选中状态 mCheckBox.setChecked(checked);
} else { } else {
mCheckBox.setVisibility(View.GONE); // 文件夹/通话记录隐藏复选框 mCheckBox.setVisibility(View.GONE);
} }
mItemData = data; // 缓存数据对象 mItemData = data;
// 分支1通话记录文件夹
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE); // 隐藏来电人姓名 mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE); // 显示通话记录图标 mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 主标题样式 mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
mTitle.setText(context.getString(R.string.call_record_folder_name) // "通话记录" mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount())); // 追加数量(如"(3)" + context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record); // 设置通话记录图标 mAlert.setImageResource(R.drawable.call_record);
// 分支2通话记录条目
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.VISIBLE); // 显示来电人姓名 mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName()); // 设置来电人(如"张三" mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); // 副标题样式 mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 格式化内容预览 mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) { // 判断是否有提醒 if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock); // 显示时钟图标 mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
} else { } else {
mAlert.setVisibility(View.GONE); // 无提醒隐藏图标 mAlert.setVisibility(View.GONE);
} }
// 分支3普通笔记/文件夹
} else { } else {
mCallName.setVisibility(View.GONE); // 隐藏来电人姓名 mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 主样式 mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
// 子分支3-1文件夹类型
if (data.getType() == Notes.TYPE_FOLDER) { if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet() // 文件夹名称 mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count, // 追加数量 + context.getString(R.string.format_folder_files_count,
data.getNotesCount())); data.getNotesCount()));
mAlert.setVisibility(View.GONE); // 文件夹不显示图标 mAlert.setVisibility(View.GONE);
// 子分支3-2普通笔记
} else { } else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 内容预览 mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) { // 提醒处理 if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock); mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
} else { } else {
@ -79,39 +94,29 @@ public class NotesListItem extends LinearLayout {
} }
} }
} }
// 设置时间显示(例如"2小时前"
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
setBackground(data); // 根据位置设置背景样式 setBackground(data);
} }
// 背景设置逻辑(实现列表项不同位置的圆角效果)
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {
int id = data.getBgColorId(); // 获取背景颜色ID int id = data.getBgColorId();
// 仅普通笔记需要特殊背景处理
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {
// 条件1单一条目或跟随文件夹的第一个条目
if (data.isSingle() || data.isOneFollowingFolder()) { if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); // 单一行圆角 setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
// 条件2列表最后一项
} else if (data.isLast()) { } else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); // 底部圆角 setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
// 条件3列表第一项或多条目组的第一个
} else if (data.isFirst() || data.isMultiFollowingFolder()) { } else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); // 顶部圆角 setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
// 默认:中间条目
} else { } else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); // 直角背景 setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
}
} }
// 其他类型(文件夹/通话记录)使用默认背景 } else {
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
} }
} }
public NoteItemData getItemData() { public NoteItemData getItemData() {
return mItemData; // 返回成员变量存储的数据模型引用 return mItemData;
}
} }

@ -1,265 +1,388 @@
//// ====================== 同步时间显示控制 ====================== /*
UI * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
if (GTaskSyncService.isSyncing()) { // 检测同步服务是否正在运行 *
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); // 显示动态同步进度文本 * Licensed under the Apache License, Version 2.0 (the "License");
lastSyncTimeView.setVisibility(View.VISIBLE); // 确保视图可见 * you may not use this file except in compliance with the License.
} else { // 未处于同步状态时 * You may obtain a copy of the License at
long lastSyncTime = getLastSyncTime(this); // 从SharedPreferences获取存储的时间戳 *
if (lastSyncTime != 0) { // 存在有效同步记录 * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
public class NotesPreferenceActivity extends PreferenceActivity {
public static final String PREFERENCE_NAME = "notes_preferences";
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
private static final String AUTHORITIES_FILTER_KEY = "authorities";
private PreferenceCategory mAccountCategory;
private GTaskReceiver mReceiver;
private Account[] mOriAccounts;
private boolean mHasAddedAccount;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true);
addPreferencesFromResource(R.xml.preferences);
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter);
mOriAccounts = null;
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true);
}
@Override
protected void onResume() {
super.onResume();
// need to set sync account automatically if user has added a new
// account
if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
for (Account accountNew : accounts) {
boolean found = false;
for (Account accountOld : mOriAccounts) {
if (TextUtils.equals(accountOld.name, accountNew.name)) {
found = true;
break;
}
}
if (!found) {
setSyncAccount(accountNew.name);
break;
}
}
}
}
refreshUI();
}
@Override
protected void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
super.onDestroy();
}
private void loadAccountPreference() {
mAccountCategory.removeAll();
Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary));
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account
showSelectAccountAlertDialog();
} else {
// if the account has already been set, we need to promp
// user about the risk
showChangeAccountConfirmAlertDialog();
}
} else {
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
}
return true;
}
});
mAccountCategory.addPreference(accountPref);
}
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state
if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}
});
} else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.startSync(NotesPreferenceActivity.this);
}
});
}
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time
if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) {
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format), DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime))); // 格式化时间为"yyyy-MM-dd HH:mm"样式 lastSyncTime)));
lastSyncTimeView.setVisibility(View.VISIBLE); // 显示时间文本 lastSyncTimeView.setVisibility(View.VISIBLE);
} else { // 无同步记录 } else {
lastSyncTimeView.setVisibility(View.GONE); // 隐藏视图避免空白区域 lastSyncTimeView.setVisibility(View.GONE);
}
} }
} }
// ====================== 界面刷新方法 ======================
private void refreshUI() { private void refreshUI() {
loadAccountPreference(); // 更新顶部账户名称显示(调用内部方法) loadAccountPreference();
loadSyncButton(); // 控制同步按钮的可用状态(如网络未连接时禁用) loadSyncButton();
} }
// ====================== 账户选择对话框 ======================
private void showSelectAccountAlertDialog() { private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // 创建对话框构建器 AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 构建自定义标题布局 View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); // 加载布局文件 TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); // 获取标题TextView titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); // 设置主标题文本 TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); // 副标题视图 subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); // 设置提示性文字
dialogBuilder.setCustomTitle(titleView); // 应用自定义标题布局
dialogBuilder.setPositiveButton(null, null); // 移除默认确认按钮(因使用单选列表交互) dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null);
Account[] accounts = getGoogleAccounts(); // 通过AccountManager获取设备上所有Google账户 Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this); // 从SharedPreferences读取当前选中的账户名 String defAccount = getSyncAccountName(this);
mOriAccounts = accounts; // 类成员变量缓存账户列表(用于后续比较是否新增账户) mOriAccounts = accounts;
mHasAddedAccount = false; // 标记位标识用户是否执行了添加账户操作 mHasAddedAccount = false;
if (accounts.length > 0) { // 存在可用账户时构建单选列表 if (accounts.length > 0) {
CharSequence[] items = new CharSequence[accounts.length]; // 准备显示项数组 CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items; // 用于内部类访问的final引用 final CharSequence[] itemMapping = items;
int checkedItem = -1; // 默认没有选中项(-1表示无选中 int checkedItem = -1;
int index = 0; // 数组索引计数器 int index = 0;
for (Account account : accounts) { // 遍历所有Google账户 for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) { // 匹配当前选中账户 if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index; // 记录选中项位置 checkedItem = index;
} }
items[index++] = account.name; // 将账户名存入显示项数组 items[index++] = account.name;
} }
// 设置单选列表项及选择监听
dialogBuilder.setSingleChoiceItems(items, checkedItem, dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString()); // 用户点击时更新选中账户 setSyncAccount(itemMapping[which].toString());
dialog.dismiss(); // 关闭对话框 dialog.dismiss();
refreshUI(); // 刷新界面显示新账户 refreshUI();
} }
}); });
} }
// 添加"新建账户"入口 View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); // 加载布局 dialogBuilder.setView(addAccountView);
dialogBuilder.setView(addAccountView); // 将布局添加到对话框底部
final AlertDialog dialog = dialogBuilder.show(); // 显示完整对话框 final AlertDialog dialog = dialogBuilder.show();
addAccountView.setOnClickListener(new View.OnClickListener() { // 处理添加账户点击事件 addAccountView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { public void onClick(View v) {
mHasAddedAccount = true; // 标记已触发添加账户操作 mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); // 系统级添加账户Intent Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[]{"gmail-ls"}); // 过滤只显示Gmail类账户 intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
startActivityForResult(intent, -1); // 启动系统界面(-1为临时请求码建议改为常量 "gmail-ls"
dialog.dismiss(); // 关闭当前对话框 });
startActivityForResult(intent, -1);
dialog.dismiss();
} }
}); });
} }
// ====================== 账户变更确认对话框 ======================
private void showChangeAccountConfirmAlertDialog() { private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // 新建对话框构建器 AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 复用标题布局,动态显示当前账户
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this))); // 动态插入当前账户名(例:"当前账户user@gmail.com" getSyncAccountName(this)));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); // 警告文本 subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView); // 应用自定义标题 dialogBuilder.setCustomTitle(titleView);
// 操作选项列表(更换/移除/取消)
CharSequence[] menuItemArray = new CharSequence[] { CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account), // 资源ID对应"更换账户" getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account), // "移除账户" getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel) // "取消" getString(R.string.preferences_menu_cancel)
}; };
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
if (which == 0) { // 用户点击第一项(更换账户) if (which == 0) {
showSelectAccountAlertDialog(); // 打开账户选择对话框 showSelectAccountAlertDialog();
} else if (which == 1) { // 点击第二项(移除账户) } else if (which == 1) {
removeSyncAccount(); // 清空SharedPreferences中的账户存储 removeSyncAccount();
refreshUI(); // 更新界面为无账户状态 refreshUI();
} // 第三项"取消"无操作,自动关闭对话框 }
} }
}); });
dialogBuilder.show(); // 显示最终对话框 dialogBuilder.show();
} }
// ====================== 账户管理工具方法 ======================
private Account[] getGoogleAccounts() { private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this); // 获取系统账户管理器实例 AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google"); // 过滤出所有Google类型账户 return accountManager.getAccountsByType("com.google");
} }
// ====================== 核心账户设置方法 ======================
private void setSyncAccount(String account) { private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) { // 仅在新旧账户不同时执行操作 if (!getSyncAccountName(this).equals(account)) {
// 持久化存储账户名到SharedPreferences
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); // 获取编辑器 SharedPreferences.Editor editor = settings.edit();
if (account != null) { if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); // 存储有效账户名 editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else { } else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); // 空值处理 editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
editor.commit(); // 立即提交写入注意同步操作可能阻塞UI editor.commit();
setLastSyncTime(this, 0); // 重置最后同步时间戳为0表示需要重新同步 // clean up last sync time
setLastSyncTime(this, 0);
// 启动后台线程清理旧账户关联数据 // clean up local gtask related info
new Thread(new Runnable() { new Thread(new Runnable() {
@Override
public void run() { public void run() {
ContentValues values = new ContentValues(); // 创建更新数据集 ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, ""); // 清空任务ID字段 values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0); // 重置同步ID为初始状态 values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update( getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
Notes.CONTENT_NOTE_URI, // 目标ContentProvider URI }
values, // 更新内容 }).start();
null, // 无WHERE条件更新所有记录
null // 无参数
); // 执行批量更新操作
}
}).start(); // 立即启动清理线程
// 显示操作成功的Toast提示
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account), // 动态插入账户名 getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show(); // 短时显示提示 Toast.LENGTH_SHORT).show();
} }
} }
private void removeSyncAccount() { private void removeSyncAccount() {
// 获取SharedPreferences实例私有模式仅本应用可访问
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); // 获取编辑器对象 SharedPreferences.Editor editor = settings.edit();
// 条件移除账户名配置(避免删除不存在的键)
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); // 删除键值对 editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
} }
// 条件移除最后同步时间戳
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME); editor.remove(PREFERENCE_LAST_SYNC_TIME);
} }
editor.commit(); // 同步提交修改(立即生效,适合关键配置操作) editor.commit();
// 启动异步任务清理关联数据 // clean up local gtask related info
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, ""); // 重置任务ID为空字符串 values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0); // 重置同步标识为初始状态 values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update( getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
Notes.CONTENT_NOTE_URI, // 目标ContentProvider的URI
values, // 更新值集合
null, // 无WHERE条件全表更新
null // 无参数绑定
); // 执行批量数据清理
} }
}).start(); // 立即启动后台线程 }).start();
} }
// ====================== 配置存取工具方法 ======================
// 获取当前绑定账户名(返回空字符串表示未设置)
public static String getSyncAccountName(Context context) { public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences( SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
PREFERENCE_NAME, // 配置文件名 Context.MODE_PRIVATE);
Context.MODE_PRIVATE // 访问模式 return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
);
return settings.getString(
PREFERENCE_SYNC_ACCOUNT_NAME, // 键名
"" // 默认值(空字符串)
);
} }
// 更新最后同步时间戳(单位:毫秒)
public static void setLastSyncTime(Context context, long time) { public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences( SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
PREFERENCE_NAME, Context.MODE_PRIVATE);
Context.MODE_PRIVATE
);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); // 写入长整型数值 editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit(); // 同步提交保证时间戳立即更新 editor.commit();
} }
// 获取最后成功同步时间返回0表示从未同步
public static long getLastSyncTime(Context context) { public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences( SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
PREFERENCE_NAME, Context.MODE_PRIVATE);
Context.MODE_PRIVATE return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
);
return settings.getLong(
PREFERENCE_LAST_SYNC_TIME, // 键名
0L // 默认值0
);
} }
// ====================== 同步状态广播接收器 ======================
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
refreshUI(); // 强制刷新界面显示最新状态 refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
// 检测广播是否携带同步状态 TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
if (intent.getBooleanExtra( syncStatus.setText(intent
GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, // 附加参数键名 .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
false // 默认值
)) {
TextView syncStatus = (TextView) findViewById(
R.id.prefenerece_sync_status_textview // 状态显示文本框ID
);
// 设置动态进度信息(例如:"同步中(50%)"
syncStatus.setText(intent.getStringExtra(
GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG
));
} }
} }
} }
// ====================== 选项菜单处理 ======================
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: // 处理导航栏返回按钮 case android.R.id.home:
Intent intent = new Intent(this, NotesListActivity.class); Intent intent = new Intent(this, NotesListActivity.class);
// 清理活动栈如果目标Activity已在栈中则弹出其上所有Activity
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent); // 跳转到笔记列表 startActivity(intent);
return true; // 消费事件 return true;
default: default:
return false; // 未处理的事件传递给超类 return false;
}
} }
} }

@ -1,154 +1,132 @@
/** /*
* 便 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package net.micode.notes.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.widget.RemoteViews;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;
public abstract class NoteWidgetProvider extends AppWidgetProvider { public abstract class NoteWidgetProvider extends AppWidgetProvider {
// 数据库查询投影字段(对应笔记表的列)
public static final String [] PROJECTION = new String [] { public static final String [] PROJECTION = new String [] {
NoteColumns.ID, // 笔记ID列 NoteColumns.ID,
NoteColumns.BG_COLOR_ID, // 背景颜色ID列 NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET // 内容摘要列 NoteColumns.SNIPPET
}; };
// 查询结果列的索引常量 public static final int COLUMN_ID = 0;
public static final int COLUMN_ID = 0; // 笔记ID索引 public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_BG_COLOR_ID = 1; // 背景颜色ID索引 public static final int COLUMN_SNIPPET = 2;
public static final int COLUMN_SNIPPET = 2; // 内容摘要索引
private static final String TAG = "NoteWidgetProvider"; // 日志标签 private static final String TAG = "NoteWidgetProvider";
/**
*
* @param context
* @param appWidgetIds ID
*
*/
@Override @Override
public void onDeleted(Context context, int[] appWidgetIds) { public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // 重置无效ID values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
for (int i = 0; i < appWidgetIds.length; i++) {
for (int widgetId : appWidgetIds) { // 遍历所有被删除的小部件 context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
context.getContentResolver().update( values,
Notes.CONTENT_NOTE_URI, // 笔记内容URI NoteColumns.WIDGET_ID + "=?",
values, // 更新值集合 new String[] { String.valueOf(appWidgetIds[i])});
NoteColumns.WIDGET_ID + "=?",// 按小部件ID筛选
new String[]{String.valueOf(widgetId)}
);
} }
} }
/**
*
* @param context
* @param widgetId ID
* @return Cursor
*
*/
private Cursor getNoteWidgetInfo(Context context, int widgetId) { private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query( return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
Notes.CONTENT_NOTE_URI, // 笔记内容URI PROJECTION,
PROJECTION, // 查询字段 NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
NoteColumns.WIDGET_ID + "=? AND " + // 查询条件
NoteColumns.PARENT_ID + "<>?", // 排除垃圾桶
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
null // 排序方式 null);
);
} }
/**
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetManager, appWidgetIds, false); // 默认普通模式 update(context, appWidgetManager, appWidgetIds, false);
} }
/** private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
* boolean privacyMode) {
* @param privacyMode true for (int i = 0; i < appWidgetIds.length; i++) {
*/ if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
private void update(Context context, AppWidgetManager appWidgetManager, int bgId = ResourceParser.getDefaultBgId(context);
int[] appWidgetIds, boolean privacyMode) { String snippet = "";
for (int widgetId : appWidgetIds) { // 遍历处理每个小部件 Intent intent = new Intent(context, NoteEditActivity.class);
if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) continue; intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
// 初始化默认值 intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
int bgId = ResourceParser.getDefaultBgId(context); // 获取默认背景
String snippet = ""; // 内容摘要 Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
Intent intent = new Intent(context, NoteEditActivity.class); // 编辑意图
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // 单例模式
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, widgetId); // 传递小部件ID
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); // 小部件类型
// 查询关联的笔记数据
try (Cursor c = getNoteWidgetInfo(context, widgetId)) {
if (c != null && c.moveToFirst()) { if (c != null && c.moveToFirst()) {
// 数据校验防止相同小部件ID关联多个笔记
if (c.getCount() > 1) { if (c.getCount() > 1) {
Log.e(TAG, "小部件ID重复关联多个笔记:" + widgetId); Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
continue; c.close();
return;
} }
// 获取实际笔记数据 snippet = c.getString(COLUMN_SNIPPET);
snippet = c.getString(COLUMN_SNIPPET); // 内容摘要 bgId = c.getInt(COLUMN_BG_COLOR_ID);
bgId = c.getInt(COLUMN_BG_COLOR_ID); // 背景ID intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); // 笔记ID intent.setAction(Intent.ACTION_VIEW);
intent.setAction(Intent.ACTION_VIEW); // 设置为查看模式
} else { } else {
// 没有关联笔记的处理 snippet = context.getResources().getString(R.string.widget_havenot_content);
snippet = context.getString(R.string.widget_havenot_content); intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 新建/编辑模式
} }
if (c != null) {
c.close();
} }
// 构建小部件视图
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); // 设置背景 rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); // 传递背景给后续Activity intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
/**
// 构建点击事件 * Generate the pending intent to start host for the widget
PendingIntent pendingIntent; */
PendingIntent pendingIntent = null;
if (privacyMode) { if (privacyMode) {
// 隐私模式:显示占位文本,点击跳转到笔记列表 rv.setTextViewText(R.id.widget_text,
rv.setTextViewText(R.id.widget_text, context.getString(R.string.widget_under_visit_mode)); context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, widgetId, pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
new Intent(context, NotesListActivity.class), // 跳转列表页 context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent.FLAG_UPDATE_CURRENT);
} else { } else {
// 正常模式:显示真实内容,点击打开对应笔记
rv.setTextViewText(R.id.widget_text, snippet); rv.setTextViewText(R.id.widget_text, snippet);
pendingIntent = PendingIntent.getActivity(context, widgetId, intent, pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent.FLAG_UPDATE_CURRENT);
} }
// 绑定点击事件
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
// 更新小部件界面 }
appWidgetManager.updateAppWidget(widgetId, rv);
} }
} }
//----------- 抽象方法(子类必须实现) -----------
/**
* ID
* @param bgId
* @return ID
*/
protected abstract int getBgResourceId(int bgId); protected abstract int getBgResourceId(int bgId);
/**
* ID
*/
protected abstract int getLayoutId(); protected abstract int getLayoutId();
/**
*
*/
protected abstract int getWidgetType(); protected abstract int getWidgetType();
} }

Loading…
Cancel
Save