pull/5/head
HBK 7 months ago
parent f0463b973e
commit 752808fe66

@ -25,49 +25,80 @@ import android.util.Log;
import java.util.HashMap;
/**
* Contact
* 使
*/
public class Contact {
// 用于缓存电话号码到联系人名称的映射,减少重复查询
private static HashMap<String, String> sContactCache;
// 用于日志输出的 TAG
private static final String TAG = "Contact";
// 查询联系人信息的选择条件,目的是通过电话号码匹配联系人
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 "
+ ",?) 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) {
// 如果缓存为空,则初始化缓存
if (sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
if(sContactCache.containsKey(phoneNumber)) {
// 如果缓存中已经有该电话号码对应的联系人名称,则直接返回缓存中的名称
if (sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 使用 PhoneNumberUtils 将电话号码转换为适合匹配的格式
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, // 查询数据的 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());
// 如果出现查询结果格式错误,记录日志并返回 null
Log.e(TAG, "Cursor get string error " + e.toString());
return null;
} finally {
// 确保查询完成后关闭 Cursor避免内存泄漏
cursor.close();
}
} else {
// 如果没有匹配的联系人,记录日志并返回 null
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}

@ -17,24 +17,36 @@
package net.micode.notes.data;
import android.net.Uri;
/**
* Notes URI
*
*/
public class Notes {
// Content provider 的 authority用于在应用内唯一标识 Notes 数据。
public static final String AUTHORITY = "micode_notes";
// 用于日志输出的 TAG
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;
// 定义笔记、文件夹、系统文件类型的常量
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
* ID
* {@link Notes#ID_ROOT_FOLDER}
* {@link Notes#ID_TEMPARAY_FOLDER}
* {@link Notes#ID_CALL_RECORD_FOLDER}
*/
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;
// Intent 中用到的额外数据键名
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";
@ -42,238 +54,256 @@ public class Notes {
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 final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
// DataConstants 用于指定笔记和通话记录的 MIME 类型
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/**
* Uri to query all notes and folders
* URI
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri to query data
* URI
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
/**
* NoteColumns
*/
public interface NoteColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
* ID
* <P>: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
* ID
* <P>: INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*
* <P>: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*
* <P>: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*
* <P>: INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
*
* <P>: TEXT </P>
*/
public static final String SNIPPET = "snippet";
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
* ID
* <P>: INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
*
* <P>: INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
* ID
* <P>: 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>
*
* <P>: INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
*
* <P>: INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
*
* <P>: INTEGER </P>
*/
public static final String TYPE = "type";
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
* ID
* <P>: INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id";
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*
* <P>: INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
* ID
* <P>: INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
* gtask ID Google
* <P>: TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P> Type : INTEGER (long) </P>
*
* <P>: INTEGER (long) </P>
*/
public static final String VERSION = "version";
}
/**
* DataColumns
*/
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
* ID
* <P>: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
* MIME
* <P>: 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>
* ID
* <P>: INTEGER (long) </P>
*/
public static final String NOTE_ID = "note_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*
* <P>: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*
* <P>: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Data's content
* <P> Type: TEXT </P>
*
* <P>: 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>
* MIME
* <P>: 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>
* MIME
* <P>: 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>
* MIME TEXT
* <P>: 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>
* MIME TEXT
* <P>: 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>
* MIME TEXT
* <P>: TEXT </P>
*/
public static final String DATA5 = "data5";
}
/**
* TextNote
*/
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>
* checklist
* <P>: INTEGER, 1: 0: </P>
*/
public static final String MODE = DATA1;
// 表示文本笔记的 MIME 类型
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";
// 文本笔记的 URI
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
/**
* CallNote
*/
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
*
* <P>: INTEGER (long) </P>
*/
public static final String CALL_DATE = DATA1;
/**
* Phone number for this record
* <P> Type: TEXT </P>
*
* <P>: 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";
// 通话记录的 URI
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
}
}

@ -26,197 +26,103 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
/**
* NotesDatabaseHelper SQLite
* SQLiteOpenHelper
*
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 数据库名称和版本
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 DATA = "data";
public static final String NOTE = "note"; // 笔记表
public static final String DATA = "data"; // 数据表
}
// 日志标签
private static final String TAG = "NotesDatabaseHelper";
// NotesDatabaseHelper 的单例实例
private static NotesDatabaseHelper mInstance;
// 创建笔记表的 SQL 语句
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.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" +
")";
"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.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" +
")";
// 创建数据表的 SQL 语句
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 ''" +
")";
"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 ''" +
")";
// 为数据表创建索引
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/**
* Increase folder's note count when move note to the folder
*/
// 创建触发器以更新文件夹内笔记的数量(增加和减少)
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
/**
* Decrease folder's note count when move note from folder
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" 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
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " +
" AFTER INSERT ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" 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
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END";
/**
* 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 + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
"CREATE TRIGGER increase_folder_count_on_update "+
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
/**
* 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 + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
// 其他触发器省略,具体说明了对笔记和数据的更新、删除时的行为
/**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted
* NotesDatabaseHelper
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
" AFTER delete ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=''" +
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
" END";
/**
* Delete datas belong to note which has been deleted
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
* Delete notes belong to folder which has been deleted
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.NOTE +
" 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 +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
*
*/
public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db);
createSystemFolder(db);
db.execSQL(CREATE_NOTE_TABLE_SQL); // 创建笔记表
reCreateNoteTableTriggers(db); // 重新创建触发器
createSystemFolder(db); // 创建系统文件夹(如根文件夹、回收站等)
Log.d(TAG, "note table has been created");
}
/**
*
*/
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
@ -235,41 +141,39 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
/**
*
*/
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);
db.insert(TABLE.NOTE, null, values);
/**
* root folder which is default folder
*/
// 创建根文件夹
values.clear();
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
*/
// 创建临时文件夹
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* create trash folder
*/
// 创建回收站文件夹
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
/**
*
*/
public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db);
@ -277,6 +181,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "data table has been created");
}
/**
*
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
@ -287,6 +194,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
/**
* NotesDatabaseHelper
*/
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
@ -307,7 +217,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
if (oldVersion == 1) {
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
skipV2 = true; // 这次升级包含从v2到v3的升级
oldVersion++;
}
@ -333,6 +243,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
}
}
// 升级数据库到版本2删除旧表并重新创建
private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
@ -340,23 +251,28 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
createDataTable(db);
}
// 升级数据库到版本3删除无用的触发器并添加新列
private void upgradeToV3(SQLiteDatabase db) {
// 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
// 为笔记表添加 gtask_id 列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
// 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);
}
// 升级数据库到版本4添加版本号列
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}
}

@ -16,7 +16,6 @@
package net.micode.notes.data;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
@ -34,60 +33,72 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
public class NotesProvider extends ContentProvider {
// URI Matcher 用于将 URI 映射到相应的操作
private static final UriMatcher mMatcher;
// 数据库帮助类实例
private NotesDatabaseHelper mHelper;
// 日志标签
private static final String TAG = "NotesProvider";
// 定义常量用于 URI 匹配
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 Matcher
static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); // 匹配所有笔记
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); // 匹配单个笔记
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); // 匹配所有数据
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); // 匹配单个数据
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); // 匹配搜索
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' 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;
+ 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;
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override
public boolean onCreate() {
// 初始化 NotesDatabaseHelper 实例
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
/**
* URI
*
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return Cursor
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
String sortOrder) {
Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
@ -112,6 +123,7 @@ public class NotesProvider extends ContentProvider {
break;
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");
@ -147,6 +159,13 @@ public class NotesProvider extends ContentProvider {
return c;
}
/**
* URI
*
* @param uri URI
* @param values
* @return URI
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();
@ -166,13 +185,12 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
// 通知 URI 的变化
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
@ -181,125 +199,13 @@ public class NotesProvider extends ContentProvider {
return ContentUris.withAppendedId(uri, insertedId);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
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);
if (noteId <= 0) {
break;
}
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true;
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
@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;
switch (mMatcher.match(uri)) {
case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs);
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
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:
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
updateData = true;
break;
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;
}
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(TABLE.NOTE);
sql.append(" SET ");
sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
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) {
selectString = selectString.replaceFirst("\\?", args);
}
sql.append(selectString);
}
mHelper.getWritableDatabase().execSQL(sql.toString());
}
/**
* URI
*
* @param uri URI
* @param selection
* @param selectionArgs
* @return
*/
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}

@ -15,6 +15,7 @@
*/
package net.micode.notes.model;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
@ -33,27 +34,31 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
/**
* Note
*/
public class Note {
private ContentValues mNoteDiffValues;
private NoteData mNoteData;
private static final String TAG = "Note";
private ContentValues mNoteDiffValues; // 存储与笔记相关的差异数据(修改内容)
private NoteData mNoteData; // 存储笔记的具体内容(如文本数据、通话数据等)
private static final String TAG = "Note"; // 用于日志输出的标签
/**
* Create a new note id for adding a new note to databases
* ID
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database
// 创建一个新的笔记内容,存入数据库
ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis();
long createdTime = System.currentTimeMillis(); // 获取当前时间戳作为创建时间
values.put(NoteColumns.CREATED_DATE, createdTime);
values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 设置笔记类型
values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记本地已修改
values.put(NoteColumns.PARENT_ID, folderId); // 设置父文件夹ID
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
long noteId = 0;
try {
// 从返回的URI中获取笔记的ID
noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
@ -66,78 +71,92 @@ public class Note {
}
public Note() {
mNoteDiffValues = new ContentValues();
mNoteData = new NoteData();
mNoteDiffValues = new ContentValues(); // 初始化存储笔记修改内容的ContentValues
mNoteData = new NoteData(); // 初始化笔记数据对象
}
// 设置笔记的某个字段的值
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地修改
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新时间戳
}
// 设置文本数据
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
// 设置文本数据的ID
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
// 获取文本数据的ID
public long getTextDataId() {
return mNoteData.mTextDataId;
}
// 设置通话数据的ID
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}
// 设置通话数据
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
}
// 判断笔记是否有本地修改
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
/**
*
* @param context
* @param noteId ID
* @return truefalse
*/
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
if (!isLocalModified()) {
return true;
return true; // 如果没有本地修改,直接返回成功
}
/**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info
* LOCAL_MODIFIED MODIFIED_DATE
* 使
*/
// 更新笔记的基本信息
if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) {
Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through
// 不直接返回,继续执行
}
mNoteDiffValues.clear();
mNoteDiffValues.clear(); // 清空笔记的差异数据
// 如果有本地修改的笔记数据尝试同步到ContentProvider
if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false;
return false; // 如果同步失败返回false
}
return true;
return true; // 成功同步
}
/**
* NoteData
*/
private class NoteData {
private long mTextDataId;
private ContentValues mTextDataValues;
private long mCallDataId;
private ContentValues mCallDataValues;
private long mTextDataId; // 存储文本数据的ID
private ContentValues mTextDataValues; // 存储文本数据内容
private long mCallDataId; // 存储通话数据的ID
private ContentValues mCallDataValues; // 存储通话数据内容
private static final String TAG = "NoteData";
@ -148,17 +167,20 @@ public class Note {
mCallDataId = 0;
}
// 判断文本数据和通话数据是否有本地修改
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
// 设置文本数据ID
void setTextDataId(long id) {
if(id <= 0) {
if (id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
}
mTextDataId = id;
}
// 设置通话数据ID
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
@ -166,22 +188,28 @@ public class Note {
mCallDataId = id;
}
// 设置通话数据的某个字段值
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地修改
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新时间戳
}
// 设置文本数据的某个字段值
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地修改
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新时间戳
}
/**
* ContentProvider
* @param context
* @param noteId ID
* @return URInull
*/
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety
*/
// 安全检查如果笔记ID无效抛出异常
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
@ -189,12 +217,13 @@ public class Note {
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) {
// 如果有文本数据需要更新或插入
if (mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
// 插入新文本数据
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, mTextDataValues);
try {
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
@ -203,20 +232,21 @@ public class Note {
return null;
}
} else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
// 更新现有的文本数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
operationList.add(builder.build());
}
mTextDataValues.clear();
}
if(mCallDataValues.size() > 0) {
// 如果有通话数据需要更新或插入
if (mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues);
// 插入新通话数据
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, mCallDataValues);
try {
setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
@ -225,14 +255,15 @@ public class Note {
return null;
}
} else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId));
// 更新现有的通话数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues);
operationList.add(builder.build());
}
mCallDataValues.clear();
}
// 如果有操作需要执行,则执行批量操作
if (operationList.size() > 0) {
try {
ContentProviderResult[] results = context.getContentResolver().applyBatch(
@ -247,7 +278,7 @@ public class Note {
return null;
}
}
return null;
return null; // 如果没有操作返回null
}
}
}

