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

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

@ -14,266 +14,77 @@
* limitations under the License.
*/
package net.micode.notes.data;
import android.net.Uri;
public class Notes {//定义类
public static final String AUTHORITY = "micode_notes";
public static final String TAG = "Notes";
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
/**
* 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
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*/
public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
package net.micode.notes.data;//导入包
import android.content.Context;//
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.util.HashMap;
/**
*
*/
public class Contact {
// 静态缓存,用于存储电话号码与对应联系人名称的映射关系,避免重复查询数据库
private static HashMap<String, String> sContactCache;
// 日志标签
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
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/**
*
* @param context 访
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) {
// 初始化缓存
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
/**
* Uri to query all notes and folders
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri to query data
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
public interface NoteColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
*/
public static final String SNIPPET = "snippet";
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
* For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P> Type: INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
*/
public static final String TYPE = "type";
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id";
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P> Type : INTEGER (long) </P>
*/
public static final String VERSION = "version";
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
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";
// 优先从缓存中获取
String selection = CALLER_ID_SELECTION.replace("+",
// 构造完整查询条件:替换最小匹配长度参数
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 通过内容解析器查询联系人数据库
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,// 访问组合联系人数据
new String [] { Phone.DISPLAY_NAME },// 查询显示名字段
selection,// 动态生成的查询条件
new String[] { phoneNumber },// 查询参数(原始电话号码)
null);// 排序方式(无)
// 处理查询结果
if (cursor != null && cursor.moveToFirst()) {
try {
// 获取第一条记录的显示名称
String name = cursor.getString(0);
// 更新缓存
sContactCache.put(phoneNumber, name);
return name;
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
cursor.close();// 确保关闭Cursor释放资源
}
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");
} else {
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
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.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
/**
*
*
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "note.db";
private static final int DB_VERSION = 4;
// 数据库元数据配置
private static final String DB_NAME = "note.db";// 数据库文件名
private static final int DB_VERSION = 4;// 当前数据库版本
// 表名常量接口
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 NotesDatabaseHelper mInstance;
private static final String TAG = "NotesDatabaseHelper";// 日志标签
private static NotesDatabaseHelper mInstance; // 单例实例
// Note表建表语句
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ID + " INTEGER PRIMARY KEY," +// 笔记唯一标识
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +// 所属文件夹ID树形结构
NoteColumns.ALERTED_DATE + " 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.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.VERSION + " 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.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + // 子项数量(用于文件夹)
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +// 内容摘要
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + // 笔记类型(普通笔记、文件夹等)
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +// 关联的小部件ID
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +// 小部件类型
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +// 同步标识
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +// 本地修改标记
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +// 原始父目录(用于同步)
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +// Google Task关联ID
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 数据版本号(乐观锁)
")";
// Data表建表语句
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
DataColumns.MIME_TYPE + " TEXT NOT NULL," +
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_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.DATA1 + " INTEGER," +
DataColumns.DATA2 + " INTEGER," +
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
DataColumns.ID + " INTEGER PRIMARY KEY," +// 数据项唯一标识
DataColumns.MIME_TYPE + " TEXT NOT NULL," +// MIME类型文本、清单、媒体等
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联的笔记ID
NoteColumns.CREATED_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.DATA1 + " INTEGER," +// 扩展字段1类型相关数据
DataColumns.DATA2 + " INTEGER," +// 扩展字段2如清单项状态
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +// 扩展字段3如地理位置
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +// 扩展字段4如附件路径
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +// 扩展字段5保留字段
")";
// 数据表索引加速按笔记ID查询数据项
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
// 触发器:当更新笔记的父目录时,增加新文件夹的计数
// 场景示例把笔记A从文件夹X移动到文件夹Y时Y的计数+1
/**
* 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" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
// 触发器:当更新笔记的父目录时,减少原文件夹的计数
// 场景示例同上移动操作时X的计数-1需>0时生效
/**
* 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 +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END";
// 触发器:插入新笔记时增加所在文件夹的计数
/**
* 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" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
// 触发器:删除笔记时减少原文件夹的计数(防止负数)
/**
* 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 +
" AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END";
/**
* NOTE
* datanotesnippet
*/
/**
* Update note's content when insert data with type {@link DataConstants#NOTE}
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +// 仅处理普通笔记类型
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +// 使用新插入的内容更新摘要
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +// 通过NOTE_ID关联
" END";
/**
* NOTE
*
*/
/**
* Update note's content when data with {@link DataConstants#NOTE} type has changed
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
" AFTER UPDATE ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +// 仅处理原类型为笔记的记录
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +// 同步最新内容到摘要
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
/**
* NOTE
*
*/
/**
* 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 + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=''" +
" SET " + NoteColumns.SNIPPET + "=''" +// 清空摘要内容
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
" END";
/**
*
* notedata
*
*/
/**
* Delete datas belong to note which has been deleted
*/
@ -179,9 +199,13 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +// 根据被删除笔记ID清理数据
" END";
/**
*
*
* delete_data_on_delete
*/
/**
* Delete notes belong to folder which has been deleted
*/
@ -190,22 +214,33 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.NOTE +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +// 删除所有父目录为被删文件夹的笔记
" END";
/**
*
*
*
*/
/**
* Move notes belong to folder which has been moved to trash folder
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " +
" AFTER UPDATE ON " + TABLE.NOTE +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +// 检测是否移动到回收站
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +// 批量更新子项父目录为回收站
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + // 选择原父目录下的所有笔记
" END";
/**
*
*
* 1. ID_CALL_RECORD_FOLDER
* 2. ID_ROOT_FOLDER
* 3. ID_TEMPARAY_FOLDER
* 4. ID_TRASH_FOLER
*/
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@ -237,14 +272,14 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues();
// 插入通话记录文件夹
/**
* call record foler for call notes
*/
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);
// 插入根文件夹(默认笔记存储位置)
/**
* 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.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
// 插入临时文件夹(用于笔记移动操作时的暂存区)
/**
* 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.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
// 插入回收站(软删除数据存储位置)
/**
* create trash folder
*/
@ -293,7 +328,13 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
}
return mInstance;
}
/**
*
*
* V1 V2
* V2 V3Google Task +
* V3 V4
*/
@Override
public void onCreate(SQLiteDatabase db) {
createNoteTable(db);
@ -304,57 +345,72 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
boolean skipV2 = false;
// V1到V2升级策略完全重建表结构
if (oldVersion == 1) {
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++;
}
// V2到V3升级策略非破坏性升级
if (oldVersion == 2 && !skipV2) {
upgradeToV3(db);
reCreateTriggers = true;
reCreateTriggers = true;// 需要重建触发器
oldVersion++;
}
// V3到V4升级策略添加版本字段
if (oldVersion == 3) {
upgradeToV4(db);
oldVersion++;
}
// 重建触发器(当表结构变化可能影响触发器时)
if (reCreateTriggers) {
reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
}
// 版本检查容错
if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails");
}
}
/**
* V2
*
* 1.
* 2.
* 3.
*/
private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
createNoteTable(db);
createDataTable(db);
}
/**
* V3
*
* 1.
* 2. GTASK_IDGoogle Tasks
* 3.
*/
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_delete");
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
+ " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
// add a trash system folder// 插入回收站系统文件夹
ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
/**
* V4
* VERSION
*/
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");

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

