Compare commits

..

3 Commits

Author SHA1 Message Date
zgx a6f16c4b8c 111
2 months ago
zgx 14a8d917d1 张家辉注释
2 months ago
zgx a7af2c8d80 1
4 months ago

@ -0,0 +1 @@
1111

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

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,19 +24,32 @@ 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>();
} }
@ -44,26 +57,30 @@ 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.close();// 确保关闭Cursor释放资源
} }
} else { } else {
Log.d(TAG, "No contact matched with number:" + phoneNumber); Log.d(TAG, "No contact matched with number:" + phoneNumber);

@ -14,266 +14,77 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.data; package net.micode.notes.data;//导入包
import android.net.Uri; import android.content.Context;//
public class Notes {//定义类 import android.database.Cursor;
public static final String AUTHORITY = "micode_notes"; import android.provider.ContactsContract.CommonDataKinds.Phone;
public static final String TAG = "Notes"; import android.provider.ContactsContract.Data;
public static final int TYPE_NOTE = 0; import android.telephony.PhoneNumberUtils;
public static final int TYPE_FOLDER = 1; import android.util.Log;
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 */
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder public class Contact {
* {@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; // 日志标签
public static final int ID_TEMPARAY_FOLDER = -1; private static final String TAG = "Contact";
public static final int ID_CALL_RECORD_FOLDER = -2; // 查询条件模板:
public static final int ID_TRASH_FOLER = -3; // 1. 使用PHONE_NUMBERS_EQUAL比较电话号码考虑格式差异
// 2. 数据类型为电话条目
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // 3. 限制raw_contact_id必须在phone_lookup表中匹配指定最小匹配长度的记录
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; + " AND " + Data.RAW_CONTACT_ID + " IN "
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; + "(SELECT raw_contact_id "
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; + " FROM phone_lookup"
+ " WHERE min_match = '+')";
public static final int TYPE_WIDGET_INVALIDE = -1; /**
public static final int TYPE_WIDGET_2X = 0; *
public static final int TYPE_WIDGET_4X = 1; * @param context 访
* @param phoneNumber
public static class DataConstants { * @return null
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/**
* 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 static String getContact(Context context, String phoneNumber) {
// 初始化缓存
public interface NoteColumns { if(sContactCache == null) {
/** sContactCache = new HashMap<String, String>();
* The unique ID for a row }
* <P> Type: INTEGER (long) </P>
*/ if(sContactCache.containsKey(phoneNumber)) {
public static final String ID = "_id"; return sContactCache.get(phoneNumber);
}
/** // 优先从缓存中获取
* The parent's id for note or folder String selection = CALLER_ID_SELECTION.replace("+",
* <P> Type: INTEGER (long) </P> // 构造完整查询条件:替换最小匹配长度参数
*/ PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
public static final String PARENT_ID = "parent_id"; // 通过内容解析器查询联系人数据库
Cursor cursor = context.getContentResolver().query(
/** Data.CONTENT_URI,// 访问组合联系人数据
* Created data for note or folder new String [] { Phone.DISPLAY_NAME },// 查询显示名字段
* <P> Type: INTEGER (long) </P> selection,// 动态生成的查询条件
*/ new String[] { phoneNumber },// 查询参数(原始电话号码)
public static final String CREATED_DATE = "created_date"; null);// 排序方式(无)
// 处理查询结果
/** if (cursor != null && cursor.moveToFirst()) {
* Latest modified date try {
* <P> Type: INTEGER (long) </P> // 获取第一条记录的显示名称
*/ String name = cursor.getString(0);
public static final String MODIFIED_DATE = "modified_date"; // 更新缓存
sContactCache.put(phoneNumber, name);
return name;
/** } catch (IndexOutOfBoundsException e) {
* Alert date Log.e(TAG, " Cursor get string error " + e.toString());
* <P> Type: INTEGER (long) </P> return null;
*/ } finally {
public static final String ALERTED_DATE = "alert_date"; cursor.close();// 确保关闭Cursor释放资源
}
/** } else {
* Folder's name or text content of note Log.d(TAG, "No contact matched with number:" + phoneNumber);
* <P> Type: TEXT </P> return null;
*/ }
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";
}
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
*/
public static final String MIME_TYPE = "mime_type";
/**
* The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTE_ID = "note_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";
/**
* 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";
}
public static final class TextNote implements DataColumns {
/**
* 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,63 +25,69 @@ 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," + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +// 所属文件夹ID树形结构
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," + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +// 是否有附件0/1布尔值
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," + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +// 关联的小部件ID
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 ''," + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +// Google Task关联ID
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," + DataColumns.MIME_TYPE + " TEXT NOT NULL," +// MIME类型文本、清单、媒体等
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联的笔记ID
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," + DataColumns.DATA1 + " INTEGER," +// 扩展字段1类型相关数据
DataColumns.DATA2 + " INTEGER," + DataColumns.DATA2 + " INTEGER," +// 扩展字段2如清单项状态
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +// 扩展字段3如地理位置
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +// 扩展字段4如附件路径
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +// 扩展字段5保留字段
")"; ")";
// 数据表索引加速按笔记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
*/ */
@ -93,7 +99,8 @@ 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
*/ */
@ -106,7 +113,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
*/ */
@ -118,7 +125,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
*/ */
@ -131,33 +138,42 @@ 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 + ";" + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +// 通过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
*/ */
@ -167,10 +183,14 @@ 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
*/ */
@ -179,9 +199,13 @@ 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 + ";" + " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +// 根据被删除笔记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
*/ */
@ -190,22 +214,33 @@ 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);
} }
@ -237,14 +272,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
*/ */
@ -252,7 +287,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
*/ */
@ -260,7 +295,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
*/ */
@ -293,7 +328,13 @@ 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);
@ -304,57 +345,72 @@ 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 skipV2 = true; // this upgrade including the upgrade from v2 to v3// 包含V2到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 // add a column for gtask id// 添加Google Task关联字段
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;//111 package net.micode.notes.data;
import android.app.SearchManager; import android.app.SearchManager;
@ -34,22 +34,26 @@ 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 int URI_NOTE = 1; private static final String TAG = "NotesProvider";// 日志标签
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_SEARCH = 5; private static final int URI_NOTE = 1;// 笔记集合操作
private static final int URI_SEARCH_SUGGEST = 6; 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_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);
@ -57,30 +61,37 @@ 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 + "," private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","// 原始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;
} }
@ -91,47 +102,53 @@ 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 c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id// 从URI路径获取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) {
@ -141,21 +158,27 @@ 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 {
@ -166,50 +189,55 @@ 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) { if (noteId > 0) {// 通知笔记URI变更触发CursorLoader刷新
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 // Notify the data uri// 通知数据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; boolean deleteData = false;// 标记是否删除的是data表数据
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); long noteId = Long.valueOf(id); // 系统文件夹ID<=0不允许删除
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);
@ -218,37 +246,44 @@ 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; boolean updateData = false;// 标记是否更新data表
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);
@ -257,20 +292,31 @@ 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 ");
@ -278,13 +324,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) {
@ -292,13 +338,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 // TODO Auto-generated method stub// 根据URI返回MIME类型当前未实现
return null; return null;
} }