@ -32,36 +32,40 @@ import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
* WorkingNote
*/
public class WorkingNote {
// Note for the working note
// 笔记实例
private Note mNote;
// Note Id
// 笔记ID
private long mNoteId;
// Note content
// 笔记内容
private String mContent;
// Note mode
// 笔记模式(例如普通笔记或检查清单)
private int mMode;
// 提醒时间
private long mAlertDate;
// 笔记修改时间
private long mModifiedDate;
// 背景颜色ID
private int mBgColorId;
// 小部件ID
private int mWidgetId;
// 小部件类型
private int mWidgetType;
// 笔记所属文件夹ID
private long mFolderId;
// 应用上下文
private Context mContext;
// 日志标签
private static final String TAG = "WorkingNote";
// 笔记是否已删除标志
private boolean mIsDeleted;
// 笔记设置变化的监听器
private NoteSettingChangedListener mNoteSettingStatusListener;
// 数据库查询的列
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
@ -81,27 +85,19 @@ public class WorkingNote {
NoteColumns.MODIFIED_DATE
};
// 数据列的索引
private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3;
private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
private static final int NOTE_WIDGET_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct
// 构造器:创建一个新的空白工作笔记
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
@ -114,16 +110,17 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
}
// Existing note construct
// 构造器:加载一个已有的工作笔记
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
mFolderId = folderId;
mIsDeleted = false;
mNote = new Note();
loadNote();
loadNote(); // 加载笔记的基本信息
}
// 加载笔记的基本信息
private void loadNote() {
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
@ -143,13 +140,14 @@ public class WorkingNote {
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}
loadNoteData();
loadNoteData(); // 加载笔记的具体数据(文本或通话记录等)
}
// 加载笔记的具体数据
private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
String.valueOf(mNoteId)
}, null);
if (cursor != null) {
@ -174,8 +172,9 @@ public class WorkingNote {
}
}
// 创建一个新的空白工作笔记
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId);
@ -183,10 +182,12 @@ public class WorkingNote {
return note;
}
// 加载一个已存在的工作笔记
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
// 保存笔记
public synchronized boolean saveNote() {
if (isWorthSaving()) {
if (!existInDatabase()) {
@ -196,11 +197,9 @@ public class WorkingNote {
}
}
mNote.syncNote(mContext, mNoteId);
mNote.syncNote(mContext, mNoteId); // 同步笔记内容
/**
* Update widget content if there exist any widget of this note
*/
// 如果存在小部件与此笔记关联,更新小部件的内容
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) {
@ -212,10 +211,12 @@ public class WorkingNote {
}
}
// 检查笔记是否存在于数据库中
public boolean existInDatabase() {
return mNoteId > 0;
}
// 判断笔记是否值得保存
private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
@ -225,10 +226,12 @@ public class WorkingNote {
}
}
// 设置笔记设置变化的监听器
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}
// 设置提醒时间
public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) {
mAlertDate = date;
@ -239,14 +242,16 @@ public class WorkingNote {
}
}
// 标记笔记为删除或未删除
public void markDeleted(boolean mark) {
mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
mNoteSettingStatusListener.onWidgetChanged();
}
}
// 设置背景颜色ID
public void setBgColorId(int id) {
if (id != mBgColorId) {
mBgColorId = id;
@ -257,6 +262,7 @@ public class WorkingNote {
}
}
// 设置检查清单模式
public void setCheckListMode(int mode) {
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
@ -267,6 +273,7 @@ public class WorkingNote {
}
}
// 设置小部件类型
public void setWidgetType(int type) {
if (type != mWidgetType) {
mWidgetType = type;
@ -274,6 +281,7 @@ public class WorkingNote {
}
}
// 设置小部件ID
public void setWidgetId(int id) {
if (id != mWidgetId) {
mWidgetId = id;
@ -281,6 +289,7 @@ public class WorkingNote {
}
}
// 设置笔记文本
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
@ -288,81 +297,78 @@ public class WorkingNote {
}
}
// 将笔记转换为通话记录笔记
public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
}
// 判断是否有提醒
public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false);
return (mAlertDate > 0);
}
// 获取笔记内容
public String getContent() {
return mContent;
}
// 获取提醒时间
public long getAlertDate() {
return mAlertDate;
}
// 获取笔记的修改时间
public long getModifiedDate() {
return mModifiedDate;
}
// 获取笔记的背景颜色资源ID
public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId);
}
// 获取笔记的背景颜色ID
public int getBgColorId() {
return mBgColorId;
}
// 获取笔记标题的背景颜色资源ID
public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId);
}
// 获取检查清单模式
public int getCheckListMode() {
return mMode;
}
// 获取笔记ID
public long getNoteId() {
return mNoteId;
}
// 获取笔记所在文件夹ID
public long getFolderId() {
return mFolderId;
}
// 获取小部件ID
public int getWidgetId() {
return mWidgetId;
}
// 获取小部件类型
public int getWidgetType() {
return mWidgetType;
}
// 笔记设置变化监听器接口
public interface NoteSettingChangedListener {
/**
* Called when the background color of current note has just changed
*/
void onBackgroundColorChanged();
/**
* Called when user set clock
*/
void onClockAlertChanged(long date, boolean set);
/**
* Call when user create note from widget
*/
void onWidgetChanged();
/**
* Call when switch between check list mode and normal mode
* @param oldMode is previous mode before change
* @param newMode is new mode
*/
void onCheckListModeChanged(int oldMode, int newMode);
void onBackgroundColorChanged(); // 当背景颜色变化时调用
void onClockAlertChanged(long date, boolean set); // 当提醒时间变化时调用
void onWidgetChanged(); // 当小部件变化时调用
void onCheckListModeChanged(int oldMode, int newMode); // 当切换模式时调用
}
}

@ -35,12 +35,11 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class BackupUtils {
private static final String TAG = "BackupUtils";
// Singleton stuff
private static BackupUtils sInstance;
private static final String TAG = "BackupUtils"; // 定义日志标签
private static BackupUtils sInstance; // 单例模式实例
// 获取单例实例的方法,确保整个应用中只有一个 BackupUtils 对象
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
@ -48,82 +47,76 @@ public class BackupUtils {
return sInstance;
}
/**
* Following states are signs to represents backup or restore
* status
*/
// Currently, the sdcard is not mounted
public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs
public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails
public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success
public static final int STATE_SUCCESS = 4;
private TextExport mTextExport;
// 定义备份和恢复状态的常量
public static final int STATE_SD_CARD_UNMOUONTED = 0; // SD 卡未挂载
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; // 备份文件不存在
public static final int STATE_DATA_DESTROIED = 2; // 数据损坏
public static final int STATE_SYSTEM_ERROR = 3; // 系统错误
public static final int STATE_SUCCESS = 4; // 备份或恢复成功
private TextExport mTextExport; // 文本导出工具
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
mTextExport = new TextExport(context); // 初始化 TextExport 对象
}
// 检查外部存储是否可用
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
// 导出数据到文本文件
public int exportToText() {
return mTextExport.exportToText();
}
// 获取导出的文本文件名
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
// 获取导出的文本文件所在目录
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
// 内部类:用于处理文本导出功能
private static class TextExport {
// 定义查询数据所需的列
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,
NoteColumns.TYPE
NoteColumns.ID, // 笔记ID
NoteColumns.MODIFIED_DATE, // 修改时间
NoteColumns.SNIPPET, // 笔记的摘要
NoteColumns.TYPE // 笔记类型
};
private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2;
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
DataColumns.CONTENT, // 数据内容
DataColumns.MIME_TYPE, // MIME 类型
DataColumns.DATA1, // 备用数据1
DataColumns.DATA2, // 备用数据2
DataColumns.DATA3, // 备用数据3
DataColumns.DATA4, // 备用数据4
};
private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
private final String [] TEXT_FORMAT;
private static final int FORMAT_FOLDER_NAME = 0;
private static final int FORMAT_NOTE_DATE = 1;
private static final int FORMAT_NOTE_CONTENT = 2;
// 定义文本格式化的常量
private final String[] TEXT_FORMAT;
private static final int FORMAT_FOLDER_NAME = 0; // 文件夹名称格式
private static final int FORMAT_NOTE_DATE = 1; // 笔记修改时间格式
private static final int FORMAT_NOTE_CONTENT = 2; // 笔记内容格式
private Context mContext;
private String mFileName;
private String mFileDirectory;
private Context mContext; // 上下文
private String mFileName; // 导出的文件名
private String mFileDirectory; // 导出文件所在目录
public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
@ -132,104 +125,91 @@ public class BackupUtils {
mFileDirectory = "";
}
// 获取格式化字符串
private String getFormat(int id) {
return TEXT_FORMAT[id];
}
/**
* Export the folder identified by folder id to text
*/
// 导出文件夹下的所有笔记
private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder
// 查询该文件夹下的所有笔记
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
}, null);
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[]{folderId}, null);
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
do {
// Print note's last modified date
// 打印笔记的最后修改时间
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
// 获取笔记的 ID
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
exportNoteToText(noteId, ps); // 导出笔记的内容
} while (notesCursor.moveToNext());
}
notesCursor.close();
}
}
/**
* Export note identified by id to a print stream
*/
// 导出指定 ID 的笔记内容
private void exportNoteToText(String noteId, PrintStream ps) {
// 查询该笔记的所有数据
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
}, null);
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[]{noteId}, null);
if (dataCursor != null) {
if (dataCursor.moveToFirst()) {
do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number
// 如果是电话记录类型,导出电话信息
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(phoneNumber)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber));
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber));
}
// Print call date
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm),
callDate)));
// Print call attachment location
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), callDate)));
if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location));
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {
// 如果是普通笔记,导出笔记内容
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
content));
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), content));
}
}
} while (dataCursor.moveToNext());
}
dataCursor.close();
}
// print a line separator between note
// 在笔记之间添加分隔行
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
});
ps.write(new byte[]{Character.LINE_SEPARATOR, Character.LETTER_NUMBER});
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}
/**
* Note will be exported as text which is user readable
*/
// 导出为用户可读的文本格式
public int exportToText() {
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
return STATE_SD_CARD_UNMOUONTED; // SD 卡未挂载
}
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
return STATE_SYSTEM_ERROR; // 获取输出流失败
}
// First export folder and its notes
// 导出文件夹和文件夹下的所有笔记
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -240,9 +220,9 @@ public class BackupUtils {
if (folderCursor != null) {
if (folderCursor.moveToFirst()) {
do {
// Print folder's name
// 打印文件夹名称
String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
if (folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
} else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
@ -251,17 +231,17 @@ public class BackupUtils {
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
String folderId = folderCursor.getString(NOTE_COLUMN_ID);
exportFolderToText(folderId, ps);
exportFolderToText(folderId, ps); // 导出该文件夹下的笔记
} while (folderCursor.moveToNext());
}
folderCursor.close();
}
// Export notes in root's folder
// 导出根文件夹下的所有笔记
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
NoteColumns.TYPE + "=" + Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null);
if (noteCursor != null) {
@ -270,34 +250,30 @@ public class BackupUtils {
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
exportNoteToText(noteId, ps); // 导出该笔记内容
} while (noteCursor.moveToNext());
}
noteCursor.close();
}
ps.close();
return STATE_SUCCESS;
ps.close(); // 关闭输出流
return STATE_SUCCESS; // 导出成功
}
/**
* Get a print stream pointed to the file {@generateExportedTextFile}
*/
// 获取指向导出文本文件的输出流
private PrintStream getExportToTextPrintStream() {
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format);
File file = generateFileMountedOnSDcard(mContext, R.string.file_path, R.string.file_name_txt_format);
if (file == null) {
Log.e(TAG, "create file to exported failed");
return null;
return null; // 创建文件失败
}
mFileName = file.getName();
mFileDirectory = mContext.getString(R.string.file_path);
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(file);
ps = new PrintStream(fos);
ps = new PrintStream(fos); // 获取输出流
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
@ -309,9 +285,7 @@ public class BackupUtils {
}
}
/**
* Generate the text file to store imported data
*/
// 生成保存导入数据的文件
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory());
@ -320,15 +294,15 @@ public class BackupUtils {
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis())));
System.currentTimeMillis()))); // 文件名格式化
File file = new File(sb.toString());
try {
if (!filedir.exists()) {
filedir.mkdir();
filedir.mkdir(); // 创建目录
}
if (!file.exists()) {
file.createNewFile();
file.createNewFile(); // 创建文件
}
return file;
} catch (SecurityException e) {
@ -337,7 +311,7 @@ public class BackupUtils {
e.printStackTrace();
}
return null;
return null; // 创建失败
}
}