@ -1,158 +1,130 @@
/*
* 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.
* Activity
*/
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 {
private long mNoteId;
private String mSnippet;
private static final int SNIPPET_PREW_MAX_LEN = 60;
MediaPlayer mPlayer;
private long mNoteId; // 当前提醒关联的笔记ID
private String mSnippet; // 笔记内容摘要
private static final int SNIPPET_PREW_MAX_LEN = 60; // 摘要最大显示长度
MediaPlayer mPlayer; // 媒体播放器实例
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 界面设置
requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题栏
final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // 支持锁屏显示
// 屏幕唤醒策略(仅在屏幕关闭时生效)
if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON // 保持屏幕常亮
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON // 点亮屏幕
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON // 允许锁屏
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); // 调整窗口布局
}
// 数据初始化
Intent intent = getIntent();
try {
// 从Intent URI解析笔记ID格式content://xxx/notes/123
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 从数据库获取原始内容
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
// 截取前60字符超长显示省略符
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN
? mSnippet.substring(0, SNIPPET_PREW_MAX_LEN)
+ getResources().getString(R.string.notelist_string_info)
: mSnippet;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
return; // 数据异常直接退出
}
// 媒体播放初始化
mPlayer = new MediaPlayer();
// 检查笔记有效性(未被删除)
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog();
playAlarmSound();
showActionDialog(); // 展示提醒对话框
playAlarmSound(); // 播放提醒音
} else {
finish();
finish(); // 笔记不存在则结束
}
}
// 屏幕状态检测
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
return pm.isScreenOn(); // 使用电源服务判断屏幕状态
}
// 播放提醒铃声
private void playAlarmSound() {
// 获取系统默认闹钟铃声
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 静音模式兼容处理
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 判断静音模式是否影响闹钟音量
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
} else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); // 使用闹钟音量通道
}
// 播放设置
try {
mPlayer.setDataSource(this, url);
mPlayer.prepare();
mPlayer.setLooping(true);
mPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
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();
mPlayer.setDataSource(this, url); // 设置铃声源
mPlayer.prepare(); // 预加载资源
mPlayer.setLooping(true); // 循环播放
mPlayer.start(); // 开始播放
} catch (IllegalArgumentException | SecurityException
| IllegalStateException | IOException e) {
e.printStackTrace(); // 捕获多种媒体播放异常
}
}
// 显示操作对话框
private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.app_name);
dialog.setMessage(mSnippet);
dialog.setTitle(R.string.app_name); // 设置应用名为标题
dialog.setMessage(mSnippet); // 显示内容摘要
// 主操作按钮(确认)
dialog.setPositiveButton(R.string.notealert_ok, this);
// 仅在屏幕亮起时显示"进入"按钮
if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this);
}
dialog.show().setOnDismissListener(this);
dialog.show().setOnDismissListener(this); // 绑定对话框关闭监听
}
// 对话框按钮点击处理
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
case DialogInterface.BUTTON_NEGATIVE: // "进入"按钮
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent);
break;
default:
intent.setAction(Intent.ACTION_VIEW); // 查看模式
intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递笔记ID
startActivity(intent); // 跳转编辑页面
break;
// 确认按钮无需特别处理,默认关闭
}
}
// 对话框关闭回调
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
finish();
stopAlarmSound(); // 停止铃声
finish(); // 关闭当前Activity
}
// 停止并释放媒体资源
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
mPlayer.stop(); // 停止播放
mPlayer.release(); // 释放资源
mPlayer = null; // 防止内存泄漏
}
}
}