@ -1,158 +1,130 @@
/* * 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; private long mNoteId; // 当前提醒关联的笔记ID
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 {
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); // 从Intent URI解析笔记ID格式content://xxx/notes/123
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 从数据库获取原始内容
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, // 截取前60字符超长显示省略符
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN
? 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 e) { } catch (IllegalArgumentException | SecurityException
// TODO Auto-generated catch block | IllegalStateException | IOException e) {
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); intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递笔记ID
startActivity(intent); startActivity(intent); // 跳转编辑页面
break;
default:
break; break;
// 确认按钮无需特别处理,默认关闭
} }
} }
// 对话框关闭回调
public void onDismiss(DialogInterface dialog) { public void onDismiss(DialogInterface dialog) {
stopAlarmSound(); stopAlarmSound(); // 停止铃声
finish(); finish(); // 关闭当前Activity
} }
// 停止并释放媒体资源
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,153 +1,149 @@
/* * 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_ALL_DAY = 24; private static final int HOURS_IN_HALF_DAY = 12; // 半日小时数AM/PM制
private static final int DAYS_IN_ALL_WEEK = 7; private static final int HOURS_IN_ALL_DAY = 24; // 全日小时数24小时制
private static final int DATE_SPINNER_MIN_VAL = 0; private static final int DAYS_IN_ALL_WEEK = 7; // 日期选择范围(一周)
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; private static final int DATE_SPINNER_MIN_VAL = 0; // 日期选择器最小值
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; // 日期选择器最大值
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; // 24小时制小时最小值
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; // 24小时制小时最大值
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; // 12小时制小时最小值
private static final int MINUT_SPINNER_MIN_VAL = 0; private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; // 12小时制小时最大值
private static final int MINUT_SPINNER_MAX_VAL = 59; private static final int MINUT_SPINNER_MIN_VAL = 0; // 分钟最小值
private static final int AMPM_SPINNER_MIN_VAL = 0; private static final int MINUT_SPINNER_MAX_VAL = 59; // 分钟最大值
private static final int AMPM_SPINNER_MAX_VAL = 1; private static final int AMPM_SPINNER_MIN_VAL = 0; // AM/PM最小值
private static final int AMPM_SPINNER_MAX_VAL = 1; // AM/PM最大值
private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner; // UI控件
private final NumberPicker mMinuteSpinner; private final NumberPicker mDateSpinner; // 日期选择器
private final NumberPicker mAmPmSpinner; private final NumberPicker mHourSpinner; // 小时选择器
private Calendar mDate; private final NumberPicker mMinuteSpinner; // 分钟选择器
private final NumberPicker mAmPmSpinner; // AM/PM选择器
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
// 数据存储
private boolean mIsAm; private Calendar mDate; // 当前选择的日期时间
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; // 日期显示文本缓存
private boolean mIs24HourView; private boolean mIsAm; // 是否为上午
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) {
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { // 处理AM/PM自动切换
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 (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { } else if (oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1 && 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;
} }
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 minValue = mMinuteSpinner.getMinValue(); int min = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue(); int max = mMinuteSpinner.getMaxValue();
int offset = 0; int offset = 0;
if (oldVal == maxValue && newVal == minValue) {
offset += 1; // 处理分钟循环滚动
} else if (oldVal == minValue && newVal == maxValue) { if (oldVal == max && newVal == min) { // 59->00
offset -= 1; offset += 1; // 增加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();
if (newHour >= HOURS_IN_HALF_DAY) { mIsAm = (newHour < HOURS_IN_HALF_DAY);
mIsAm = false; updateAmPmControl();
updateAmPmControl();
} else {
mIsAm = true;
updateAmPmControl();
}
} }
// 设置分钟值
mDate.set(Calendar.MINUTE, newVal); mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { // AM/PM切换监听器
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 {
@ -158,11 +154,7 @@ 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());
} }
@ -171,55 +163,59 @@ 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);
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); // 初始化AM/PM选择器
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(stringsForAmPm); mAmPmSpinner.setDisplayedValues(ampmStrings); // 设置AM/PM本地化文本
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state // 初始化显示状态
updateDateControl(); updateDateControl(); // 更新日期显示
updateHourControl(); updateHourControl(); // 更新小时显示
updateAmPmControl(); updateAmPmControl(); // 更新AM/PM显示
set24HourView(is24HourView); // 设置时间格式
set24HourView(is24HourView); setCurrentDate(date); // 设置初始时间
// set to current time // 设置控件启用状态
setCurrentDate(date); setEnabled(mIsEnabled);
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) { if (mIsEnabled == enabled) return;
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);
@ -227,259 +223,23 @@ 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(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), setCurrentDate(
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)); cal.get(Calendar.YEAR),
} cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH),
/** cal.get(Calendar.HOUR_OF_DAY),
* Set the current date cal.get(Calendar.MINUTE)
* );
* @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,224 +1,119 @@
/* 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); // 基础字段初始化
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mId = cursor.getLong(ID_COLUMN); // 获取笔记唯一ID
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); // 提醒时间戳0表示无提醒
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); // 背景颜色标识ID
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); // 创建时间戳
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); mHasAttachment = cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0; // 是否有附件(布尔值转换)
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); // 最后修改时间戳
mParentId = cursor.getLong(PARENT_ID_COLUMN); mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); // 关联笔记数量(用于文件夹类型)
mSnippet = cursor.getString(SNIPPET_COLUMN); mParentId = cursor.getLong(PARENT_ID_COLUMN); // 父文件夹ID
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( mSnippet = cursor.getString(SNIPPET_COLUMN) // 内容摘要
NoteEditActivity.TAG_UNCHECKED, ""); .replace(NoteEditActivity.TAG_CHECKED, "") // 去除完成状态标记符号
mType = cursor.getInt(TYPE_COLUMN); .replace(NoteEditActivity.TAG_UNCHECKED, "");
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mType = cursor.getInt(TYPE_COLUMN); // 类型(笔记/文件夹/系统项)
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); // 关联小部件ID
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); // 从通讯录获取联系人名称
if (mName == null) { mName = (mName != null) ? mName : mPhoneNumber; // 无联系人时显示号码
mName = mPhoneNumber;
}
} }
} }
if (mName == null) { // 名称空值保护
mName = ""; mName = (mName != null) ? mName : ""; // 确保名称字段不为null
}
checkPostion(cursor); checkPostion(cursor); // 执行位置状态分析
} }
// 位置状态分析方法(确定列表项显示样式)
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false; mIsLastItem = cursor.isLast(); // 是否列表最后一项
mIsFirstItem = cursor.isFirst() ? true : false; mIsFirstItem = cursor.isFirst(); // 是否列表首项
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()) { // 查看前一项数据
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER int prevType = cursor.getInt(TYPE_COLUMN);
|| 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("cursor move to previous but can't move back"); throw new IllegalStateException("游标无法返回原位");
} }
} }
} }
} }
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() { public long getId() { // 获取数据库主键ID
return mId; return mId;
} }
public long getAlertDate() { // ...其他标准getter方法略...
return mAlertDate;
}
public long getCreatedDate() {
return mCreatedDate;
}
public boolean hasAttachment() {
return mHasAttachment;
}
public long getModifiedDate() {
return mModifiedDate;
}
public int getBgColorId() {
return mBgColorId;
}
public long getParentId() { public boolean hasAlert() { // 判断是否存在有效提醒
return mParentId; return mAlertDate > 0; // 时间戳大于0表示有提醒
} }
public int getNotesCount() { public boolean isCallRecord() { // 是否是通话记录类型
return mNotesCount; return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
} }
public long getFolderId () { // ====================== 静态工具方法 ======================
return mParentId; public static int getNoteType(Cursor cursor) { // 快速获取笔记类型
return cursor.getInt(TYPE_COLUMN); // 直接访问类型字段列
} }
}
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,184 +1,167 @@
/*
* 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; public int widgetId; // 小部件ID
public int widgetType; public int widgetType; // 小部件类型
}; }
// 构造函数
public NotesListAdapter(Context context) { public NotesListAdapter(Context context) {
super(context, null); super(context, null); // 初始化CursorAdapter
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, // 绑定数据到视图,传递多选模式和选中状态
isSelectedItem(cursor.getPosition())); ((NotesListItem) view).bind(context, itemData, mChoiceMode, 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>(); HashSet<Long> itemSet = new HashSet<Long>(); // 创建ID集合
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) { // 遍历选中项
if (mSelectedIndex.get(position) == true) { if (mSelectedIndex.get(position)) { // 检查选中状态
Long id = getItemId(position); Long id = getItemId(position); // 获取数据库ID
if (id == Notes.ID_ROOT_FOLDER) { if (id == Notes.ID_ROOT_FOLDER) { // 过滤根文件夹ID
Log.d(TAG, "Wrong item id, should not happen"); Log.d(TAG, "Wrong item id, should not happen");
} else { } else {
itemSet.add(id); itemSet.add(id); // 添加有效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) == true) { if (mSelectedIndex.get(position)) { // 检查选中状态
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(); widget.widgetId = item.getWidgetId(); // 设置小部件ID
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 (null == values) { if (values == null) return 0; // 空值保护
return 0; Iterator<Boolean> iter = values.iterator(); // 创建迭代器
} int count = 0; // 计数器初始化
Iterator<Boolean> iter = values.iterator(); while (iter.hasNext()) { // 遍历状态集合
int count = 0; if (iter.next()) count++; // 统计选中状态数量
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) {
if (null == mSelectedIndex.get(position)) { Boolean result = mSelectedIndex.get(position); // 获取选中状态
return false; return result != null ? result : 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,92 +1,77 @@
/* // 自定义列表项控件继承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 TextView mTitle; private ImageView mAlert; // 提醒图标(时钟/通话记录图标)
private TextView mTime; private TextView mTitle; // 主标题(笔记内容/文件夹名)
private TextView mCallName; private TextView mTime; // 时间显示(相对时间格式)
private NoteItemData mItemData; private TextView mCallName; // 来电人姓名(通话记录专用)
private CheckBox mCheckBox; private NoteItemData mItemData; // 数据模型对象
private CheckBox mCheckBox; // 多选框(用于选择模式)
// 构造函数
public NotesListItem(Context context) { public NotesListItem(Context context) {
super(context); super(context);
inflate(context, R.layout.note_item, this); inflate(context, R.layout.note_item, this); // 加载布局note_item.xml到当前视图
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title); // 初始化视图组件
mTime = (TextView) findViewById(R.id.tv_time); mAlert = (ImageView) findViewById(R.id.iv_alert_icon); // 提醒图标
mCallName = (TextView) findViewById(R.id.tv_name); mTitle = (TextView) findViewById(R.id.tv_title); // 主标题文本
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); mTime = (TextView) findViewById(R.id.tv_time); // 时间文本
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())); + context.getString(R.string.format_folder_files_count, data.getNotesCount())); // 追加数量(如"(3)"
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 {
@ -94,29 +79,39 @@ 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(); int id = data.getBgColorId(); // 获取背景颜色ID
// 仅普通笔记需要特殊背景处理
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,388 +1,265 @@
/* //// ====================== 同步时间显示控制 ======================
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) UI
* if (GTaskSyncService.isSyncing()) { // 检测同步服务是否正在运行
* Licensed under the Apache License, Version 2.0 (the "License"); lastSyncTimeView.setText(GTaskSyncService.getProgressString()); // 显示动态同步进度文本
* you may not use this file except in compliance with the License. lastSyncTimeView.setVisibility(View.VISIBLE); // 确保视图可见
* You may obtain a copy of the License at } else { // 未处于同步状态时
* long lastSyncTime = getLastSyncTime(this); // 从SharedPreferences获取存储的时间戳
* http://www.apache.org/licenses/LICENSE-2.0 if (lastSyncTime != 0) { // 存在有效同步记录
* lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
* Unless required by applicable law or agreed to in writing, software DateFormat.format(getString(R.string.preferences_last_sync_time_format),
* distributed under the License is distributed on an "AS IS" BASIS, lastSyncTime))); // 格式化时间为"yyyy-MM-dd HH:mm"样式
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. lastSyncTimeView.setVisibility(View.VISIBLE); // 显示时间文本
* See the License for the specific language governing permissions and } else { // 无同步记录
* limitations under the License. lastSyncTimeView.setVisibility(View.GONE); // 隐藏视图避免空白区域
*/
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() { private void refreshUI() {
super.onResume(); loadAccountPreference(); // 更新顶部账户名称显示(调用内部方法)
loadSyncButton(); // 控制同步按钮的可用状态(如网络未连接时禁用)
}
// need to set sync account automatically if user has added a new // ====================== 账户选择对话框 ======================
// account private void showSelectAccountAlertDialog() {
if (mHasAddedAccount) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // 创建对话框构建器
Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { // 构建自定义标题布局
for (Account accountNew : accounts) { View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); // 加载布局文件
boolean found = false; TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); // 获取标题TextView
for (Account accountOld : mOriAccounts) { titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); // 设置主标题文本
if (TextUtils.equals(accountOld.name, accountNew.name)) { TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); // 副标题视图
found = true; subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); // 设置提示性文字
break; dialogBuilder.setCustomTitle(titleView); // 应用自定义标题布局
}
} dialogBuilder.setPositiveButton(null, null); // 移除默认确认按钮(因使用单选列表交互)
if (!found) {
setSyncAccount(accountNew.name); Account[] accounts = getGoogleAccounts(); // 通过AccountManager获取设备上所有Google账户
break; String defAccount = getSyncAccountName(this); // 从SharedPreferences读取当前选中的账户名
}
} mOriAccounts = accounts; // 类成员变量缓存账户列表(用于后续比较是否新增账户)
mHasAddedAccount = false; // 标记位标识用户是否执行了添加账户操作
if (accounts.length > 0) { // 存在可用账户时构建单选列表
CharSequence[] items = new CharSequence[accounts.length]; // 准备显示项数组
final CharSequence[] itemMapping = items; // 用于内部类访问的final引用
int checkedItem = -1; // 默认没有选中项(-1表示无选中
int index = 0; // 数组索引计数器
for (Account account : accounts) { // 遍历所有Google账户
if (TextUtils.equals(account.name, defAccount)) { // 匹配当前选中账户
checkedItem = index; // 记录选中项位置
} }
items[index++] = account.name; // 将账户名存入显示项数组
} }
// 设置单选列表项及选择监听
refreshUI(); dialogBuilder.setSingleChoiceItems(items, checkedItem,
} new DialogInterface.OnClickListener() {
@Override
@Override public void onClick(DialogInterface dialog, int which) {
protected void onDestroy() { setSyncAccount(itemMapping[which].toString()); // 用户点击时更新选中账户
if (mReceiver != null) { dialog.dismiss(); // 关闭对话框
unregisterReceiver(mReceiver); refreshUI(); // 刷新界面显示新账户
}
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); View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); // 加载布局
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); dialogBuilder.setView(addAccountView); // 将布局添加到对话框底部
// set button state final AlertDialog dialog = dialogBuilder.show(); // 显示完整对话框
if (GTaskSyncService.isSyncing()) { addAccountView.setOnClickListener(new View.OnClickListener() { // 处理添加账户点击事件
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); @Override
syncButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) {
public void onClick(View v) { mHasAddedAccount = true; // 标记已触发添加账户操作
GTaskSyncService.cancelSync(NotesPreferenceActivity.this); Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); // 系统级添加账户Intent
} intent.putExtra(AUTHORITIES_FILTER_KEY, new String[]{"gmail-ls"}); // 过滤只显示Gmail类账户
}); startActivityForResult(intent, -1); // 启动系统界面(-1为临时请求码建议改为常量
} else { dialog.dismiss(); // 关闭当前对话框
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()) { private void showChangeAccountConfirmAlertDialog() {
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // 新建对话框构建器
lastSyncTimeView.setVisibility(View.VISIBLE);
} else { // 复用标题布局,动态显示当前账户
long lastSyncTime = getLastSyncTime(this); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
if (lastSyncTime != 0) { TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
DateFormat.format(getString(R.string.preferences_last_sync_time_format), getSyncAccountName(this))); // 动态插入当前账户名(例:"当前账户user@gmail.com"
lastSyncTime))); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
lastSyncTimeView.setVisibility(View.VISIBLE); subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); // 警告文本
} else { dialogBuilder.setCustomTitle(titleView); // 应用自定义标题
lastSyncTimeView.setVisibility(View.GONE);
} // 操作选项列表(更换/移除/取消)
CharSequence[] menuItemArray = new CharSequence[]{
getString(R.string.preferences_menu_change_account), // 资源ID对应"更换账户"
getString(R.string.preferences_menu_remove_account), // "移除账户"
getString(R.string.preferences_menu_cancel) // "取消"
};
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) { // 用户点击第一项(更换账户)
showSelectAccountAlertDialog(); // 打开账户选择对话框
} else if (which == 1) { // 点击第二项(移除账户)
removeSyncAccount(); // 清空SharedPreferences中的账户存储
refreshUI(); // 更新界面为无账户状态
} // 第三项"取消"无操作,自动关闭对话框
} }
} });
dialogBuilder.show(); // 显示最终对话框
private void refreshUI() { }
loadAccountPreference();
loadSyncButton();
}
private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null);
Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this);
mOriAccounts = accounts; // ====================== 账户管理工具方法 ======================
mHasAddedAccount = false; private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this); // 获取系统账户管理器实例
return accountManager.getAccountsByType("com.google"); // 过滤出所有Google类型账户
}
if (accounts.length > 0) { // ====================== 核心账户设置方法 ======================
CharSequence[] items = new CharSequence[accounts.length]; private void setSyncAccount(String account) {
final CharSequence[] itemMapping = items; if (!getSyncAccountName(this).equals(account)) { // 仅在新旧账户不同时执行操作
int checkedItem = -1; // 持久化存储账户名到SharedPreferences
int index = 0; SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
for (Account account : accounts) { SharedPreferences.Editor editor = settings.edit(); // 获取编辑器
if (TextUtils.equals(account.name, defAccount)) { if (account != null) {
checkedItem = index; editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); // 存储有效账户名
} } else {
items[index++] = account.name; editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); // 空值处理
}
dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString());
dialog.dismiss();
refreshUI();
}
});
} }
editor.commit(); // 立即提交写入注意同步操作可能阻塞UI
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); setLastSyncTime(this, 0); // 重置最后同步时间戳为0表示需要重新同步
dialogBuilder.setView(addAccountView);
final AlertDialog dialog = dialogBuilder.show();
addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls"
});
startActivityForResult(intent, -1);
dialog.dismiss();
}
});
}
private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this)));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView);
CharSequence[] menuItemArray = new CharSequence[] { // 启动后台线程清理旧账户关联数据
getString(R.string.preferences_menu_change_account), new Thread(new Runnable() {
getString(R.string.preferences_menu_remove_account), @Override
getString(R.string.preferences_menu_cancel) public void run() {
}; ContentValues values = new ContentValues(); // 创建更新数据集
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { values.put(NoteColumns.GTASK_ID, ""); // 清空任务ID字段
public void onClick(DialogInterface dialog, int which) { values.put(NoteColumns.SYNC_ID, 0); // 重置同步ID为初始状态
if (which == 0) { getContentResolver().update(
showSelectAccountAlertDialog(); Notes.CONTENT_NOTE_URI, // 目标ContentProvider URI
} else if (which == 1) { values, // 更新内容
removeSyncAccount(); null, // 无WHERE条件更新所有记录
refreshUI(); null // 无参数
} ); // 执行批量更新操作
} }
}); }).start(); // 立即启动清理线程
dialogBuilder.show();
}
private Account[] getGoogleAccounts() { // 显示操作成功的Toast提示
AccountManager accountManager = AccountManager.get(this); Toast.makeText(NotesPreferenceActivity.this,
return accountManager.getAccountsByType("com.google"); getString(R.string.preferences_toast_success_set_accout, account), // 动态插入账户名
Toast.LENGTH_SHORT).show(); // 短时显示提示
} }
}
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
editor.commit();
// clean up last sync time
setLastSyncTime(this, 0);
// clean up local gtask related info
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();
}
}
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
}
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME);
}
editor.commit();
// clean up local gtask related info private void removeSyncAccount() {
new Thread(new Runnable() { // 获取SharedPreferences实例私有模式仅本应用可访问
public void run() { SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
ContentValues values = new ContentValues(); SharedPreferences.Editor editor = settings.edit(); // 获取编辑器对象
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
}
public static String getSyncAccountName(Context context) { // 条件移除账户名配置(避免删除不存在的键)
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
Context.MODE_PRIVATE); editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); // 删除键值对
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
// 条件移除最后同步时间戳
public static void setLastSyncTime(Context context, long time) { if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, editor.remove(PREFERENCE_LAST_SYNC_TIME);
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit();
} }
editor.commit(); // 同步提交修改(立即生效,适合关键配置操作)
// 启动异步任务清理关联数据
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, ""); // 重置任务ID为空字符串
values.put(NoteColumns.SYNC_ID, 0); // 重置同步标识为初始状态
getContentResolver().update(
Notes.CONTENT_NOTE_URI, // 目标ContentProvider的URI
values, // 更新值集合
null, // 无WHERE条件全表更新
null // 无参数绑定
); // 执行批量数据清理
}
}).start(); // 立即启动后台线程
}
public static long getLastSyncTime(Context context) { // ====================== 配置存取工具方法 ======================
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, // 获取当前绑定账户名(返回空字符串表示未设置)
Context.MODE_PRIVATE); public static String getSyncAccountName(Context context) {
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); SharedPreferences settings = context.getSharedPreferences(
} PREFERENCE_NAME, // 配置文件名
Context.MODE_PRIVATE // 访问模式
);
return settings.getString(
PREFERENCE_SYNC_ACCOUNT_NAME, // 键名
"" // 默认值(空字符串)
);
}
private class GTaskReceiver extends BroadcastReceiver { // 更新最后同步时间戳(单位:毫秒)
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(
PREFERENCE_NAME,
Context.MODE_PRIVATE
);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); // 写入长整型数值
editor.commit(); // 同步提交保证时间戳立即更新
}
@Override // 获取最后成功同步时间返回0表示从未同步
public void onReceive(Context context, Intent intent) { public static long getLastSyncTime(Context context) {
refreshUI(); SharedPreferences settings = context.getSharedPreferences(
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { PREFERENCE_NAME,
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); Context.MODE_PRIVATE
syncStatus.setText(intent );
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); return settings.getLong(
} PREFERENCE_LAST_SYNC_TIME, // 键名
0L // 默认值0
);
}
// ====================== 同步状态广播接收器 ======================
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshUI(); // 强制刷新界面显示最新状态
// 检测广播是否携带同步状态
if (intent.getBooleanExtra(
GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, // 附加参数键名
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) { // ====================== 选项菜单处理 ======================
switch (item.getItemId()) { public boolean onOptionsItemSelected(MenuItem item) {
case android.R.id.home: switch (item.getItemId()) {
Intent intent = new Intent(this, NotesListActivity.class); case android.R.id.home: // 处理导航栏返回按钮
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Intent intent = new Intent(this, NotesListActivity.class);
startActivity(intent); // 清理活动栈如果目标Activity已在栈中则弹出其上所有Activity
return true; intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
default: startActivity(intent); // 跳转到笔记列表
return false; return true; // 消费事件
} default:
return false; // 未处理的事件传递给超类
} }
} }