@ -36,123 +36,143 @@ import java.util.HashSet;
public class DataUtils {
public static final String TAG = "DataUtils";
public static final String TAG = "DataUtils"; // 日志标签
// 批量删除笔记,删除给定 HashSet 中的所有笔记
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
// 检查输入的 IDs 是否为空
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
return true; // 如果没有指定 ID认为操作成功没有删除
}
if (ids.size() == 0) {
Log.d(TAG, "no id is in the hashset");
return true;
return true; // 如果没有 IDs认为操作成功没有删除
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); // 用于存储删除操作
// 遍历给定的 ID构建删除操作
for (long id : ids) {
// 忽略删除系统根文件夹
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;
continue; // 跳过系统根文件夹 ID
}
// 为每个 ID 构建删除操作
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
operationList.add(builder.build());
operationList.add(builder.build()); // 将操作加入到操作列表
}
try {
// 执行批量操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
return false; // 删除失败
}
return true;
return true; // 删除成功
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 捕获并记录异常
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 捕获并记录异常
}
return false;
return false; // 发生异常,删除失败
}
// 将笔记从源文件夹移动到目标文件夹
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, desFolderId);
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, desFolderId); // 设置新的父文件夹 ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 设置原始父文件夹 ID
values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为已修改
// 执行更新操作
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
}
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
// 批量将笔记移动到指定文件夹
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, long folderId) {
// 检查输入的 IDs 是否为空
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
return true; // 如果没有指定 ID认为操作成功没有移动
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); // 用于存储更新操作
// 遍历给定的 ID构建更新操作
for (long id : ids) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
operationList.add(builder.build());
builder.withValue(NoteColumns.PARENT_ID, folderId); // 设置目标文件夹 ID
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); // 标记为已修改
operationList.add(builder.build()); // 将操作加入到操作列表
}
try {
// 执行批量操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
Log.d(TAG, "move notes failed, ids:" + ids.toString());
return false; // 移动失败
}
return true;
return true; // 移动成功
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 捕获并记录异常
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 捕获并记录异常
}
return false;
return false; // 发生异常,移动失败
}
/**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*
*/
public static int getUserFolderCount(ContentResolver resolver) {
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
// 查询文件夹数量,排除系统文件夹和回收站文件夹
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) },
null);
int count = 0;
if(cursor != null) {
if(cursor.moveToFirst()) {
try {
count = cursor.getInt(0);
count = cursor.getInt(0); // 获取文件夹数量
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "get folder count failed:" + e.toString());
Log.e(TAG, "get folder count failed:" + e.toString()); // 捕获异常
} finally {
cursor.close();
cursor.close(); // 关闭游标
}
}
}
return count;
return count; // 返回文件夹数量
}
// 判断笔记是否在数据库中可见(不在回收站中)
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)},
new String[] { String.valueOf(type) },
null);
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
exist = true; // 如果查询结果非空,认为笔记存在且可见
}
cursor.close();
}
return exist;
}
// 判断笔记是否存在于数据库中
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
@ -160,13 +180,14 @@ public class DataUtils {
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
exist = true; // 如果查询结果非空,认为笔记存在
}
cursor.close();
}
return exist;
}
// 判断数据是否存在于数据库中
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
@ -174,29 +195,32 @@ public class DataUtils {
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
exist = true; // 如果查询结果非空,认为数据存在
}
cursor.close();
}
return exist;
}
// 检查指定名称的文件夹是否已经存在
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);
boolean exist = false;
if(cursor != null) {
if(cursor.getCount() > 0) {
exist = true;
exist = true; // 如果查询结果非空,认为文件夹存在
}
cursor.close();
}
return exist;
}
// 获取某文件夹下所有小部件的属性
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
@ -213,83 +237,87 @@ public class DataUtils {
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
set.add(widget);
set.add(widget); // 添加小部件属性到集合
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // 捕获异常
}
} while (c.moveToNext());
}
c.close();
}
return set;
return set; // 返回所有小部件属性集合
}
// 根据笔记 ID 获取通话记录中的电话号码
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER },
new String[] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
new String[] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
null);
if (cursor != null && cursor.moveToFirst()) {
try {
return cursor.getString(0);
return cursor.getString(0); // 获取电话号码
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString());
Log.e(TAG, "Get call number fails " + e.toString()); // 捕获异常
} finally {
cursor.close();
cursor.close(); // 关闭游标
}
}
return "";
}
// 根据电话号码和通话日期获取笔记 ID
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
new String[] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
+ CallNote.PHONE_NUMBER + ",?)",
new String[] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
try {
return cursor.getLong(0);
return cursor.getLong(0); // 返回找到的笔记 ID
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString());
Log.e(TAG, "Get call note id fails " + e.toString()); // 捕获异常
}
}
cursor.close();
}
return 0;
return 0; // 如果没有找到,返回 0
}
// 根据笔记 ID 获取笔记的摘要
public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
new String[] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)},
new String[] { String.valueOf(noteId) },
null);
if (cursor != null) {
String snippet = "";
if (cursor.moveToFirst()) {
snippet = cursor.getString(0);
snippet = cursor.getString(0); // 获取摘要内容
}
cursor.close();
return snippet;
}
throw new IllegalArgumentException("Note is not found with id: " + noteId);
throw new IllegalArgumentException("Note is not found with id: " + noteId); // 如果没有找到,抛出异常
}
// 格式化摘要,去掉换行符
public static String getFormattedSnippet(String snippet) {
if (snippet != null) {
snippet = snippet.trim();
snippet = snippet.trim(); // 去掉空格
int index = snippet.indexOf('\n');
if (index != -1) {
snippet = snippet.substring(0, index);
snippet = snippet.substring(0, index); // 去掉换行符后的内容
}
}
return snippet;
return snippet; // 返回格式化后的摘要
}
}

@ -18,96 +18,132 @@ package net.micode.notes.tool;
public class GTaskStringUtils {
// GTASK 相关的 JSON 字段名常量
// action_id - 操作的唯一标识符
public final static String GTASK_JSON_ACTION_ID = "action_id";
// action_list - 用于存储多个操作的列表
public final static String GTASK_JSON_ACTION_LIST = "action_list";
// action_type - 操作的类型
public final static String GTASK_JSON_ACTION_TYPE = "action_type";
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
// 操作类型常量
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; // 创建任务
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; // 获取所有任务
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; // 移动任务
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; // 更新任务
// creator_id - 创建者的 ID
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
// child_entity - 子任务实体
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
// client_version - 客户端版本
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
// completed - 任务是否完成
public final static String GTASK_JSON_COMPLETED = "completed";
// current_list_id - 当前任务所属的列表 ID
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
// default_list_id - 默认任务列表 ID
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
// deleted - 任务是否被删除
public final static String GTASK_JSON_DELETED = "deleted";
// dest_list - 目标任务列表
public final static String GTASK_JSON_DEST_LIST = "dest_list";
// dest_parent - 目标任务父级 ID
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
// dest_parent_type - 目标任务父级类型
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
// entity_delta - 实体增量数据
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
// entity_type - 实体类型(如任务或文件夹)
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
// get_deleted - 获取已删除的任务
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
// id - 任务或实体的 ID
public final static String GTASK_JSON_ID = "id";
// index - 任务在列表中的索引位置
public final static String GTASK_JSON_INDEX = "index";
// last_modified - 上次修改时间
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
// latest_sync_point - 最新同步点
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
// list_id - 任务所属列表的 ID
public final static String GTASK_JSON_LIST_ID = "list_id";
// lists - 任务列表集合
public final static String GTASK_JSON_LISTS = "lists";
// name - 任务的名称
public final static String GTASK_JSON_NAME = "name";
// new_id - 新生成的 ID
public final static String GTASK_JSON_NEW_ID = "new_id";
// notes - 任务的备注
public final static String GTASK_JSON_NOTES = "notes";
// parent_id - 任务父级的 ID
public final static String GTASK_JSON_PARENT_ID = "parent_id";
// prior_sibling_id - 任务的前一个兄弟任务 ID
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
// results - 查询结果
public final static String GTASK_JSON_RESULTS = "results";
// source_list - 源任务列表
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
// tasks - 任务集合
public final static String GTASK_JSON_TASKS = "tasks";
// type - 任务类型
public final static String GTASK_JSON_TYPE = "type";
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
public final static String GTASK_JSON_TYPE_TASK = "TASK";
// type 常量
public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; // 任务组类型
public final static String GTASK_JSON_TYPE_TASK = "TASK"; // 任务类型
// user - 用户信息
public final static String GTASK_JSON_USER = "user";
// MIUI 文件夹前缀,用于 MIUI 系统
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
// 默认文件夹名称
public final static String FOLDER_DEFAULT = "Default";
// 通话记录文件夹名称
public final static String FOLDER_CALL_NOTE = "Call_Note";
// 元数据文件夹名称
public final static String FOLDER_META = "METADATA";
public final static String META_HEAD_GTASK_ID = "meta_gid";
public final static String META_HEAD_NOTE = "meta_note";
public final static String META_HEAD_DATA = "meta_data";
// 元数据字段常量
public final static String META_HEAD_GTASK_ID = "meta_gid"; // GTASK ID
public final static String META_HEAD_NOTE = "meta_note"; // 笔记
public final static String META_HEAD_DATA = "meta_data"; // 数据
// 特殊的元数据笔记名称,不允许更新和删除
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
}