@ -1,153 +1,149 @@
/*
* 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.
* 12/24
*/
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 {
// 默认启用状态
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 DAYS_IN_ALL_WEEK = 7;
private static final int DATE_SPINNER_MIN_VAL = 0;
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
private static final int MINUT_SPINNER_MIN_VAL = 0;
private static final int MINUT_SPINNER_MAX_VAL = 59;
private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MAX_VAL = 1;
private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner;
private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner;
private Calendar mDate;
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
private boolean mIsAm;
private boolean mIs24HourView;
private boolean mIsEnabled = DEFAULT_ENABLE_STATE;
private boolean mInitialising;
// 时间格式常量
private static final int HOURS_IN_HALF_DAY = 12; // 半日小时数AM/PM制
private static final int HOURS_IN_ALL_DAY = 24; // 全日小时数24小时制
private static final int DAYS_IN_ALL_WEEK = 7; // 日期选择范围(一周)
private static final int DATE_SPINNER_MIN_VAL = 0; // 日期选择器最小值
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; // 日期选择器最大值
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; // 24小时制小时最小值
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; // 24小时制小时最大值
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; // 12小时制小时最小值
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; // 12小时制小时最大值
private static final int MINUT_SPINNER_MIN_VAL = 0; // 分钟最小值
private static final int MINUT_SPINNER_MAX_VAL = 59; // 分钟最大值
private static final int AMPM_SPINNER_MIN_VAL = 0; // AM/PM最小值
private static final int AMPM_SPINNER_MAX_VAL = 1; // AM/PM最大值
// UI控件
private final NumberPicker mDateSpinner; // 日期选择器
private final NumberPicker mHourSpinner; // 小时选择器
private final NumberPicker mMinuteSpinner; // 分钟选择器
private final NumberPicker mAmPmSpinner; // AM/PM选择器
// 数据存储
private Calendar mDate; // 当前选择的日期时间
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; // 日期显示文本缓存
private boolean mIsAm; // 是否为上午
private boolean mIs24HourView; // 是否24小时制
private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 控件启用状态
private boolean mInitialising; // 初始化标志位
// 监听器接口
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
}
private OnDateTimeChangedListener mOnDateTimeChangedListener;
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
// 日期变更监听器
private NumberPicker.OnValueChangeListener mOnDateChangedListener =
new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 计算日期差值并更新Calendar对象
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl();
onDateTimeChanged();
updateDateControl(); // 刷新日期显示
onDateTimeChanged(); // 触发回调
}
};
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
// 小时变更监听器(处理跨日逻辑)
private NumberPicker.OnValueChangeListener mOnHourChangedListener =
new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;
Calendar cal = Calendar.getInstance();
// 12小时制特殊处理
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.add(Calendar.DAY_OF_YEAR, 1);
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.add(Calendar.DAY_OF_YEAR, -1);
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 {
// 24小时制跨日处理
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
}
// 更新小时数值
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged();
// 处理日期变更
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
}
onDateTimeChanged();
}
};
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
// 分钟变更监听器(处理小时进位)
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener =
new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue();
int min = mMinuteSpinner.getMinValue();
int max = mMinuteSpinner.getMaxValue();
int offset = 0;
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
} else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
// 处理分钟循环滚动
if (oldVal == max && newVal == min) { // 59->00
offset += 1; // 增加1小时
} else if (oldVal == min && newVal == max) { // 00->59
offset -= 1; // 减少1小时
}
// 更新小时
if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();
// 自动切换AM/PM显示
int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
mIsAm = (newHour < HOURS_IN_HALF_DAY);
updateAmPmControl();
} else {
mIsAm = true;
updateAmPmControl();
}
}
// 设置分钟值
mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged();
}
};
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
// AM/PM切换监听器
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener =
new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
// 调整小时数值
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} 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) {
this(context, System.currentTimeMillis());
}
@ -171,55 +163,59 @@ public class DateTimePicker extends FrameLayout {
this(context, date, DateFormat.is24HourFormat(context));
}
// 主构造函数
public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context);
// 初始化时间对象
mDate = Calendar.getInstance();
mInitialising = true;
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
mInitialising = true; // 设置初始化标志
// 加载布局
inflate(context, R.layout.datetime_picker, this);
// 初始化日期选择器
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
// 初始化小时选择器
mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
// 初始化分钟选择器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnLongPressUpdateInterval(100); // 长按加速间隔
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
// 初始化AM/PM选择器
String[] ampmStrings = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setDisplayedValues(ampmStrings); // 设置AM/PM本地化文本
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state
updateDateControl();
updateHourControl();
updateAmPmControl();
set24HourView(is24HourView);
// 初始化显示状态
updateDateControl(); // 更新日期显示
updateHourControl(); // 更新小时显示
updateAmPmControl(); // 更新AM/PM显示
set24HourView(is24HourView); // 设置时间格式
setCurrentDate(date); // 设置初始时间
// set to current time
setCurrentDate(date);
setEnabled(isEnabled());
// set the content descriptions
mInitialising = false;
// 设置控件启用状态
setEnabled(mIsEnabled);
mInitialising = false; // 结束初始化
}
// 启用/禁用控件
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
return;
}
if (mIsEnabled == enabled) return;
super.setEnabled(enabled);
// 级联设置子控件状态
mDateSpinner.setEnabled(enabled);
mMinuteSpinner.setEnabled(enabled);
mHourSpinner.setEnabled(enabled);
@ -227,259 +223,23 @@ public class DateTimePicker extends FrameLayout {
mIsEnabled = enabled;
}
@Override
public boolean isEnabled() {
return mIsEnabled;
}
/**
* Get the current date in millis
*
* @return the current date in millis
*/
// 获取当前时间(毫秒)
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
/**
* Set the current date
*
* @param date The current date in millis
*/
// 设置当前时间(毫秒)
public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date);
setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
}
/**
* Set the current date
*
* @param year The current year
* @param month The current month
* @param dayOfMonth The current dayOfMonth
* @param hourOfDay The current hourOfDay
* @param minute The current minute
*/
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
setCurrentHour(hourOfDay);
setCurrentMinute(minute);
}
/**
* Get current year
*
* @return The current year
*/
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
setCurrentDate(
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE)
);
}
/**
* 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 @@
/*
* 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.
NoteItemData.java
/**
*
*/
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 {
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) {
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN);
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
// 基础字段初始化
mId = cursor.getLong(ID_COLUMN); // 获取笔记唯一ID
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); // 提醒时间戳0表示无提醒
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); // 背景颜色标识ID
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); // 创建时间戳
mHasAttachment = cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0; // 是否有附件(布尔值转换)
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); // 最后修改时间戳
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); // 关联笔记数量(用于文件夹类型)
mParentId = cursor.getLong(PARENT_ID_COLUMN); // 父文件夹ID
mSnippet = cursor.getString(SNIPPET_COLUMN) // 内容摘要
.replace(NoteEditActivity.TAG_CHECKED, "") // 去除完成状态标记符号
.replace(NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN); // 类型(笔记/文件夹/系统项)
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); // 关联小部件ID
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); // 小部件类型
// 通话记录特殊处理
mPhoneNumber = ""; // 初始化电话号码
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { // 判断是否为通话记录类型
// 通过内容解析器获取通话号码
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) {
mName = mPhoneNumber;
}
if (!TextUtils.isEmpty(mPhoneNumber)) { // 有效号码处理
mName = Contact.getContact(context, mPhoneNumber); // 从通讯录获取联系人名称
mName = (mName != null) ? mName : mPhoneNumber; // 无联系人时显示号码
}
}
if (mName == null) {
mName = "";
}
checkPostion(cursor);
// 名称空值保护
mName = (mName != null) ? mName : ""; // 确保名称字段不为null
checkPostion(cursor); // 执行位置状态分析
}
// 位置状态分析方法(确定列表项显示样式)
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
mIsLastItem = cursor.isLast(); // 是否列表最后一项
mIsFirstItem = cursor.isFirst(); // 是否列表首项
mIsOnlyOneItem = (cursor.getCount() == 1); // 是否唯一项
mIsMultiNotesFollowingFolder = false; // 重置多项跟随状态
mIsOneNoteFollowingFolder = false; // 重置单项跟随状态
// 仅普通笔记需要检查文件夹跟随状态
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition();
if (cursor.moveToPrevious()) {
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
int position = cursor.getPosition(); // 记录当前位置
if (cursor.moveToPrevious()) { // 查看前一项数据
int prevType = cursor.getInt(TYPE_COLUMN);
// 判断前项是否为文件夹类型
if (prevType == Notes.TYPE_FOLDER || prevType == Notes.TYPE_SYSTEM) {
// 根据剩余项数量判断跟随类型
if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true;
mIsMultiNotesFollowingFolder = true; // 多个笔记跟随文件夹
} else {
mIsOneNoteFollowingFolder = true;
mIsOneNoteFollowingFolder = true; // 单个笔记跟随文件夹
}
}
// 游标归位安全检查
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;
}
public boolean isMultiFollowingFolder() {
public boolean isMultiFollowingFolder() { // 是否属于多笔记组中的第一个
return mIsMultiNotesFollowingFolder;
}
public boolean isLast() {
public boolean isLast() { // 是否列表最后一项
return mIsLastItem;
}
public String getCallName() {
return mName;
public String getCallName() { // 获取通话记录联系人名称
return mName; // 格式:联系人名 或 电话号码
}
public boolean isFirst() {
public boolean isFirst() { // 是否列表首项
return mIsFirstItem;
}
public boolean isSingle() {
public boolean isSingle() { // 是否唯一列表项
return mIsOnlyOneItem;
}
public long getId() {
public long getId() { // 获取数据库主键ID
return mId;
}
public long getAlertDate() {
return mAlertDate;
}
public long getCreatedDate() {
return mCreatedDate;
}
// ...其他标准getter方法略...
public boolean hasAttachment() {
return mHasAttachment;
public boolean hasAlert() { // 判断是否存在有效提醒
return mAlertDate > 0; // 时间戳大于0表示有提醒
}
public long getModifiedDate() {
return mModifiedDate;
}
public int getBgColorId() {
return mBgColorId;
}
public long getParentId() {
return mParentId;
}
public int getNotesCount() {
return mNotesCount;
}
public long getFolderId () {
return mParentId;
public boolean isCallRecord() { // 是否是通话记录类型
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
public int getType() {
return mType;
// ====================== 静态工具方法 ======================
public static int getNoteType(Cursor cursor) { // 快速获取笔记类型
return cursor.getInt(TYPE_COLUMN); // 直接访问类型字段列
}
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 {
// 日志标签
private static final String TAG = "NotesListAdapter";
private Context mContext;
private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount;
private boolean mChoiceMode;
private Context mContext; // 上下文对象
private HashMap<Integer, Boolean> mSelectedIndex; // 存储选中位置的映射表(位置 -> 选中状态)
private int mNotesCount; // 普通笔记总数(排除文件夹)
private boolean mChoiceMode; // 是否处于多选模式
// 小部件属性封装类
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
};
public int widgetId; // 小部件ID
public int widgetType; // 小部件类型
}
// 构造函数
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
mContext = context;
mNotesCount = 0;
super(context, null); // 初始化CursorAdapter
mSelectedIndex = new HashMap<Integer, Boolean>(); // 初始化选中状态容器
mContext = context; // 保存上下文引用
mNotesCount = 0; // 初始化笔记数量
}
// 创建新列表项视图
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context);
return new NotesListItem(context); // 实例化自定义列表项视图
}
// 绑定数据到列表项视图
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor);
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
if (view instanceof NotesListItem) { // 类型安全检查
NoteItemData itemData = new NoteItemData(context, cursor); // 创建数据包装对象
// 绑定数据到视图,传递多选模式和选中状态
((NotesListItem) view).bind(context, itemData, mChoiceMode, isSelectedItem(cursor.getPosition()));
}
}
// 设置指定位置选中状态
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked);
notifyDataSetChanged();
mSelectedIndex.put(position, checked); // 更新选中状态映射表
notifyDataSetChanged(); // 触发视图刷新
}
// 检查是否处于多选模式
public boolean isInChoiceMode() {
return mChoiceMode;
return mChoiceMode; // 返回当前多选模式状态
}
// 切换多选模式
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear();
mChoiceMode = mode;
mSelectedIndex.clear(); // 清空选中记录
mChoiceMode = mode; // 更新多选模式状态
}
// 全选/取消全选操作
public void selectAll(boolean checked) {
Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) {
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked);
Cursor cursor = getCursor(); // 获取数据游标
for (int i = 0; i < getCount(); i++) { // 遍历所有数据项
if (cursor.moveToPosition(i)) { // 移动游标到指定位置
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { // 仅处理普通笔记类型
setCheckedItem(i, checked); // 设置选中状态
}
}
}
}
// 获取选中项ID集合
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) {
HashSet<Long> itemSet = new HashSet<Long>(); // 创建ID集合
for (Integer position : mSelectedIndex.keySet()) { // 遍历选中项
if (mSelectedIndex.get(position)) { // 检查选中状态
Long id = getItemId(position); // 获取数据库ID
if (id == Notes.ID_ROOT_FOLDER) { // 过滤根文件夹ID
Log.d(TAG, "Wrong item id, should not happen");
} else {
itemSet.add(id);
itemSet.add(id); // 添加有效ID到集合
}
}
}
return itemSet;
return itemSet; // 返回结果集合
}
// 获取选中项的小部件属性
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position);
for (Integer position : mSelectedIndex.keySet()) { // 遍历选中位置
if (mSelectedIndex.get(position)) { // 检查选中状态
Cursor c = (Cursor) getItem(position); // 获取对应游标
if (c != null) {
AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType();
itemSet.add(widget);
/**
* Don't close cursor here, only the adapter could close it
*/
AppWidgetAttribute widget = new AppWidgetAttribute(); // 创建属性对象
NoteItemData item = new NoteItemData(mContext, c); // 包装数据
widget.widgetId = item.getWidgetId(); // 设置小部件ID
widget.widgetType = item.getWidgetType(); // 设置小部件类型
itemSet.add(widget); // 添加到集合
} else {
Log.e(TAG, "Invalid cursor");
return null;
Log.e(TAG, "Invalid cursor"); // 错误日志记录
return null; // 返回空值
}
}
}
return itemSet;
return itemSet; // 返回结果集合
}
// 统计选中项数量
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
return 0;
}
Iterator<Boolean> iter = values.iterator();
int count = 0;
while (iter.hasNext()) {
if (true == iter.next()) {
count++;
}
Collection<Boolean> values = mSelectedIndex.values(); // 获取所有状态值
if (values == null) return 0; // 空值保护
Iterator<Boolean> iter = values.iterator(); // 创建迭代器
int count = 0; // 计数器初始化
while (iter.hasNext()) { // 遍历状态集合
if (iter.next()) count++; // 统计选中状态数量
}
return count;
return count; // 返回总数
}
// 检查是否全选
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount);
int checkedCount = getSelectedCount(); // 获取当前选中数
return (checkedCount != 0 && checkedCount == mNotesCount); // 比较总数
}
// 检查指定位置是否选中
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false;
}
return mSelectedIndex.get(position);
Boolean result = mSelectedIndex.get(position); // 获取选中状态
return result != null ? result : false; // 空值安全处理
}
// 数据变更回调
@Override
protected void onContentChanged() {
super.onContentChanged();
calcNotesCount();
super.onContentChanged(); // 调用父类方法
calcNotesCount(); // 重新计算笔记数量
}
// 切换数据游标
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
calcNotesCount();
super.changeCursor(cursor); // 调用父类方法
calcNotesCount(); // 重新计算笔记数量
}
// 计算普通笔记数量
private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i);
mNotesCount = 0; // 重置计数器
for (int i = 0; i < getCount(); i++) { // 遍历所有数据项
Cursor c = (Cursor) getItem(i); // 获取游标对象
if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++;
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { // 类型检查
mNotesCount++; // 计数普通笔记
}
} else {
Log.e(TAG, "Invalid cursor");
return;
}
Log.e(TAG, "Invalid cursor"); // 错误日志
return; // 提前退出
}
}
}