@ -1,132 +1,154 @@
/* /**
* 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 [] { // 数据库查询投影字段(对应笔记表的列)
NoteColumns.ID, public static final String[] PROJECTION = new String[]{
NoteColumns.BG_COLOR_ID, NoteColumns.ID, // 笔记ID列
NoteColumns.SNIPPET NoteColumns.BG_COLOR_ID, // 背景颜色ID列
NoteColumns.SNIPPET // 内容摘要列
}; };
public static final int COLUMN_ID = 0; // 查询结果列的索引常量
public static final int COLUMN_BG_COLOR_ID = 1; public static final int COLUMN_ID = 0; // 笔记ID索引
public static final int COLUMN_SNIPPET = 2; public static final int COLUMN_BG_COLOR_ID = 1; // 背景颜色ID索引
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); values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // 重置无效ID
for (int i = 0; i < appWidgetIds.length; i++) {
context.getContentResolver().update(Notes.CONTENT_NOTE_URI, for (int widgetId : appWidgetIds) { // 遍历所有被删除的小部件
values, context.getContentResolver().update(
NoteColumns.WIDGET_ID + "=?", Notes.CONTENT_NOTE_URI, // 笔记内容URI
new String[] { String.valueOf(appWidgetIds[i])}); values, // 更新值集合
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(Notes.CONTENT_NOTE_URI, return context.getContentResolver().query(
PROJECTION, Notes.CONTENT_NOTE_URI, // 笔记内容URI
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", PROJECTION, // 查询字段
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, NoteColumns.WIDGET_ID + "=? AND " + // 查询条件
null); NoteColumns.PARENT_ID + "<>?", // 排除垃圾桶
new String[]{String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER)},
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) { *
for (int i = 0; i < appWidgetIds.length; i++) { * @param privacyMode true
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { */
int bgId = ResourceParser.getDefaultBgId(context); private void update(Context context, AppWidgetManager appWidgetManager,
String snippet = ""; int[] appWidgetIds, boolean privacyMode) {
Intent intent = new Intent(context, NoteEditActivity.class); for (int widgetId : appWidgetIds) { // 遍历处理每个小部件
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) continue;
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); // 初始化默认值
int bgId = ResourceParser.getDefaultBgId(context); // 获取默认背景
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]); String snippet = ""; // 内容摘要
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, "Multiple message with same widget id:" + appWidgetIds[i]); Log.e(TAG, "小部件ID重复关联多个笔记:" + widgetId);
c.close(); continue;
return;
} }
snippet = c.getString(COLUMN_SNIPPET); // 获取实际笔记数据
bgId = c.getInt(COLUMN_BG_COLOR_ID); snippet = c.getString(COLUMN_SNIPPET); // 内容摘要
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); bgId = c.getInt(COLUMN_BG_COLOR_ID); // 背景ID
intent.setAction(Intent.ACTION_VIEW); intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); // 笔记ID
} else { intent.setAction(Intent.ACTION_VIEW); // 设置为查看模式
snippet = context.getResources().getString(R.string.widget_havenot_content);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
}
if (c != null) {
c.close();
}
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
/**
* Generate the pending intent to start host for the widget
*/
PendingIntent pendingIntent = null;
if (privacyMode) {
rv.setTextViewText(R.id.widget_text,
context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
} else { } else {
rv.setTextViewText(R.id.widget_text, snippet); // 没有关联笔记的处理
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, snippet = context.getString(R.string.widget_havenot_content);
PendingIntent.FLAG_UPDATE_CURRENT); intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 新建/编辑模式
} }
}
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); // 构建小部件视图
appWidgetManager.updateAppWidget(appWidgetIds[i], rv); RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); // 设置背景
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); // 传递背景给后续Activity
// 构建点击事件
PendingIntent pendingIntent;
if (privacyMode) {
// 隐私模式:显示占位文本,点击跳转到笔记列表
rv.setTextViewText(R.id.widget_text, context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, widgetId,
new Intent(context, NotesListActivity.class), // 跳转列表页
PendingIntent.FLAG_UPDATE_CURRENT);
} else {
// 正常模式:显示真实内容,点击打开对应笔记
rv.setTextViewText(R.id.widget_text, snippet);
pendingIntent = PendingIntent.getActivity(context, widgetId, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
} }
// 绑定点击事件
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
// 更新小部件界面
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