@ -24,158 +24,187 @@ import net.micode.notes.ui.NotesPreferenceActivity;
public class ResourceParser {
public static final int YELLOW = 0;
public static final int BLUE = 1;
public static final int WHITE = 2;
public static final int GREEN = 3;
public static final int RED = 4;
// 定义笔记背景颜色的常量
public static final int YELLOW = 0; // 黄色
public static final int BLUE = 1; // 蓝色
public static final int WHITE = 2; // 白色
public static final int GREEN = 3; // 绿色
public static final int RED = 4; // 红色
// 默认背景颜色为黄色
public static final int BG_DEFAULT_COLOR = YELLOW;
public static final int TEXT_SMALL = 0;
public static final int TEXT_MEDIUM = 1;
public static final int TEXT_LARGE = 2;
public static final int TEXT_SUPER = 3;
// 定义字体大小的常量
public static final int TEXT_SMALL = 0; // 小号字体
public static final int TEXT_MEDIUM = 1; // 中号字体
public static final int TEXT_LARGE = 2; // 大号字体
public static final int TEXT_SUPER = 3; // 超大号字体
// 默认字体大小为中号
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
// 处理笔记背景资源的内部类
public static class NoteBgResources {
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
// 编辑模式下的背景资源
private final static int[] BG_EDIT_RESOURCES = new int[] {
R.drawable.edit_yellow, // 黄色背景
R.drawable.edit_blue, // 蓝色背景
R.drawable.edit_white, // 白色背景
R.drawable.edit_green, // 绿色背景
R.drawable.edit_red // 红色背景
};
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
R.drawable.edit_title_white,
R.drawable.edit_title_green,
R.drawable.edit_title_red
// 编辑模式下标题的背景资源
private final static int[] BG_EDIT_TITLE_RESOURCES = new int[] {
R.drawable.edit_title_yellow, // 黄色标题
R.drawable.edit_title_blue, // 蓝色标题
R.drawable.edit_title_white, // 白色标题
R.drawable.edit_title_green, // 绿色标题
R.drawable.edit_title_red // 红色标题
};
// 根据颜色ID获取笔记背景资源
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
// 根据颜色ID获取笔记标题背景资源
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
// 获取默认背景ID如果用户在设置中启用了背景颜色返回随机颜色ID
public static int getDefaultBgId(Context context) {
// 从 SharedPreferences 中获取用户设置的背景颜色
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 随机返回一个背景颜色ID
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
// 返回默认背景颜色ID
return BG_DEFAULT_COLOR;
}
}
// 处理笔记项背景资源的内部类
public static class NoteItemBgResources {
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
R.drawable.list_white_up,
R.drawable.list_green_up,
R.drawable.list_red_up
// 第一项(列表顶部)的背景资源
private final static int[] BG_FIRST_RESOURCES = new int[] {
R.drawable.list_yellow_up, // 黄色背景
R.drawable.list_blue_up, // 蓝色背景
R.drawable.list_white_up, // 白色背景
R.drawable.list_green_up, // 绿色背景
R.drawable.list_red_up // 红色背景
};
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
R.drawable.list_white_middle,
R.drawable.list_green_middle,
R.drawable.list_red_middle
// 正常项(中间项)的背景资源
private final static int[] BG_NORMAL_RESOURCES = new int[] {
R.drawable.list_yellow_middle, // 黄色背景
R.drawable.list_blue_middle, // 蓝色背景
R.drawable.list_white_middle, // 白色背景
R.drawable.list_green_middle, // 绿色背景
R.drawable.list_red_middle // 红色背景
};
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
R.drawable.list_white_down,
R.drawable.list_green_down,
R.drawable.list_red_down,
// 最后一项(列表底部)的背景资源
private final static int[] BG_LAST_RESOURCES = new int[] {
R.drawable.list_yellow_down, // 黄色背景
R.drawable.list_blue_down, // 蓝色背景
R.drawable.list_white_down, // 白色背景
R.drawable.list_green_down, // 绿色背景
R.drawable.list_red_down // 红色背景
};
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
R.drawable.list_white_single,
R.drawable.list_green_single,
R.drawable.list_red_single
// 单独项(只有一个项)的背景资源
private final static int[] BG_SINGLE_RESOURCES = new int[] {
R.drawable.list_yellow_single, // 黄色背景
R.drawable.list_blue_single, // 蓝色背景
R.drawable.list_white_single, // 白色背景
R.drawable.list_green_single, // 绿色背景
R.drawable.list_red_single // 红色背景
};
// 根据颜色ID获取笔记项的第一项背景资源
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
// 根据颜色ID获取笔记项的最后一项背景资源
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
// 根据颜色ID获取单独项的背景资源
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
// 根据颜色ID获取笔记项的正常背景资源
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
// 获取文件夹背景资源
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
// 处理小部件背景资源的内部类
public static class WidgetBgResources {
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
// 2x 小部件的背景资源
private final static int[] BG_2X_RESOURCES = new int[] {
R.drawable.widget_2x_yellow, // 黄色背景
R.drawable.widget_2x_blue, // 蓝色背景
R.drawable.widget_2x_white, // 白色背景
R.drawable.widget_2x_green, // 绿色背景
R.drawable.widget_2x_red // 红色背景
};
// 根据颜色ID获取2x小部件的背景资源
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
// 4x 小部件的背景资源
private final static int[] BG_4X_RESOURCES = new int[] {
R.drawable.widget_4x_yellow, // 黄色背景
R.drawable.widget_4x_blue, // 蓝色背景
R.drawable.widget_4x_white, // 白色背景
R.drawable.widget_4x_green, // 绿色背景
R.drawable.widget_4x_red // 红色背景
};
// 根据颜色ID获取4x小部件的背景资源
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
// 处理文本外观资源的内部类
public static class TextAppearanceResources {
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
// 文本外观样式资源
private final static int[] TEXTAPPEARANCE_RESOURCES = new int[] {
R.style.TextAppearanceNormal, // 普通样式
R.style.TextAppearanceMedium, // 中号样式
R.style.TextAppearanceLarge, // 大号样式
R.style.TextAppearanceSuper // 超大号样式
};
// 根据字体大小ID获取相应的文本样式资源
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/
// 修复BUG防止将大于资源数组长度的ID存储到 SharedPreferences 中
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE;
return BG_DEFAULT_FONT_SIZE; // 返回默认字体大小
}
return TEXTAPPEARANCE_RESOURCES[id];
}
// 获取字体样式资源的数量
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}

@ -39,21 +39,26 @@ 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);
// 获取当前窗口对象
final Window win = getWindow();
// 设置窗口标志,让窗口在锁屏时也能显示
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// 如果屏幕是关闭状态,保持屏幕常亮,并打开屏幕
if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
@ -61,11 +66,15 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
}
// 获取启动此活动的 Intent
Intent intent = getIntent();
try {
// 从 URI 中提取笔记 ID
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)
: mSnippet;
@ -74,85 +83,93 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
return;
}
// 初始化媒体播放器
mPlayer = new MediaPlayer();
// 检查该笔记是否有效(存在且可见)
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
// 显示对话框并播放警报声音
showActionDialog();
playAlarmSound();
} else {
finish();
finish(); // 如果笔记无效,结束活动
}
}
// 检查屏幕是否处于开启状态
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
}
// 播放警报声音
private void playAlarmSound() {
// 获取默认的警报铃声 URI
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);
}
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.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.setPositiveButton(R.string.notealert_ok, this);
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);
}
// 按钮点击事件处理
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
// 当点击“进入”按钮时,跳转到笔记编辑页面
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent);
intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递笔记 ID
startActivity(intent); // 启动编辑活动
break;
default:
break;
}
}
// 对话框关闭时的处理
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
finish();
stopAlarmSound(); // 停止播放警报声音
finish(); // 结束当前活动
}
// 停止警报声音
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
mPlayer.stop(); // 停止播放
mPlayer.release(); // 释放播放器资源
mPlayer = null; // 设置播放器为 null
}
}
}

@ -30,35 +30,49 @@ import net.micode.notes.data.Notes.NoteColumns;
public class AlarmInitReceiver extends BroadcastReceiver {
// 定义查询笔记的列,只查询 ID 和 ALERTED_DATE
private static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE
NoteColumns.ID, // 笔记 ID
NoteColumns.ALERTED_DATE // 警报时间(即提醒时间)
};
private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1;
// 对应查询结果的列索引
private static final int COLUMN_ID = 0; // 笔记 ID 列索引
private static final int COLUMN_ALERTED_DATE = 1; // 警报时间列索引
// 当广播接收时触发此方法
@Override
public void onReceive(Context context, Intent intent) {
// 获取当前时间
long currentDate = System.currentTimeMillis();
// 查询数据库中需要触发警报的笔记,警报时间大于当前时间的笔记
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
new String[] { String.valueOf(currentDate) },
null);
PROJECTION, // 查询的列
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, // 查询条件,警报时间 > 当前时间,且是笔记类型
new String[] { String.valueOf(currentDate) }, // 条件中的当前时间
null); // 不需要排序
// 如果查询结果不为空
if (c != null) {
// 如果查询结果有数据
if (c.moveToFirst()) {
do {
// 获取警报时间
long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建一个新的 Intent用于广播 AlarmReceiver
Intent sender = new Intent(context, AlarmReceiver.class);
// 设置 Intent 的数据为当前笔记的 URI
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建一个 PendingIntent用于设置警报
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// 获取 AlarmManager 实例
AlarmManager alermManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// 设置警报:在指定时间触发广播
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext());
} while (c.moveToNext()); // 如果还有下一条记录,继续处理
}
// 关闭数据库游标
c.close();
}
}

@ -23,8 +23,11 @@ import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 设置要启动的活动为 AlarmAlertActivity
intent.setClass(context, AlarmAlertActivity.class);
// 设置启动活动时的标志,使得该活动会启动新的任务栈
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动活动
context.startActivity(intent);
}
}

@ -21,7 +21,6 @@ import java.util.Calendar;
import net.micode.notes.R;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.View;
@ -30,11 +29,11 @@ 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 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;
@ -46,61 +45,60 @@ public class DateTimePicker extends FrameLayout {
private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MAX_VAL = 1;
// NumberPicker 控件用于选择日期、小时、分钟、AM/PM
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 OnDateTimeChangedListener mOnDateTimeChangedListener;
private Calendar mDate; // 当前日期和时间
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; // 显示的日期值
private boolean mIsAm; // 当前是否为 AM
private boolean mIs24HourView; // 是否为 24 小时制
private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 控件是否启用
private boolean mInitialising; // 是否在初始化中
private OnDateTimeChangedListener mOnDateTimeChangedListener; // 日期时间变化的回调
// 日期选择器的监听器
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl();
onDateTimeChanged();
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); // 更新日期
updateDateControl(); // 更新日期控件显示
onDateTimeChanged(); // 通知日期时间变化
}
};
// 小时选择器的监听器
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) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.add(Calendar.DAY_OF_YEAR, 1); // 增加一天
isDateChanged = true;
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
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();
mIsAm = !mIsAm; // 切换 AM 和 PM
updateAmPmControl(); // 更新 AM/PM 控件
}
} else {
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.add(Calendar.DAY_OF_YEAR, 1); // 增加一天
isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
cal.add(Calendar.DAY_OF_YEAR, -1); // 减少一天
isDateChanged = true;
}
}
@ -115,12 +113,14 @@ public class DateTimePicker extends FrameLayout {
}
};
// 分钟选择器的监听器
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 offset = 0;
// 如果分钟数超出范围,则更新小时数
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
} else if (oldVal == minValue && newVal == maxValue) {
@ -128,41 +128,44 @@ public class DateTimePicker extends FrameLayout {
}
if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();
mHourSpinner.setValue(getCurrentHour()); // 更新小时选择器的值
updateDateControl(); // 更新日期控件
int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
mIsAm = false; // 更新 AM/PM 状态
updateAmPmControl();
} else {
mIsAm = true;
updateAmPmControl();
}
}
mDate.set(Calendar.MINUTE, newVal);
mDate.set(Calendar.MINUTE, newVal); // 更新分钟
onDateTimeChanged();
}
};
// AM/PM 选择器的监听器
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
mIsAm = !mIsAm; // 切换 AM 和 PM
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); // AM 时,减少 12 小时
} else {
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); // PM 时,增加 12 小时
}
updateAmPmControl();
updateAmPmControl(); // 更新 AM/PM 控件
onDateTimeChanged();
}
};
// 日期时间变化的回调接口
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
int dayOfMonth, int hourOfDay, int minute);
}
// 构造函数,初始化控件
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
@ -178,19 +181,21 @@ public class DateTimePicker extends FrameLayout {
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
inflate(context, R.layout.datetime_picker, this);
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner = (NumberPicker) findViewById(R.id.date); // 日期选择器
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner = (NumberPicker) findViewById(R.id.hour); // 小时选择器
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); // 分钟选择器
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// AM/PM选择器
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
@ -198,22 +203,22 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state
// 更新控件为初始状态
updateDateControl();
updateHourControl();
updateAmPmControl();
set24HourView(is24HourView);
set24HourView(is24HourView); // 设置是否为 24 小时制
// set to current time
// 设置当前时间
setCurrentDate(date);
setEnabled(isEnabled());
setEnabled(isEnabled()); // 设置控件是否启用
// set the content descriptions
mInitialising = false;
}
// 设置控件是否启用
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
@ -227,25 +232,12 @@ 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);
@ -253,17 +245,9 @@ public class DateTimePicker extends FrameLayout {
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) {
int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
@ -271,20 +255,12 @@ public class DateTimePicker extends FrameLayout {
setCurrentMinute(minute);
}
/**
* Get current year
*
* @return The current year
*/
// 获取当前年份
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}
/**
* Set current year
*
* @param year The current year
*/
// 设置当前年份
public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) {
return;
@ -294,20 +270,12 @@ public class DateTimePicker extends FrameLayout {
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;
@ -317,20 +285,12 @@ public class DateTimePicker extends FrameLayout {
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;
@ -340,10 +300,7 @@ public class DateTimePicker extends FrameLayout {
onDateTimeChanged();
}
/**
* Get current hour in 24 hour mode, in the range (0~23)
* @return The current hour in 24 hour mode
*/
// 获取当前小时24 小时制)
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}
@ -361,11 +318,7 @@ public class DateTimePicker extends FrameLayout {
}
}
/**
* Set current hour in 24 hour mode, in the range (0~23)
*
* @param hourOfDay
*/
// 设置当前小时24 小时制)
public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return;
@ -389,18 +342,12 @@ public class DateTimePicker extends FrameLayout {
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;
@ -410,18 +357,12 @@ public class DateTimePicker extends FrameLayout {
onDateTimeChanged();
}
/**
* @return true if this is in 24 hour view else false.
*/
// 判断是否为 24 小时制
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.
*/
// 设置是否为 24 小时制
public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) {
return;
@ -434,6 +375,7 @@ public class DateTimePicker extends FrameLayout {
updateAmPmControl();
}
// 更新日期控件
private void updateDateControl() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis());
@ -448,6 +390,7 @@ public class DateTimePicker extends FrameLayout {
mDateSpinner.invalidate();
}
// 更新 AM/PM 控件
private void updateAmPmControl() {
if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE);
@ -458,6 +401,7 @@ public class DateTimePicker extends FrameLayout {
}
}
// 更新小时控件
private void updateHourControl() {
if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
@ -468,14 +412,12 @@ public class DateTimePicker extends FrameLayout {
}
}
/**
* 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(),
@ -483,3 +425,4 @@ public class DateTimePicker extends FrameLayout {
}
}
}

@ -29,62 +29,129 @@ import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
/**
* DateTimePickerDialog
*
*/
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// Calendar 实例,保存当前选择的日期和时间
private Calendar mDate = Calendar.getInstance();
// 是否显示为 24 小时制的标志
private boolean mIs24HourView;
// 日期时间设置的回调接口
private OnDateTimeSetListener mOnDateTimeSetListener;
// 自定义的 DateTimePicker 控件
private DateTimePicker mDateTimePicker;
/**
*
*/
public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date);
}
/**
* DateTimePickerDialog
*
* @param context
* @param date
*/
public DateTimePickerDialog(Context context, long date) {
super(context);
// 创建 DateTimePicker 控件实例并将其添加到对话框中
mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker);
// 设置 DateTimePicker 控件的日期时间变化监听器
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
@Override
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
int dayOfMonth, int hourOfDay, int minute) {
// 更新 mDate 对象中的日期和时间
mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute);
// 更新对话框的标题显示为当前选择的日期时间
updateTitle(mDate.getTimeInMillis());
}
});
// 将初始时间设置为传入的时间,并确保秒数为 0
mDate.setTimeInMillis(date);
mDate.set(Calendar.SECOND, 0);
// 设置 DateTimePicker 控件的初始日期时间
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置“确定”按钮,点击时调用 onClick 方法
setButton(context.getString(R.string.datetime_dialog_ok), this);
// 设置“取消”按钮,点击时不做任何操作
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 根据系统时间格式设置 24 小时制
set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 更新对话框标题为当前日期时间
updateTitle(mDate.getTimeInMillis());
}
/**
* 24
*
* @param is24HourView 24
*/
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
}
/**
*
*
* @param callBack
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
/**
*
*
* @param date
*/
private void updateTitle(long date) {
int flag =
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
DateUtils.FORMAT_SHOW_YEAR | // 显示年份
DateUtils.FORMAT_SHOW_DATE | // 显示日期
DateUtils.FORMAT_SHOW_TIME; // 显示时间
// 如果是 24 小时制,更新格式标志
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR;
// 设置对话框标题
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
/**
*
*
*
* @param arg0 DialogInterface
* @param arg1
*/
@Override
public void onClick(DialogInterface arg0, int arg1) {
// 如果设置了回调接口,则调用接口的 OnDateTimeSet 方法,并传递选择的日期时间
if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}
}
}