@ -1,92 +1,77 @@
/*
* 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;
// 自定义列表项控件继承LinearLayout实现复合视图
public class NotesListItem extends LinearLayout {
private ImageView mAlert;
private TextView mTitle;
private TextView mTime;
private TextView mCallName;
private NoteItemData mItemData;
private CheckBox mCheckBox;
// 声明视图组件
private ImageView mAlert; // 提醒图标(时钟/通话记录图标)
private TextView mTitle; // 主标题(笔记内容/文件夹名)
private TextView mTime; // 时间显示(相对时间格式)
private TextView mCallName; // 来电人姓名(通话记录专用)
private NoteItemData mItemData; // 数据模型对象
private CheckBox mCheckBox; // 多选框(用于选择模式)
// 构造函数
public NotesListItem(Context context) {
super(context);
inflate(context, R.layout.note_item, this);
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name);
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
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); // 时间文本
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) {
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
mCheckBox.setVisibility(View.VISIBLE); // 仅普通笔记显示复选框
mCheckBox.setChecked(checked); // 设置选中状态
} else {
mCheckBox.setVisibility(View.GONE);
mCheckBox.setVisibility(View.GONE); // 文件夹/通话记录隐藏复选框
}
mItemData = data;
mItemData = data; // 缓存数据对象
// 分支1通话记录文件夹
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record);
mCallName.setVisibility(View.GONE); // 隐藏来电人姓名
mAlert.setVisibility(View.VISIBLE); // 显示通话记录图标
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 主标题样式
mTitle.setText(context.getString(R.string.call_record_folder_name) // "通话记录"
+ context.getString(R.string.format_folder_files_count, data.getNotesCount())); // 追加数量(如"(3)"
mAlert.setImageResource(R.drawable.call_record); // 设置通话记录图标
// 分支2通话记录条目
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mCallName.setVisibility(View.VISIBLE); // 显示来电人姓名
mCallName.setText(data.getCallName()); // 设置来电人(如"张三"
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); // 副标题样式
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 格式化内容预览
if (data.hasAlert()) { // 判断是否有提醒
mAlert.setImageResource(R.drawable.clock); // 显示时钟图标
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
mAlert.setVisibility(View.GONE); // 无提醒隐藏图标
}
// 分支3普通笔记/文件夹
} else {
mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
mCallName.setVisibility(View.GONE); // 隐藏来电人姓名
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 主样式
// 子分支3-1文件夹类型
if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
mTitle.setText(data.getSnippet() // 文件夹名称
+ context.getString(R.string.format_folder_files_count, // 追加数量
data.getNotesCount()));
mAlert.setVisibility(View.GONE);
mAlert.setVisibility(View.GONE); // 文件夹不显示图标
// 子分支3-2普通笔记
} else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 内容预览
if (data.hasAlert()) { // 提醒处理
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
@ -94,29 +79,39 @@ public class NotesListItem extends LinearLayout {
}
}
}
// 设置时间显示(例如"2小时前"
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
setBackground(data);
setBackground(data); // 根据位置设置背景样式
}
// 背景设置逻辑(实现列表项不同位置的圆角效果)
private void setBackground(NoteItemData data) {
int id = data.getBgColorId();
int id = data.getBgColorId(); // 获取背景颜色ID
// 仅普通笔记需要特殊背景处理
if (data.getType() == Notes.TYPE_NOTE) {
// 条件1单一条目或跟随文件夹的第一个条目
if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); // 单一行圆角
// 条件2列表最后一项
} else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); // 底部圆角
// 条件3列表第一项或多条目组的第一个
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); // 顶部圆角
// 默认:中间条目
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); // 直角背景
}
} else {
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
// 其他类型(文件夹/通话记录)使用默认背景
}
public NoteItemData getItemData() {
return mItemData;
}
public NoteItemData getItemData() {
return mItemData; // 返回成员变量存储的数据模型引用
}

@ -1,388 +1,265 @@
/*
* 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.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
public class NotesPreferenceActivity extends PreferenceActivity {
public static final String PREFERENCE_NAME = "notes_preferences";
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
private static final String AUTHORITIES_FILTER_KEY = "authorities";
private PreferenceCategory mAccountCategory;
private GTaskReceiver mReceiver;
private Account[] mOriAccounts;
private boolean mHasAddedAccount;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true);
addPreferencesFromResource(R.xml.preferences);
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter);
mOriAccounts = null;
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true);
}
@Override
protected void onResume() {
super.onResume();
// need to set sync account automatically if user has added a new
// account
if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
for (Account accountNew : accounts) {
boolean found = false;
for (Account accountOld : mOriAccounts) {
if (TextUtils.equals(accountOld.name, accountNew.name)) {
found = true;
break;
}
}
if (!found) {
setSyncAccount(accountNew.name);
break;
}
}
}
}
refreshUI();
}
@Override
protected void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
super.onDestroy();
}
private void loadAccountPreference() {
mAccountCategory.removeAll();
Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary));
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account
showSelectAccountAlertDialog();
} else {
// if the account has already been set, we need to promp
// user about the risk
showChangeAccountConfirmAlertDialog();
}
} else {
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
}
return true;
}
});
mAccountCategory.addPreference(accountPref);
}
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state
if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}
});
} else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.startSync(NotesPreferenceActivity.this);
}
});
}
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time
if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) {
//// ====================== 同步时间显示控制 ======================
UI
if (GTaskSyncService.isSyncing()) { // 检测同步服务是否正在运行
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); // 显示动态同步进度文本
lastSyncTimeView.setVisibility(View.VISIBLE); // 确保视图可见
} else { // 未处于同步状态时
long lastSyncTime = getLastSyncTime(this); // 从SharedPreferences获取存储的时间戳
if (lastSyncTime != 0) { // 存在有效同步记录
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime)));
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
lastSyncTimeView.setVisibility(View.GONE);
}
lastSyncTime))); // 格式化时间为"yyyy-MM-dd HH:mm"样式
lastSyncTimeView.setVisibility(View.VISIBLE); // 显示时间文本
} else { // 无同步记录
lastSyncTimeView.setVisibility(View.GONE); // 隐藏视图避免空白区域
}
}
// ====================== 界面刷新方法 ======================
private void refreshUI() {
loadAccountPreference();
loadSyncButton();
loadAccountPreference(); // 更新顶部账户名称显示(调用内部方法)
loadSyncButton(); // 控制同步按钮的可用状态(如网络未连接时禁用)
}
// ====================== 账户选择对话框 ======================
private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // 创建对话框构建器
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
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));
// 构建自定义标题布局
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); // 加载布局文件
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); // 获取标题TextView
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.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null);
dialogBuilder.setPositiveButton(null, null); // 移除默认确认按钮(因使用单选列表交互)
Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this);
Account[] accounts = getGoogleAccounts(); // 通过AccountManager获取设备上所有Google账户
String defAccount = getSyncAccountName(this); // 从SharedPreferences读取当前选中的账户名
mOriAccounts = accounts;
mHasAddedAccount = false;
mOriAccounts = accounts; // 类成员变量缓存账户列表(用于后续比较是否新增账户)
mHasAddedAccount = false; // 标记位标识用户是否执行了添加账户操作
if (accounts.length > 0) {
CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items;
int checkedItem = -1;
int index = 0;
for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index;
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;
items[index++] = account.name; // 将账户名存入显示项数组
}
// 设置单选列表项及选择监听
dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString());
dialog.dismiss();
refreshUI();
setSyncAccount(itemMapping[which].toString()); // 用户点击时更新选中账户
dialog.dismiss(); // 关闭对话框
refreshUI(); // 刷新界面显示新账户
}
});
}
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView);
// 添加"新建账户"入口
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); // 加载布局
dialogBuilder.setView(addAccountView); // 将布局添加到对话框底部
final AlertDialog dialog = dialogBuilder.show();
addAccountView.setOnClickListener(new View.OnClickListener() {
final AlertDialog dialog = dialogBuilder.show(); // 显示完整对话框
addAccountView.setOnClickListener(new View.OnClickListener() { // 处理添加账户点击事件
@Override
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();
mHasAddedAccount = true; // 标记已触发添加账户操作
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); // 系统级添加账户Intent
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[]{"gmail-ls"}); // 过滤只显示Gmail类账户
startActivityForResult(intent, -1); // 启动系统界面(-1为临时请求码建议改为常量
dialog.dismiss(); // 关闭当前对话框
}
});
}
// ====================== 账户变更确认对话框 ======================
private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // 新建对话框构建器
// 复用标题布局,动态显示当前账户
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this)));
getSyncAccountName(this))); // 动态插入当前账户名(例:"当前账户user@gmail.com"
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView);
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),
getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel)
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();
refreshUI();
}
if (which == 0) { // 用户点击第一项(更换账户)
showSelectAccountAlertDialog(); // 打开账户选择对话框
} else if (which == 1) { // 点击第二项(移除账户)
removeSyncAccount(); // 清空SharedPreferences中的账户存储
refreshUI(); // 更新界面为无账户状态
} // 第三项"取消"无操作,自动关闭对话框
}
});
dialogBuilder.show();
dialogBuilder.show(); // 显示最终对话框
}
// ====================== 账户管理工具方法 ======================
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
AccountManager accountManager = AccountManager.get(this); // 获取系统账户管理器实例
return accountManager.getAccountsByType("com.google"); // 过滤出所有Google类型账户
}
// ====================== 核心账户设置方法 ======================
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
if (!getSyncAccountName(this).equals(account)) { // 仅在新旧账户不同时执行操作
// 持久化存储账户名到SharedPreferences
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
SharedPreferences.Editor editor = settings.edit(); // 获取编辑器
if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); // 存储有效账户名
} else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); // 空值处理
}
editor.commit();
editor.commit(); // 立即提交写入注意同步操作可能阻塞UI
// clean up last sync time
setLastSyncTime(this, 0);
setLastSyncTime(this, 0); // 重置最后同步时间戳为0表示需要重新同步
// clean up local gtask related info
// 启动后台线程清理旧账户关联数据
new Thread(new Runnable() {
@Override
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();
ContentValues values = new ContentValues(); // 创建更新数据集
values.put(NoteColumns.GTASK_ID, ""); // 清空任务ID字段
values.put(NoteColumns.SYNC_ID, 0); // 重置同步ID为初始状态
getContentResolver().update(
Notes.CONTENT_NOTE_URI, // 目标ContentProvider URI
values, // 更新内容
null, // 无WHERE条件更新所有记录
null // 无参数
); // 执行批量更新操作
}
}).start(); // 立即启动清理线程
// 显示操作成功的Toast提示
Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();
getString(R.string.preferences_toast_success_set_accout, account), // 动态插入账户名
Toast.LENGTH_SHORT).show(); // 短时显示提示
}
}
private void removeSyncAccount() {
// 获取SharedPreferences实例私有模式仅本应用可访问
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
SharedPreferences.Editor editor = settings.edit(); // 获取编辑器对象
// 条件移除账户名配置(避免删除不存在的键)
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(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();
editor.commit(); // 同步提交修改(立即生效,适合关键配置操作)
// 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);
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();
}).start(); // 立即启动后台线程
}
// ====================== 配置存取工具方法 ======================
// 获取当前绑定账户名(返回空字符串表示未设置)
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
SharedPreferences settings = context.getSharedPreferences(
PREFERENCE_NAME, // 配置文件名
Context.MODE_PRIVATE // 访问模式
);
return settings.getString(
PREFERENCE_SYNC_ACCOUNT_NAME, // 键名
"" // 默认值(空字符串)
);
}
// 更新最后同步时间戳(单位:毫秒)
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
SharedPreferences settings = context.getSharedPreferences(
PREFERENCE_NAME,
Context.MODE_PRIVATE
);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); // 写入长整型数值
editor.commit(); // 同步提交保证时间戳立即更新
}
// 获取最后成功同步时间返回0表示从未同步
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
SharedPreferences settings = context.getSharedPreferences(
PREFERENCE_NAME,
Context.MODE_PRIVATE
);
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);
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
}
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()) {
case android.R.id.home:
case android.R.id.home: // 处理导航栏返回按钮
Intent intent = new Intent(this, NotesListActivity.class);
// 清理活动栈如果目标Activity已在栈中则弹出其上所有Activity
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
startActivity(intent); // 跳转到笔记列表
return true; // 消费事件
default:
return false;
}
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 static final String[] PROJECTION = new String[]{
NoteColumns.ID,
NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET
NoteColumns.ID, // 笔记ID列
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_SNIPPET = 2;
// 查询结果列的索引常量
public static final int COLUMN_ID = 0; // 笔记ID索引
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
public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues();
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
for (int i = 0; i < appWidgetIds.length; i++) {
context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
values,
NoteColumns.WIDGET_ID + "=?",
new String[] { String.valueOf(appWidgetIds[i])});
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // 重置无效ID
for (int widgetId : appWidgetIds) { // 遍历所有被删除的小部件
context.getContentResolver().update(
Notes.CONTENT_NOTE_URI, // 笔记内容URI
values, // 更新值集合
NoteColumns.WIDGET_ID + "=?",// 按小部件ID筛选
new String[]{String.valueOf(widgetId)}
);
}
}
/**
*
* @param context
* @param widgetId ID
* @return Cursor
*
*/
private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
return context.getContentResolver().query(
Notes.CONTENT_NOTE_URI, // 笔记内容URI
PROJECTION, // 查询字段
NoteColumns.WIDGET_ID + "=? AND " + // 查询条件
NoteColumns.PARENT_ID + "<>?", // 排除垃圾桶
new String[]{String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER)},
null);
null // 排序方式
);
}
/**
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
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++) {
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
int bgId = ResourceParser.getDefaultBgId(context);
String snippet = "";
Intent intent = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
/**
*
* @param privacyMode true
*/
private void update(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds, boolean privacyMode) {
for (int widgetId : appWidgetIds) { // 遍历处理每个小部件
if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) continue;
// 初始化默认值
int bgId = ResourceParser.getDefaultBgId(context); // 获取默认背景
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()) {
// 数据校验防止相同小部件ID关联多个笔记
if (c.getCount() > 1) {
Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
c.close();
return;
Log.e(TAG, "小部件ID重复关联多个笔记:" + widgetId);
continue;
}
snippet = c.getString(COLUMN_SNIPPET);
bgId = c.getInt(COLUMN_BG_COLOR_ID);
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
intent.setAction(Intent.ACTION_VIEW);
// 获取实际笔记数据
snippet = c.getString(COLUMN_SNIPPET); // 内容摘要
bgId = c.getInt(COLUMN_BG_COLOR_ID); // 背景ID
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); // 笔记ID
intent.setAction(Intent.ACTION_VIEW); // 设置为查看模式
} else {
snippet = context.getResources().getString(R.string.widget_havenot_content);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
// 没有关联笔记的处理
snippet = context.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;
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, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
// 隐私模式:显示占位文本,点击跳转到笔记列表
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, appWidgetIds[i], intent,
pendingIntent = PendingIntent.getActivity(context, widgetId, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
// 绑定点击事件
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
// 更新小部件界面
appWidgetManager.updateAppWidget(widgetId, rv);
}
}
//----------- 抽象方法(子类必须实现) -----------
/**
* ID
* @param bgId
* @return ID
*/
protected abstract int getBgResourceId(int bgId);
/**
* ID
*/
protected abstract int getLayoutId();
/**
*
*/
protected abstract int getWidgetType();
}

Loading…
Cancel
Save