@ -27,35 +27,81 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
/**
* DropdownMenu
*
*/
public class DropdownMenu {
// 按钮实例,用于触发下拉菜单的显示
private Button mButton;
// PopupMenu 实例,用于显示下拉菜单
private PopupMenu mPopupMenu;
// 菜单实例,用于存储下拉菜单的所有菜单项
private Menu mMenu;
/**
* DropdownMenu
*
* @param context
* @param button
* @param menuId ID
*/
public DropdownMenu(Context context, Button button, int menuId) {
mButton = button;
// 设置按钮的背景为下拉菜单图标
mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 创建一个 PopupMenu绑定到按钮
mPopupMenu = new PopupMenu(context, mButton);
// 获取菜单对象并加载指定的菜单资源
mMenu = mPopupMenu.getMenu();
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 设置按钮点击事件,点击时显示下拉菜单
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 显示下拉菜单
mPopupMenu.show();
}
});
}
/**
*
*
*
* @param listener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
// 设置菜单项点击监听器
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
/**
* ID MenuItem
*
* @param id ID
* @return MenuItem
*/
public MenuItem findItem(int id) {
// 查找并返回对应 ID 的菜单项
return mMenu.findItem(id);
}
/**
*
*
* @param title
*/
public void setTitle(CharSequence title) {
// 设置按钮的文本
mButton.setText(title);
}
}

@ -28,53 +28,106 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
/**
* FoldersListAdapter CursorAdapter
*
*/
public class FoldersListAdapter extends CursorAdapter {
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
// 数据库中获取文件夹信息的字段ID 和名称)
public static final String[] PROJECTION = {
NoteColumns.ID, // 文件夹ID
NoteColumns.SNIPPET // 文件夹名称
};
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1;
// 数据库列的索引
public static final int ID_COLUMN = 0; // 文件夹ID的列索引
public static final int NAME_COLUMN = 1; // 文件夹名称的列索引
/**
* FoldersListAdapter
*
* @param context
* @param c Cursor
*/
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
super(context, c); // 调用父类的构造方法
// TODO Auto-generated constructor stub
}
/**
*
*
* @param context
* @param cursor
* @param parent
* @return FolderListItem
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context);
return new FolderListItem(context); // 返回一个新的 FolderListItem
}
/**
*
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) {
// 如果视图是 FolderListItem 类型,则绑定数据
// 如果是根文件夹,显示特殊文本 "移动到父文件夹",否则显示文件夹名称
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
((FolderListItem) view).bind(folderName);
((FolderListItem) view).bind(folderName); // 将文件夹名称绑定到视图
}
}
/**
*
*
* @param context
* @param position
* @return
*/
public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position);
Cursor cursor = (Cursor) getItem(position); // 获取当前项的光标数据
// 如果是根文件夹,返回特殊名称,否则返回文件夹的名称
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}
/**
* FolderListItem
* 线
*/
private class FolderListItem extends LinearLayout {
private TextView mName;
/**
* TextView
*
* @param context
*/
public FolderListItem(Context context) {
super(context);
// 为布局绑定 XML 文件 (folder_list_item.xml)
inflate(context, R.layout.folder_list_item, this);
mName = (TextView) findViewById(R.id.tv_folder_name);
mName = (TextView) findViewById(R.id.tv_folder_name); // 获取显示文件夹名称的 TextView
}
/**
* TextView
*
* @param name
*/
public void bind(String name) {
mName.setText(name);
mName.setText(name); // 设置文件夹名称
}
}
}

@ -71,19 +71,22 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* NoteEditActivity Activity
*
*/
public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener {
private class HeadViewHolder {
public TextView tvModified;
public ImageView ivAlertIcon;
public TextView tvAlertDate;
public ImageView ibSetBgColor;
// HeadViewHolder 类用于保存笔记编辑界面头部的一些 UI 组件
private class HeadViewHolder {
public TextView tvModified; // 显示修改时间
public ImageView ivAlertIcon; // 提醒图标
public TextView tvAlertDate; // 提醒日期
public ImageView ibSetBgColor; // 设置背景颜色的按钮
}
// 定义背景颜色按钮与颜色 ID 之间的映射
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();
static {
sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);
@ -93,6 +96,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE);
}
// 定义颜色选择器中被选中的背景颜色按钮
private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>();
static {
sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select);
@ -102,6 +106,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select);
}
// 字体大小按钮与字体大小 ID 之间的映射
private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>();
static {
sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE);
@ -110,6 +115,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER);
}
// 定义字体大小选择器中被选中的字体按钮
private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>();
static {
sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select);
@ -118,37 +124,31 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select);
}
// Tag 用于日志输出
private static final String TAG = "NoteEditActivity";
// 界面组件
private HeadViewHolder mNoteHeaderHolder;
private View mHeadViewPanel;
private View mNoteBgColorSelector;
private View mFontSizeSelector;
private EditText mNoteEditor;
private View mNoteEditorPanel;
private WorkingNote mWorkingNote;
private SharedPreferences mSharedPrefs;
private int mFontSizeId;
// 常量
private static final String PREFERENCE_FONT_SIZE = "pref_font_size";
private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;
public static final String TAG_CHECKED = String.valueOf('\u221A');
public static final String TAG_UNCHECKED = String.valueOf('\u25A1');
private LinearLayout mEditTextList;
private String mUserQuery;
private Pattern mPattern;
// 生命周期方法:初始化 Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -162,8 +162,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}
/**
* Current activity may be killed when the memory is low. Once it is killed, for another time
* user load this activity, we should restore the former state
* Activity
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
@ -179,19 +178,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}
}
// 初始化 Activity 的状态
private boolean initActivityState(Intent intent) {
/**
* If the user specified the {@link Intent#ACTION_VIEW} but not provided with id,
* then jump to the NotesListActivity
*/
mWorkingNote = null;
if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {
long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0);
mUserQuery = "";
/**
* Starting from the searched result
*/
if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);
@ -214,8 +206,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
} else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {
// New note
} else if (TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {
// 新建笔记
long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);
int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
@ -224,327 +216,145 @@ public class NoteEditActivity extends Activity implements OnClickListener,
int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID,
ResourceParser.getDefaultBgId(this));
// Parse call-record note
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);
if (callDate != 0 && phoneNumber != null) {
if (TextUtils.isEmpty(phoneNumber)) {
Log.w(TAG, "The call record number is null");
}
long noteId = 0;
if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(),
phoneNumber, callDate)) > 0) {
mWorkingNote = WorkingNote.load(this, noteId);
if (mWorkingNote == null) {
Log.e(TAG, "load call note failed with note id" + noteId);
finish();
return false;
}
} else {
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId,
widgetType, bgResId);
mWorkingNote.convertToCallNote(phoneNumber, callDate);
}
} else {
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType,
bgResId);
}
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} else {
Log.e(TAG, "Intent not specified action, should not support");
finish();
return false;
}
mWorkingNote.setOnSettingStatusChangedListener(this);
return true;
}
@Override
protected void onResume() {
super.onResume();
initNoteScreen();
}
private void initNoteScreen() {
mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId));
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
switchToListMode(mWorkingNote.getContent());
} else {
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
mNoteEditor.setSelection(mNoteEditor.getText().length());
}
for (Integer id : sBgSelectorSelectionMap.keySet()) {
findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE);
}
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this,
mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_YEAR));
/**
* TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker
* is not ready
*/
showAlertHeader();
}
private void showAlertHeader() {
if (mWorkingNote.hasClockAlert()) {
long time = System.currentTimeMillis();
if (time > mWorkingNote.getAlertDate()) {
mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired);
} else {
mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString(
mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS));
}
mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE);
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE);
} else {
mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE);
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);
};
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
initActivityState(intent);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
/**
* For new note without note id, we should firstly save it to
* generate a id. If the editing note is not worth saving, there
* is no id which is equivalent to create new note
*/
if (!mWorkingNote.existInDatabase()) {
saveNote();
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, bgResId);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId());
Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState");
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mNoteBgColorSelector, ev)) {
mNoteBgColorSelector.setVisibility(View.GONE);
return true;
}
if (mFontSizeSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mFontSizeSelector, ev)) {
mFontSizeSelector.setVisibility(View.GONE);
return true;
}
return super.dispatchTouchEvent(ev);
}
private boolean inRangeOfView(View view, MotionEvent ev) {
int []location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
if (ev.getX() < x
|| ev.getX() > (x + view.getWidth())
|| ev.getY() < y
|| ev.getY() > (y + view.getHeight())) {
return false;
}
return true;
}
// 初始化界面资源
private void initResources() {
mHeadViewPanel = findViewById(R.id.note_title);
mNoteHeaderHolder = new HeadViewHolder();
mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date);
mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon);
mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date);
mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color);
mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this);
mNoteEditor = (EditText) findViewById(R.id.note_edit_view);
mNoteEditorPanel = findViewById(R.id.sv_note_edit);
mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);
for (int id : sBgSelectorBtnsMap.keySet()) {
ImageView iv = (ImageView) findViewById(id);
iv.setOnClickListener(this);
}
mNoteHeaderHolder.tvModified = findViewById(R.id.tv_modified);
mNoteHeaderHolder.ivAlertIcon = findViewById(R.id.iv_alert_icon);
mNoteHeaderHolder.tvAlertDate = findViewById(R.id.tv_alert_date);
mNoteHeaderHolder.ibSetBgColor = findViewById(R.id.ib_set_bg_color);
mHeadViewPanel = findViewById(R.id.note_header);
mNoteBgColorSelector = findViewById(R.id.bg_color_selector);
mFontSizeSelector = findViewById(R.id.font_size_selector);
for (int id : sFontSizeBtnsMap.keySet()) {
View view = findViewById(id);
view.setOnClickListener(this);
};
mNoteEditor = findViewById(R.id.note_editor);
mNoteEditorPanel = findViewById(R.id.note_editor_panel);
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/
if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) {
mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
}
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE,
ResourceParser.TEXT_MEDIUM);
mWorkingNote.setNoteSettingChangedListener(this);
}
/**
*
*/
@Override
protected void onPause() {
super.onPause();
if(saveNote()) {
Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length());
public void onClick(View v) {
switch (v.getId()) {
case R.id.ib_set_bg_color:
// 设置背景颜色的点击事件
showBgColorDialog();
break;
case R.id.ll_font_normal:
case R.id.ll_font_small:
case R.id.ll_font_large:
case R.id.ll_font_super:
// 设置字体大小的点击事件
showFontSizeDialog(v.getId());
break;
}
clearSettingState();
}
private void updateWidget() {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) {
intent.setClass(this, NoteWidgetProvider_2x.class);
} else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) {
intent.setClass(this, NoteWidgetProvider_4x.class);
} else {
Log.e(TAG, "Unspported widget type");
return;
}
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
mWorkingNote.getWidgetId()
});
sendBroadcast(intent);
setResult(RESULT_OK, intent);
// 处理字体大小选择
private void showFontSizeDialog(int fontSizeId) {
// 通过字体大小 ID 更新 UI 和笔记的设置
mFontSizeId = sFontSizeBtnsMap.get(fontSizeId);
mWorkingNote.setFontSize(mFontSizeId);
updateFontSizeUI();
}
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_set_bg_color) {
mNoteBgColorSelector.setVisibility(View.VISIBLE);
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
- View.VISIBLE);
} else if (sBgSelectorBtnsMap.containsKey(id)) {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.GONE);
mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id));
mNoteBgColorSelector.setVisibility(View.GONE);
} else if (sFontSizeBtnsMap.containsKey(id)) {
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE);
mFontSizeId = sFontSizeBtnsMap.get(id);
mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit();
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
getWorkingText();
switchToListMode(mWorkingNote.getContent());
} else {
mNoteEditor.setTextAppearance(this,
TextAppearanceResources.getTexAppearanceResource(mFontSizeId));
}
mFontSizeSelector.setVisibility(View.GONE);
// 更新字体大小 UI
private void updateFontSizeUI() {
// 更新 UI 上选择的字体大小
for (int fontSizeId : sFontSizeBtnsMap.values()) {
int selectViewId = sFontSelectorSelectionMap.get(fontSizeId);
findViewById(selectViewId).setVisibility(View.VISIBLE);
}
}
@Override
public void onBackPressed() {
if(clearSettingState()) {
return;
}
saveNote();
super.onBackPressed();
// 显示背景颜色选择器
private void showBgColorDialog() {
// 显示选择背景颜色的对话框
}
private boolean clearSettingState() {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {
mNoteBgColorSelector.setVisibility(View.GONE);
return true;
} else if (mFontSizeSelector.getVisibility() == View.VISIBLE) {
mFontSizeSelector.setVisibility(View.GONE);
return true;
}
return false;
// 显示 Toast 消息
private void showToast(int resId) {
Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
}
public void onBackgroundColorChanged() {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.VISIBLE);
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
// 处理笔记设置变化的回调
@Override
public void onNoteSettingChanged() {
// 更新笔记内容、字体、背景等设置
}
// 监听笔记文本的变化
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (isFinishing()) {
return true;
}
clearSettingState();
menu.clear();
if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) {
getMenuInflater().inflate(R.menu.call_note_edit, menu);
} else {
getMenuInflater().inflate(R.menu.note_edit, menu);
}
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode);
} else {
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode);
}
if (mWorkingNote.hasClockAlert()) {
menu.findItem(R.id.menu_alert).setVisible(false);
} else {
menu.findItem(R.id.menu_delete_remind).setVisible(false);
}
return true;
public void onTextChanged(CharSequence text) {
// 监听笔记内容的变化
}
@Override
public void onTextViewChange(View view, boolean isChecked) {
// 处理文本视图的变化
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_new_note:
// 创建一个新笔记
createNewNote();
break;
case R.id.menu_delete:
// 删除当前笔记,显示确认对话框
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_note));
builder.setTitle(getString(R.string.alert_title_delete)); // 设置对话框标题
builder.setIcon(android.R.drawable.ic_dialog_alert); // 设置对话框图标
builder.setMessage(getString(R.string.alert_message_delete_note)); // 设置对话框消息
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// 确认删除,执行删除操作并关闭当前活动
deleteCurrentNote();
finish();
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.show();
builder.setNegativeButton(android.R.string.cancel, null); // 取消按钮
builder.show(); // 显示对话框
break;
case R.id.menu_font_size:
// 显示字体大小选择器
mFontSizeSelector.setVisibility(View.VISIBLE);
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);
break;
case R.id.menu_list_mode:
// 切换为清单模式
mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ?
TextNote.MODE_CHECK_LIST : 0);
break;
case R.id.menu_share:
// 共享笔记内容
getWorkingText();
sendTo(this, mWorkingNote.getContent());
break;
case R.id.menu_send_to_desktop:
// 发送笔记到桌面快捷方式
sendToDesktop();
break;
case R.id.menu_alert:
// 设置提醒
setReminder();
break;
case R.id.menu_delete_remind:
// 删除提醒
mWorkingNote.setAlertDate(0, false);
break;
default:
@ -553,321 +363,132 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true;
}
// 设置提醒
private void setReminder() {
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());
d.setOnDateTimeSetListener(new OnDateTimeSetListener() {
public void OnDateTimeSet(AlertDialog dialog, long date) {
mWorkingNote.setAlertDate(date , true);
mWorkingNote.setAlertDate(date, true);
}
});
d.show();
}
/**
* Share note to apps that support {@link Intent#ACTION_SEND} action
* and {@text/plain} type
*/
// 共享笔记到支持 ACTION_SEND 和 text/plain 类型的应用
private void sendTo(Context context, String info) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, info);
intent.setType("text/plain");
context.startActivity(intent);
intent.putExtra(Intent.EXTRA_TEXT, info); // 传递笔记内容
intent.setType("text/plain"); // 设置共享类型为纯文本
context.startActivity(intent); // 启动共享应用
}
// 创建一个新笔记
private void createNewNote() {
// Firstly, save current editing notes
saveNote();
// For safety, start a new NoteEditActivity
finish();
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId());
startActivity(intent);
saveNote(); // 保存当前笔记
finish(); // 关闭当前活动
Intent intent = new Intent(this, NoteEditActivity.class); // 启动新的编辑活动
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 设置活动为插入或编辑模式
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); // 传递当前笔记的文件夹 ID
startActivity(intent); // 启动活动
}
// 删除当前笔记
private void deleteCurrentNote() {
if (mWorkingNote.existInDatabase()) {
HashSet<Long> ids = new HashSet<Long>();
long id = mWorkingNote.getNoteId();
if (id != Notes.ID_ROOT_FOLDER) {
ids.add(id);
ids.add(id); // 如果笔记 ID 不为根文件夹,加入删除 ID 列表
} else {
Log.d(TAG, "Wrong note id, should not happen");
}
if (!isSyncMode()) {
// 非同步模式下删除笔记
if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) {
Log.e(TAG, "Delete Note error");
}
} else {
// 同步模式下将笔记移动到回收站
if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) {
Log.e(TAG, "Move notes to trash folder error, should not happens");
}
}
}
mWorkingNote.markDeleted(true);
mWorkingNote.markDeleted(true); // 标记笔记为已删除
}
// 判断是否为同步模式
private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
}
// 当闹钟提醒被改变时
public void onClockAlertChanged(long date, boolean set) {
/**
* User could set clock to an unsaved note, so before setting the
* alert clock, we should save the note first
*/
if (!mWorkingNote.existInDatabase()) {
saveNote();
saveNote(); // 如果笔记未保存,先保存
}
if (mWorkingNote.getNoteId() > 0) {
// 设置闹钟
Intent intent = new Intent(this, AlarmReceiver.class);
intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId()));
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE));
showAlertHeader();
if(!set) {
alarmManager.cancel(pendingIntent);
showAlertHeader(); // 显示提醒头部
if (!set) {
alarmManager.cancel(pendingIntent); // 取消提醒
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); // 设置闹钟提醒
}
} else {
/**
* There is the condition that user has input nothing (the note is
* not worthy saving), we have no note id, remind the user that he
* should input something
*/
// 如果没有笔记 ID则提醒用户输入内容
Log.e(TAG, "Clock alert setting error");
showToast(R.string.error_note_empty_for_clock);
}
}
// 更新小部件
public void onWidgetChanged() {
updateWidget();
}
// 删除编辑框中的文本
public void onEditTextDelete(int index, String text) {
int childCount = mEditTextList.getChildCount();
if (childCount == 1) {
return;
return; // 如果只有一个编辑框,直接返回
}
// 删除文本并调整其他编辑框的索引
for (int i = index + 1; i < childCount; i++) {
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i - 1);
}
mEditTextList.removeViewAt(index);
mEditTextList.removeViewAt(index); // 移除指定索引的视图
NoteEditText edit = null;
if(index == 0) {
edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById(
R.id.et_edit_text);
if (index == 0) {
edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById(R.id.et_edit_text);
} else {
edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById(
R.id.et_edit_text);
edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById(R.id.et_edit_text);
}
int length = edit.length();
edit.append(text);
edit.requestFocus();
edit.setSelection(length);
edit.append(text); // 将删除的文本重新添加到编辑框
edit.requestFocus(); // 重新聚焦
edit.setSelection(length); // 设置光标位置
}
// 当回车键被按下时
public void onEditTextEnter(int index, String text) {
/**
* Should not happen, check for debug
*/
if(index > mEditTextList.getChildCount()) {
if (index > mEditTextList.getChildCount()) {
Log.e(TAG, "Index out of mEditTextList boundrary, should not happen");
}
View view = getListItem(text, index);
mEditTextList.addView(view, index);
View view = getListItem(text, index); // 获取新的一项视图
mEditTextList.addView(view, index); // 添加新项到列表
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
edit.requestFocus();
edit.setSelection(0);
edit.requestFocus(); // 聚焦新项
edit.setSelection(0); // 设置光标位置
// 更新索引
for (int i = index + 1; i < mEditTextList.getChildCount(); i++) {
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i);
}
}
private void switchToListMode(String text) {
mEditTextList.removeAllViews();
String[] items = text.split("\n");
int index = 0;
for (String item : items) {
if(!TextUtils.isEmpty(item)) {
mEditTextList.addView(getListItem(item, index));
index++;
}
}
mEditTextList.addView(getListItem("", index));
mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus();
mNoteEditor.setVisibility(View.GONE);
mEditTextList.setVisibility(View.VISIBLE);
}
private Spannable getHighlightQueryResult(String fullText, String userQuery) {
SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
if (!TextUtils.isEmpty(userQuery)) {
mPattern = Pattern.compile(userQuery);
Matcher m = mPattern.matcher(fullText);
int start = 0;
while (m.find(start)) {
spannable.setSpan(
new BackgroundColorSpan(this.getResources().getColor(
R.color.user_query_highlight)), m.start(), m.end(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
start = m.end();
}
}
return spannable;
}
private View getListItem(String item, int index) {
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId));
CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item));
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else {
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
}
}
});
if (item.startsWith(TAG_CHECKED)) {
cb.setChecked(true);
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
item = item.substring(TAG_CHECKED.length(), item.length()).trim();
} else if (item.startsWith(TAG_UNCHECKED)) {
cb.setChecked(false);
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
item = item.substring(TAG_UNCHECKED.length(), item.length()).trim();
}
edit.setOnTextViewChangeListener(this);
edit.setIndex(index);
edit.setText(getHighlightQueryResult(item, mUserQuery));
return view;
}
public void onTextChange(int index, boolean hasText) {
if (index >= mEditTextList.getChildCount()) {
Log.e(TAG, "Wrong index, should not happen");
return;
}
if(hasText) {
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE);
} else {
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE);
}
}
public void onCheckListModeChanged(int oldMode, int newMode) {
if (newMode == TextNote.MODE_CHECK_LIST) {
switchToListMode(mNoteEditor.getText().toString());
} else {
if (!getWorkingText()) {
mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ",
""));
}
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
mEditTextList.setVisibility(View.GONE);
mNoteEditor.setVisibility(View.VISIBLE);
}
}
private boolean getWorkingText() {
boolean hasChecked = false;
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mEditTextList.getChildCount(); i++) {
View view = mEditTextList.getChildAt(i);
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
if (!TextUtils.isEmpty(edit.getText())) {
if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) {
sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n");
hasChecked = true;
} else {
sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n");
}
}
}
mWorkingNote.setWorkingText(sb.toString());
} else {
mWorkingNote.setWorkingText(mNoteEditor.getText().toString());
}
return hasChecked;
}
private boolean saveNote() {
getWorkingText();
boolean saved = mWorkingNote.saveNote();
if (saved) {
/**
* There are two modes from List view to edit view, open one note,
* create/edit a node. Opening node requires to the original
* position in the list when back from edit view, while creating a
* new node requires to the top of the list. This code
* {@link #RESULT_OK} is used to identify the create/edit state
*/
setResult(RESULT_OK);
}
return saved;
}
private void sendToDesktop() {
/**
* Before send message to home, we should make sure that current
* editing note is exists in databases. So, for new note, firstly
* save it
*/
if (!mWorkingNote.existInDatabase()) {
saveNote();
}
if (mWorkingNote.getNoteId() > 0) {
Intent sender = new Intent();
Intent shortcutIntent = new Intent(this, NoteEditActivity.class);
shortcutIntent.setAction(Intent.ACTION_VIEW);
shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId());
sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
sender.putExtra(Intent.EXTRA_SHORTCUT_NAME,
makeShortcutIconTitle(mWorkingNote.getContent()));
sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app));
sender.putExtra("duplicate", true);
sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
showToast(R.string.info_note_enter_desktop);
sendBroadcast(sender);
} else {
/**
* There is the condition that user has input nothing (the note is
* not worthy saving), we have no note id, remind the user that he
* should input something
*/
Log.e(TAG, "Send to desktop error");
showToast(R.string.error_note_empty_for_send_to_desktop);
}
}
private String makeShortcutIconTitle(String content) {
content = content.replace(TAG_CHECKED, "");
content = content.replace(TAG_UNCHECKED, "");
return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0,
SHORTCUT_ICON_TITLE_MAX_LEN) : content;
}
private void showToast(int resId) {
showToast(resId, Toast.LENGTH_SHORT);
}
private void showToast(int resId, int duration) {
Toast.makeText(this, resId, duration).show();
}
}

@ -37,15 +37,20 @@ import net.micode.notes.R;
import java.util.HashMap;
import java.util.Map;
/**
* EditText
*/
public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText";
private int mIndex;
private int mSelectionStartBeforeDelete;
private static final String TAG = "NoteEditText"; // 日志标签
private int mIndex; // 当前文本框的索引,用于标识
private int mSelectionStartBeforeDelete; // 删除操作前的文本选择起始位置
// 定义支持的链接协议
private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ;
// 存储不同协议类型对应的资源 ID
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
@ -54,28 +59,17 @@ public class NoteEditText extends EditText {
}
/**
* Call by the {@link NoteEditActivity} to delete or add edit text
* TextViewChangeListener
*/
public interface OnTextViewChangeListener {
/**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null
*/
void onEditTextDelete(int index, String text);
/**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen
*/
void onEditTextEnter(int index, String text);
/**
* Hide or show item option when text change
*/
void onTextChange(int index, boolean hasText);
void onEditTextDelete(int index, String text); // 删除当前编辑框时的回调
void onEditTextEnter(int index, String text); // 按下回车键时的回调
void onTextChange(int index, boolean hasText); // 文本内容变化时的回调
}
private OnTextViewChangeListener mOnTextViewChangeListener;
private OnTextViewChangeListener mOnTextViewChangeListener; // 文本变化监听器
public NoteEditText(Context context) {
super(context, null);
@ -99,11 +93,14 @@ public class NoteEditText extends EditText {
// TODO Auto-generated constructor stub
}
/**
*
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 计算触摸点的位置,更新光标
int x = (int) event.getX();
int y = (int) event.getY();
x -= getTotalPaddingLeft();
@ -112,24 +109,29 @@ public class NoteEditText extends EditText {
y += getScrollY();
Layout layout = getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
Selection.setSelection(getText(), off);
int line = layout.getLineForVertical(y); // 计算点击位置的行号
int off = layout.getOffsetForHorizontal(line, x); // 计算点击位置的字符偏移量
Selection.setSelection(getText(), off); // 更新光标位置
break;
}
return super.onTouchEvent(event);
}
/**
*
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
// 按下回车键时,如果有回调,允许其他操作
if (mOnTextViewChangeListener != null) {
return false;
}
break;
case KeyEvent.KEYCODE_DEL:
// 按下删除键时,记录当前选择位置
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
@ -138,27 +140,32 @@ public class NoteEditText extends EditText {
return super.onKeyDown(keyCode, event);
}
/**
*
*/
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_DEL:
// 删除键松开时如果文本为空并且索引不为0通知监听器删除文本
if (mOnTextViewChangeListener != null) {
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true;
}
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
Log.d(TAG, "OnTextViewChangeListener was not set");
}
break;
case KeyEvent.KEYCODE_ENTER:
// 回车键松开时,将光标后的文本传递给监听器
if (mOnTextViewChangeListener != null) {
int selectionStart = getSelectionStart();
String text = getText().subSequence(selectionStart, length()).toString();
setText(getText().subSequence(0, selectionStart));
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
Log.d(TAG, "OnTextViewChangeListener was not set");
}
break;
default:
@ -167,6 +174,9 @@ public class NoteEditText extends EditText {
return super.onKeyUp(keyCode, event);
}
/**
*
*/
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) {
@ -179,6 +189,9 @@ public class NoteEditText extends EditText {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
/**
* URL
*/
@Override
protected void onCreateContextMenu(ContextMenu menu) {
if (getText() instanceof Spanned) {
@ -188,9 +201,11 @@ public class NoteEditText extends EditText {
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
// 获取选中的URLSpan
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) {
int defaultResId = 0;
// 根据URL协议类型选择默认的菜单项
for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema);
@ -198,14 +213,16 @@ public class NoteEditText extends EditText {
}
}
// 如果没有匹配的协议类型,默认使用“其他”选项
if (defaultResId == 0) {
defaultResId = R.string.note_link_other;
}
// 为该链接添加一个菜单项,点击后打开链接
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// goto a new intent
// 点击链接后执行URLSpan的点击操作
urls[0].onClick(NoteEditText.this);
return true;
}
@ -215,3 +232,4 @@ public class NoteEditText extends EditText {
super.onCreateContextMenu(menu);
}
}

@ -25,36 +25,44 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
/**
* NoteItemData
* ID
*
*/
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;
// 定义查询结果的列名,用于 Cursor 查询
static final String[] PROJECTION = new String[]{
NoteColumns.ID, // 笔记 ID
NoteColumns.ALERTED_DATE, // 提醒日期
NoteColumns.BG_COLOR_ID, // 背景颜色 ID
NoteColumns.CREATED_DATE, // 创建日期
NoteColumns.HAS_ATTACHMENT, // 是否有附件
NoteColumns.MODIFIED_DATE, // 修改日期
NoteColumns.NOTES_COUNT, // 笔记的数量
NoteColumns.PARENT_ID, // 父级文件夹 ID
NoteColumns.SNIPPET, // 笔记内容摘要
NoteColumns.TYPE, // 笔记类型
NoteColumns.WIDGET_ID, // 小部件 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;
@ -70,63 +78,80 @@ public class NoteItemData {
private String mName;
private String mPhoneNumber;
// 用于指示笔记在列表中的位置状态
private boolean mIsLastItem;
private boolean mIsFirstItem;
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;
/**
* NoteItemData
* @param context
* @param cursor Cursor
*/
public NoteItemData(Context context, Cursor 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;
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);
mSnippet = cursor.getString(SNIPPET_COLUMN);
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, "");
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) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) {
mName = mPhoneNumber;
mName = mPhoneNumber; // 如果未找到联系人名称,使用电话号码
}
}
}
// 默认情况下,名称为空
if (mName == null) {
mName = "";
}
// 检查笔记在列表中的位置状态
checkPostion(cursor);
}
/**
*
* @param cursor Cursor
*/
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1);
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) {
if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true;
mIsMultiNotesFollowingFolder = true; // 多个笔记跟随在文件夹后
} else {
mIsOneNoteFollowingFolder = true;
mIsOneNoteFollowingFolder = true; // 一个笔记跟随在文件夹后
}
}
// 恢复 Cursor 状态
if (!cursor.moveToNext()) {
throw new IllegalStateException("cursor move to previous but can't move back");
}
@ -134,91 +159,95 @@ public class NoteItemData {
}
}
// 以下是获取笔记相关数据的 getter 方法
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
return mIsOneNoteFollowingFolder; // 是否是跟随在文件夹后的唯一笔记
}
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
return mIsMultiNotesFollowingFolder; // 是否有多个笔记跟随在文件夹后
}
public boolean isLast() {
return mIsLastItem;
return mIsLastItem; // 是否为最后一项
}
public String getCallName() {
return mName;
return mName; // 获取联系人名称或电话号码
}
public boolean isFirst() {
return mIsFirstItem;
return mIsFirstItem; // 是否为第一项
}
public boolean isSingle() {
return mIsOnlyOneItem;
return mIsOnlyOneItem; // 是否为唯一一项
}
public long getId() {
return mId;
return mId; // 获取笔记 ID
}
public long getAlertDate() {
return mAlertDate;
return mAlertDate; // 获取提醒日期
}
public long getCreatedDate() {
return mCreatedDate;
return mCreatedDate; // 获取创建日期
}
public boolean hasAttachment() {
return mHasAttachment;
return mHasAttachment; // 是否有附件
}
public long getModifiedDate() {
return mModifiedDate;
return mModifiedDate; // 获取修改日期
}
public int getBgColorId() {
return mBgColorId;
return mBgColorId; // 获取背景颜色 ID
}
public long getParentId() {
return mParentId;
return mParentId; // 获取父级文件夹 ID
}
public int getNotesCount() {
return mNotesCount;
return mNotesCount; // 获取笔记数量
}
public long getFolderId () {
return mParentId;
public long getFolderId() {
return mParentId; // 获取文件夹 ID与 ParentId 相同)
}
public int getType() {
return mType;
return mType; // 获取笔记类型
}
public int getWidgetType() {
return mWidgetType;
return mWidgetType; // 获取小部件类型
}
public int getWidgetId() {
return mWidgetId;
return mWidgetId; // 获取小部件 ID
}
public String getSnippet() {
return mSnippet;
return mSnippet; // 获取笔记摘要
}
public boolean hasAlert() {
return (mAlertDate > 0);
return (mAlertDate > 0); // 是否有提醒日期
}
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); // 是否是通话记录
}
// 静态方法,获取 Cursor 中的笔记类型
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
return cursor.getInt(TYPE_COLUMN); // 获取笔记类型
}
}

File diff suppressed because it is too large Load Diff

@ -31,18 +31,30 @@ import java.util.HashSet;
import java.util.Iterator;
/**
*
* CursorAdapterCursor
*/
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 HashMap<Integer, Boolean> mSelectedIndex; // 记录被选中的项
private int mNotesCount; // 笔记数量
private boolean mChoiceMode; // 是否处于选择模式
/**
* ID
*/
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
public int widgetId; // 小部件ID
public int widgetType; // 小部件类型
};
/**
*
*
* @param context
*/
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
@ -50,45 +62,86 @@ public class NotesListAdapter extends CursorAdapter {
mNotesCount = 0;
}
/**
*
*
* @param context
* @param cursor
* @param parent
* @return
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context);
return new NotesListItem(context); // 返回新的笔记列表项视图
}
/**
*
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor);
NoteItemData itemData = new NoteItemData(context, cursor); // 创建笔记数据对象
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
isSelectedItem(cursor.getPosition())); // 绑定数据到视图
}
}
/**
*
*
* @param position
* @param checked
*/
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked);
notifyDataSetChanged();
mSelectedIndex.put(position, checked); // 更新选中状态
notifyDataSetChanged(); // 通知数据集发生变化
}
/**
*
*
* @return true false
*/
public boolean isInChoiceMode() {
return mChoiceMode;
}
/**
*
*
* @param mode true false 退
*/
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear();
mChoiceMode = mode;
mSelectedIndex.clear(); // 清除所有选择状态
mChoiceMode = mode; // 设置选择模式状态
}
/**
*
*
* @param checked
*/
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);
setCheckedItem(i, checked); // 设置每个笔记的选中状态
}
}
}
}
/**
* ID
*
* @return ID
*/
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) {
@ -97,7 +150,7 @@ public class NotesListAdapter extends CursorAdapter {
if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen");
} else {
itemSet.add(id);
itemSet.add(id); // 添加选中的项ID
}
}
}
@ -105,6 +158,11 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
/**
*
*
* @return
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) {
@ -115,10 +173,7 @@ public class NotesListAdapter extends CursorAdapter {
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
*/
itemSet.add(widget); // 添加选中的小部件信息
} else {
Log.e(TAG, "Invalid cursor");
return null;
@ -128,6 +183,11 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
/**
*
*
* @return
*/
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
@ -137,43 +197,65 @@ public class NotesListAdapter extends CursorAdapter {
int count = 0;
while (iter.hasNext()) {
if (true == iter.next()) {
count++;
count++; // 统计选中的项数量
}
}
return count;
}
/**
*
*
* @return true false
*/
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount);
return (checkedCount != 0 && checkedCount == mNotesCount); // 所有项已选中
}
/**
*
*
* @param position
* @return true false
*/
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false;
return false; // 如果该位置没有记录选中状态,默认未选中
}
return mSelectedIndex.get(position);
}
/**
*
*/
@Override
protected void onContentChanged() {
super.onContentChanged();
calcNotesCount();
calcNotesCount(); // 更新笔记数量
}
/**
*
*
* @param cursor
*/
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
calcNotesCount();
calcNotesCount(); // 更新笔记数量
}
/**
*
*/
private void calcNotesCount() {
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++;
mNotesCount++; // 统计笔记数量
}
} else {
Log.e(TAG, "Invalid cursor");
@ -182,3 +264,4 @@ public class NotesListAdapter extends CursorAdapter {
}
}
}

@ -29,94 +29,128 @@ import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
/**
* NotesListItem
*
*/
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; // 用于显示复选框(如果启用选择模式)
/**
*
* @param context
*/
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); // 加载布局
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); // 获取复选框
}
/**
*
*
* @param context
* @param data
* @param choiceMode
* @param 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; // 存储数据对象
// 处理来电记录文件夹项
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE);
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);
mAlert.setImageResource(R.drawable.call_record); // 设置来电记录图标
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.VISIBLE);
// 处理来电记录中的单个笔记项
mCallName.setVisibility(View.VISIBLE); // 显示来电名称
mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
mTitle.setTextAppearance(context, R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 设置笔记内容的格式化标题
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setImageResource(R.drawable.clock); // 如果有提醒,显示时钟图标
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
mAlert.setVisibility(View.GONE); // 否则隐藏警告图标
}
} else {
mCallName.setVisibility(View.GONE);
// 处理普通文件夹项
mCallName.setVisibility(View.GONE); // 隐藏来电名称
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
if (data.getType() == Notes.TYPE_FOLDER) {
// 文件夹类型的笔记项
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));
mAlert.setVisibility(View.GONE);
data.getNotesCount()));
mAlert.setVisibility(View.GONE); // 文件夹不显示警告图标
} else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 设置标题文本
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setImageResource(R.drawable.clock); // 如果有提醒,显示时钟图标
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
mAlert.setVisibility(View.GONE); // 否则隐藏警告图标
}
}
}
// 设置更新时间文本
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 设置背景颜色
setBackground(data);
}
/**
*
* @param data
*/
private void setBackground(NoteItemData data) {
int id = data.getBgColorId();
int id = data.getBgColorId(); // 获取背景颜色ID
if (data.getType() == Notes.TYPE_NOTE) {
// 设置普通笔记的背景
if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); // 单个或后续文件夹笔记
} else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); // 最后一项笔记
} 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());
setBackgroundResource(NoteItemBgResources.getFolderBgRes()); // 设置文件夹背景
}
}
/**
*
* @return
*/
public NoteItemData getItemData() {
return mItemData;
}
}

@ -47,43 +47,40 @@ 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;
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 */
// 设置ActionBar的返回按钮
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);
}
@ -92,8 +89,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
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) {
@ -106,77 +102,82 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
if (!found) {
setSyncAccount(accountNew.name);
setSyncAccount(accountNew.name); // 设置同步账户
break;
}
}
}
}
refreshUI();
refreshUI(); // 更新UI界面
}
@Override
protected void onDestroy() {
// 注销广播接收器
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
super.onDestroy();
}
// 加载账户偏好设置
private void loadAccountPreference() {
mAccountCategory.removeAll();
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)
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
}
return true;
}
});
mAccountCategory.addPreference(accountPref);
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);
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);
GTaskSyncService.startSync(NotesPreferenceActivity.this); // 开始同步
}
});
}
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); // 按钮是否可用,取决于是否有同步账户
// 设置最后同步时间
if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE);
@ -193,11 +194,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
// 更新UI界面
private void refreshUI() {
loadAccountPreference();
loadSyncButton();
loadAccountPreference(); // 加载账户设置
loadSyncButton(); // 加载同步按钮
}
// 显示选择账户的对话框
private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
@ -208,7 +211,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null);
dialogBuilder.setPositiveButton(null, null); // 没有默认的"确定"按钮
Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this);
@ -216,6 +219,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mOriAccounts = accounts;
mHasAddedAccount = false;
// 显示所有Google账户供用户选择
if (accounts.length > 0) {
CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items;
@ -230,9 +234,9 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString());
setSyncAccount(itemMapping[which].toString()); // 设置选中的账户
dialog.dismiss();
refreshUI();
refreshUI(); // 刷新UI
}
});
}
@ -240,20 +244,22 @@ public class NotesPreferenceActivity extends PreferenceActivity {
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() {
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"
"gmail-ls"
});
startActivityForResult(intent, -1);
startActivityForResult(intent, -1); // 打开账户添加界面
dialog.dismiss();
}
});
}
// 显示更改账户的确认对话框
private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
@ -273,21 +279,23 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showSelectAccountAlertDialog();
showSelectAccountAlertDialog(); // 更改账户
} else if (which == 1) {
removeSyncAccount();
refreshUI();
removeSyncAccount(); // 移除账户
refreshUI(); // 刷新UI
}
}
});
dialogBuilder.show();
}
// 获取所有Google账户
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
}
// 设置同步账户
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
@ -299,10 +307,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
editor.commit();
// clean up last sync time
// 清除最后同步时间
setLastSyncTime(this, 0);
// clean up local gtask related info
// 清理本地的gtask相关信息
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
@ -318,6 +326,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
// 移除同步账户
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
@ -329,7 +338,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
editor.commit();
// clean up local gtask related info
// 清理本地的gtask相关信息
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
@ -340,12 +349,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}).start();
}
// 获取同步账户的名称
public static String getSyncAccountName(Context context) {
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);
@ -354,12 +365,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.commit();
}
// 获取最后同步时间
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
// 广播接收器:用于监听同步状态变化
private class GTaskReceiver extends BroadcastReceiver {
@Override
@ -374,6 +387,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
// 菜单选项处理
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:

@ -15,6 +15,7 @@
*/
package net.micode.notes.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
@ -33,31 +34,39 @@ 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
// 用于查询数据库的投影列ID、背景颜色ID和摘要信息
public static final String[] PROJECTION = new String[] {
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;
public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_SNIPPET = 2;
// 日志标签
private static final String TAG = "NoteWidgetProvider";
// 当一个小部件被删除时调用
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues();
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // 将小部件ID标记为无效
// 更新笔记的WIDGET_ID字段将已删除的小部件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])});
new String[] { String.valueOf(appWidgetIds[i]) });
}
}
// 获取与小部件相关的笔记信息如摘要、背景颜色ID
private Cursor getNoteWidgetInfo(Context context, int widgetId) {
// 查询与小部件ID相关的笔记排除垃圾箱文件夹的笔记
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
@ -65,21 +74,27 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
null);
}
// 更新小部件内容
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) {
boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) {
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
// 默认背景ID和摘要内容
int bgId = ResourceParser.getDefaultBgId(context);
String snippet = "";
// 创建一个启动笔记编辑活动的Intent
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]);
if (c != null && c.moveToFirst()) {
if (c.getCount() > 1) {
@ -87,46 +102,58 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
c.close();
return;
}
// 获取摘要和背景颜色ID
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);
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);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 设置为插入或编辑操作
}
// 关闭Cursor
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
*/
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); // 设置背景资源
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); // 传递背景ID
PendingIntent pendingIntent = null;
if (privacyMode) {
rv.setTextViewText(R.id.widget_text,
context.getString(R.string.widget_under_visit_mode));
// 如果是隐私模式,设置提示信息
rv.setTextViewText(R.id.widget_text, context.getString(R.string.widget_under_visit_mode));
// 设置点击事件为打开笔记列表
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
} else {
// 否则显示笔记的摘要内容
rv.setTextViewText(R.id.widget_text, snippet);
// 设置点击事件为打开笔记编辑界面
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
// 设置小部件点击事件
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
// 更新小部件
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
}
}
// 获取背景资源ID根据笔记的背景颜色ID来设置
protected abstract int getBgResourceId(int bgId);
// 获取小部件的布局ID
protected abstract int getLayoutId();
// 获取小部件的类型
protected abstract int getWidgetType();
}

@ -23,25 +23,29 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
// 重写onUpdate方法调用父类的update方法更新2x小部件的内容
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds);
}
// 返回小部件的布局ID2x布局资源
@Override
protected int getLayoutId() {
return R.layout.widget_2x;
return R.layout.widget_2x; // 返回对应的小部件2x布局
}
// 返回根据背景颜色ID获取2x小部件背景资源的ID
@Override
protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); // 使用ResourceParser获取2x背景资源
}
// 返回该小部件的类型
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X;
return Notes.TYPE_WIDGET_2X; // 返回2x类型的小部件标识
}
}

@ -23,24 +23,29 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
// 重写onUpdate方法调用父类的update方法更新4x小部件的内容
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds);
}
// 返回小部件的布局ID4x布局资源
@Override
protected int getLayoutId() {
return R.layout.widget_4x;
return R.layout.widget_4x; // 返回对应的小部件4x布局
}
// 返回根据背景颜色ID获取4x小部件背景资源的ID
@Override
protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); // 使用ResourceParser获取4x背景资源
}
// 返回该小部件的类型
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X;
return Notes.TYPE_WIDGET_4X; // 返回4x类型的小部件标识
}
}

Loading…
Cancel
Save