diff --git a/AndroidManifest.xml b/AndroidManifest.xml
new file mode 100644
index 0000000..a1dc3f2
--- /dev/null
+++ b/AndroidManifest.xml
@@ -0,0 +1,259 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/notes/data/Contact.java b/java/net/micode/notes/data/Contact.java
similarity index 100%
rename from src/notes/data/Contact.java
rename to java/net/micode/notes/data/Contact.java
diff --git a/src/notes/data/Notes.java b/java/net/micode/notes/data/Notes.java
similarity index 98%
rename from src/notes/data/Notes.java
rename to java/net/micode/notes/data/Notes.java
index 1592d5d..fa5943b 100644
--- a/src/notes/data/Notes.java
+++ b/java/net/micode/notes/data/Notes.java
@@ -59,7 +59,6 @@ public class Notes {
* {@link Notes#ID_ROOT_FOLDER }:根文件夹(默认文件夹)
* {@link Notes#ID_TEMPARAY_FOLDER }:临时文件夹(存放无归属的笔记)
* {@link Notes#ID_CALL_RECORD_FOLDER}:通话记录文件夹(专门存储通话记录笔记)
- * {@link Notes#ID_TRASH_FOLER}:回收站文件夹(存放被删除的笔记/文件夹)
*/
// 根文件夹ID(默认文件夹,所有无指定文件夹的笔记默认归属此文件夹)
public static final int ID_ROOT_FOLDER = 0;
@@ -67,7 +66,7 @@ public class Notes {
public static final int ID_TEMPARAY_FOLDER = -1;
// 通话记录文件夹ID(专门存储通话记录类型的笔记)
public static final int ID_CALL_RECORD_FOLDER = -2;
- // 回收站文件夹ID(存放被用户删除的笔记或文件夹)
+ // 回收站文件夹ID(已废弃,用于兼容旧代码)
public static final int ID_TRASH_FOLER = -3;
/**
@@ -207,6 +206,12 @@ public class Notes {
*
数据类型: INTEGER
*/
public static final String TYPE = "type";
+
+ /**
+ * 笔记是否置顶(0:不置顶,1:置顶)
+ * 数据类型: INTEGER
+ */
+ public static final String PINNED = "pinned";
/**
* 最后一次同步的ID(用于GTask同步,标记同步状态)
@@ -220,6 +225,8 @@ public class Notes {
*/
public static final String LOCAL_MODIFIED = "local_modified";
+
+
/**
* 移动到临时文件夹前的原始父级ID(用于恢复笔记的原始归属文件夹)
* 数据类型: INTEGER (long)
@@ -381,4 +388,6 @@ public class Notes {
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
}
+
+
}
\ No newline at end of file
diff --git a/src/notes/data/NotesDatabaseHelper.java b/java/net/micode/notes/data/NotesDatabaseHelper.java
similarity index 92%
rename from src/notes/data/NotesDatabaseHelper.java
rename to java/net/micode/notes/data/NotesDatabaseHelper.java
index 516988f..743abac 100644
--- a/src/notes/data/NotesDatabaseHelper.java
+++ b/java/net/micode/notes/data/NotesDatabaseHelper.java
@@ -45,12 +45,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "note.db";
/**
- * 数据库版本号,用于版本升级控制(当前为4)
+ * 数据库版本号,用于版本升级控制(当前为6,增加了标签功能)
*/
- private static final int DB_VERSION = 4;
+ private static final int DB_VERSION = 6;
/**
- * 数据表名称接口,定义note表和data表的名称常量,提高代码可读性
+ * 数据表名称接口,定义note表、data表、标签表和便签-标签关联表的名称常量
*/
public interface TABLE {
// 笔记/文件夹表名称
@@ -90,6 +90,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + // 文件夹下的笔记数量
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + // 文件夹名称/笔记摘要
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + // 类型(笔记/文件夹/系统)
+ NoteColumns.PINNED + " INTEGER NOT NULL DEFAULT 0," + // 是否置顶(0:不置顶,1:置顶)
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联的Widget ID
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + // 关联的Widget类型
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + // 同步ID(GTask)
@@ -122,10 +123,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
* 创建data表的NOTE_ID索引的SQL语句
* 索引用于提升根据NOTE_ID查询data表的性能(频繁关联查询场景)
*/
- private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
- "CREATE INDEX IF NOT EXISTS note_id_index ON " +
+ private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
+ "CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
+
+
// ====================== 数据库触发器SQL语句(note表) ======================
/**
* 触发器:更新笔记的父级ID时,增加新文件夹的笔记数量
@@ -255,20 +258,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
- /**
- * 触发器:将文件夹移至回收站时,同步移动该文件夹下的所有笔记至回收站
- * 触发时机:note表的PARENT_ID更新为回收站ID后
- * 逻辑:将该文件夹下的所有笔记的PARENT_ID设为回收站ID
- */
- 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";
+
/**
* 构造方法,调用父类SQLiteOpenHelper的构造方法初始化数据库
@@ -308,7 +298,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
- db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
// 创建新触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
@@ -317,7 +306,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
- db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
/**
@@ -352,13 +340,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
- /**
- * 4. 回收站文件夹:存储被删除的笔记和文件夹
- */
- values.clear();
- values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
- values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
- db.insert(TABLE.NOTE, null, values);
+
}
/**
@@ -376,6 +358,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "data table has been created");
}
+
+
/**
* 重新创建data表的所有触发器(先删除旧触发器,再创建新触发器)
*
@@ -454,6 +438,16 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
upgradeToV4(db);
oldVersion++;
}
+
+ // 从版本4升级到版本5
+ if (oldVersion == 4) {
+ // 为note表添加pinned字段(用于置顶功能)
+ db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.PINNED
+ + " INTEGER NOT NULL DEFAULT 0");
+ oldVersion++;
+ }
+
+
// 如果需要,重建触发器
if (reCreateTriggers) {
@@ -468,6 +462,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
}
}
+
+
/**
* 从版本1升级到版本2的逻辑
* 删除旧表,重新创建新表(全量重建,会丢失数据,适用于早期版本)
@@ -486,8 +482,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* 从版本2升级到版本3的逻辑
* 1. 删除无用的触发器;
- * 2. 为note表添加GTASK_ID列;
- * 3. 新增回收站系统文件夹。
+ * 2. 为note表添加GTASK_ID列。
*
* @param db SQLiteDatabase对象
*/
@@ -499,11 +494,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 为note表添加GTASK_ID列(用于GTask同步)
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
- // 新增回收站系统文件夹
- 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);
}
/**
diff --git a/src/notes/data/NotesProvider.java b/java/net/micode/notes/data/NotesProvider.java
similarity index 76%
rename from src/notes/data/NotesProvider.java
rename to java/net/micode/notes/data/NotesProvider.java
index e0c01d2..392cae6 100644
--- a/src/notes/data/NotesProvider.java
+++ b/java/net/micode/notes/data/NotesProvider.java
@@ -30,6 +30,7 @@ import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.R;
+import net.micode.notes.tool.SearchHistoryManager;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
@@ -91,6 +92,7 @@ public class NotesProvider extends ContentProvider {
*/
private static final int URI_SEARCH_SUGGEST = 6;
+
/**
* 静态代码块:初始化UriMatcher,添加Uri匹配规则
* 规则格式:authority(授权名) + path(路径) -> 匹配类型常量
@@ -112,6 +114,7 @@ public class NotesProvider extends ContentProvider {
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
// 匹配搜索建议(带关键词):content://micode_notes/suggestions/query/关键词 -> URI_SEARCH_SUGGEST
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
+
}
/**
@@ -217,22 +220,81 @@ public class NotesProvider extends ContentProvider {
searchString = uri.getQueryParameter("pattern");
}
- // 关键词为空时返回null
- if (TextUtils.isEmpty(searchString)) {
- return null;
- }
-
- try {
- // 拼接SQL的LIKE关键词(%表示任意字符,如%笔记%)
- searchString = String.format("%%%s%%", searchString);
- // 执行原生SQL查询,获取搜索结果
- c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
- new String[] { searchString });
- } catch (IllegalStateException ex) {
- // 捕获异常,输出错误日志
- Log.e(TAG, "got exception: " + ex.toString());
+ // 如果是搜索建议类型,且搜索关键词不为空,返回合并结果
+ if (mMatcher.match(uri) == URI_SEARCH_SUGGEST && !TextUtils.isEmpty(searchString)) {
+ try {
+ // 1. 获取搜索历史记录
+ SearchHistoryManager historyManager = SearchHistoryManager.getInstance(getContext());
+ java.util.List historyList = historyManager.getSearchHistoryList();
+
+ // 2. 获取便签搜索结果
+ String likeSearchString = String.format("%%%s%%", searchString);
+ Cursor noteCursor = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, new String[] { likeSearchString });
+
+ // 3. 创建矩阵游标,用于合并结果
+ String[] columns = { NoteColumns.ID, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA,
+ SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2,
+ SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
+ SearchManager.SUGGEST_COLUMN_INTENT_DATA };
+ android.database.MatrixCursor matrixCursor = new android.database.MatrixCursor(columns);
+
+ // 4. 添加搜索历史记录(只添加匹配的历史)
+ for (String history : historyList) {
+ if (history.toLowerCase().contains(searchString.toLowerCase())) {
+ matrixCursor.addRow(new Object[] {
+ -1, // ID为-1表示是历史记录
+ history, // 历史记录作为Intent Extra数据
+ history, // 显示的文本1
+ getContext().getString(R.string.search_history), // 显示的文本2
+ R.drawable.search_result, // 图标
+ Intent.ACTION_SEARCH, // Intent动作
+ Notes.TextNote.CONTENT_TYPE // Intent数据类型
+ });
+ }
+ }
+
+ // 5. 添加便签搜索结果
+ if (noteCursor != null && noteCursor.moveToFirst()) {
+ do {
+ // 从便签搜索结果中获取列数据
+ long noteId = noteCursor.getLong(noteCursor.getColumnIndexOrThrow(NoteColumns.ID));
+ String extraData = noteCursor.getString(noteCursor.getColumnIndexOrThrow(SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA));
+ String text1 = noteCursor.getString(noteCursor.getColumnIndexOrThrow(SearchManager.SUGGEST_COLUMN_TEXT_1));
+ String text2 = noteCursor.getString(noteCursor.getColumnIndexOrThrow(SearchManager.SUGGEST_COLUMN_TEXT_2));
+ int icon = noteCursor.getInt(noteCursor.getColumnIndexOrThrow(SearchManager.SUGGEST_COLUMN_ICON_1));
+ String action = noteCursor.getString(noteCursor.getColumnIndexOrThrow(SearchManager.SUGGEST_COLUMN_INTENT_ACTION));
+ String data = noteCursor.getString(noteCursor.getColumnIndexOrThrow(SearchManager.SUGGEST_COLUMN_INTENT_DATA));
+
+ matrixCursor.addRow(new Object[] { noteId, extraData, text1, text2, icon, action, data });
+ } while (noteCursor.moveToNext());
+ }
+
+ // 6. 关闭便签搜索结果游标
+ if (noteCursor != null) {
+ noteCursor.close();
+ }
+
+ // 7. 设置矩阵游标为结果
+ c = matrixCursor;
+ } catch (IllegalStateException ex) {
+ // 捕获异常,输出错误日志
+ Log.e(TAG, "got exception: " + ex.toString());
+ }
+ } else if (!TextUtils.isEmpty(searchString)) {
+ // 普通搜索或搜索建议但关键词为空,只返回便签搜索结果
+ try {
+ // 拼接SQL的LIKE关键词(%表示任意字符,如%笔记%)
+ searchString = String.format("%%%s%%", searchString);
+ // 执行原生SQL查询,获取搜索结果
+ c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
+ new String[] { searchString });
+ } catch (IllegalStateException ex) {
+ // 捕获异常,输出错误日志
+ Log.e(TAG, "got exception: " + ex.toString());
+ }
}
break;
+
default:
// 未知Uri,抛出异常
throw new IllegalArgumentException("Unknown URI " + uri);
@@ -275,6 +337,7 @@ public class NotesProvider extends ContentProvider {
// 插入data表,获取插入的ID
insertedId = dataId = db.insert(TABLE.DATA, null, values);
break;
+
default:
// 未知Uri,抛出异常
throw new IllegalArgumentException("Unknown URI " + uri);
@@ -292,6 +355,8 @@ public class NotesProvider extends ContentProvider {
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
+
+
// 返回包含插入ID的新Uri
return ContentUris.withAppendedId(uri, insertedId);
}
@@ -311,11 +376,12 @@ public class NotesProvider extends ContentProvider {
// 获取可写的SQLiteDatabase对象
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false; // 标记是否删除的是data表数据
+ long noteId = 0; // 用于存储便签ID,以便发送通知
// 根据Uri匹配的类型执行删除逻辑
switch (mMatcher.match(uri)) {
case URI_NOTE:
- // 删除note表数据,条件:传入的selection + ID>0(排除系统文件夹)
+ // 直接删除便签,条件:传入的selection + ID>0(排除系统文件夹)
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
@@ -325,13 +391,12 @@ public class NotesProvider extends ContentProvider {
/**
* ID小于等于0的是系统文件夹,不允许删除
*/
- long noteId = Long.valueOf(id);
+ noteId = Long.valueOf(id);
if (noteId <= 0) {
break;
}
- // 删除note表单条数据,条件:ID=id + 传入的selection
- count = db.delete(TABLE.NOTE,
- NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
+ // 直接删除便签,条件:ID=id + 传入的selection
+ count = db.delete(TABLE.NOTE, NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
// 删除data表数据
@@ -345,6 +410,9 @@ public class NotesProvider extends ContentProvider {
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
break;
+
+
+
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
@@ -355,6 +423,11 @@ public class NotesProvider extends ContentProvider {
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
+ // 如果是便签相关操作,通知对应的便签Uri
+ if (noteId > 0) {
+ getContext().getContentResolver().notifyChange(
+ ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
+ }
// 通知当前Uri的数据变更
getContext().getContentResolver().notifyChange(uri, null);
}
@@ -377,6 +450,7 @@ public class NotesProvider extends ContentProvider {
// 获取可写的SQLiteDatabase对象
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false; // 标记是否更新的是data表数据
+ long noteId = 0; // 用于存储便签ID,以便发送通知
// 根据Uri匹配的类型执行更新逻辑
switch (mMatcher.match(uri)) {
@@ -405,6 +479,9 @@ public class NotesProvider extends ContentProvider {
+ parseSelection(selection), selectionArgs);
updateData = true;
break;
+
+
+
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
@@ -415,6 +492,11 @@ public class NotesProvider extends ContentProvider {
if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
+ // 如果是便签相关操作,通知对应的便签Uri
+ if (noteId > 0) {
+ getContext().getContentResolver().notifyChange(
+ ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
+ }
// 通知当前Uri的数据变更
getContext().getContentResolver().notifyChange(uri, null);
}
diff --git a/src/notes/gtask/data/MetaData.java b/java/net/micode/notes/gtask/data/MetaData.java
similarity index 100%
rename from src/notes/gtask/data/MetaData.java
rename to java/net/micode/notes/gtask/data/MetaData.java
diff --git a/src/notes/gtask/data/Node.java b/java/net/micode/notes/gtask/data/Node.java
similarity index 100%
rename from src/notes/gtask/data/Node.java
rename to java/net/micode/notes/gtask/data/Node.java
diff --git a/src/notes/gtask/data/SqlData.java b/java/net/micode/notes/gtask/data/SqlData.java
similarity index 100%
rename from src/notes/gtask/data/SqlData.java
rename to java/net/micode/notes/gtask/data/SqlData.java
diff --git a/src/notes/gtask/data/SqlNote.java b/java/net/micode/notes/gtask/data/SqlNote.java
similarity index 52%
rename from src/notes/gtask/data/SqlNote.java
rename to java/net/micode/notes/gtask/data/SqlNote.java
index 7eaab22..79a4095 100644
--- a/src/notes/gtask/data/SqlNote.java
+++ b/java/net/micode/notes/gtask/data/SqlNote.java
@@ -37,33 +37,12 @@ import org.json.JSONObject;
import java.util.ArrayList;
-/**
- * 笔记应用note表及关联data表的核心数据操作封装类
- * 该类是GTask同步过程中处理笔记/文件夹数据的核心类,封装了以下关键功能:
- * 1. 加载已有数据:从Cursor、note表ID加载note表数据,并联动加载关联的data表数据;
- * 2. 数据差异记录:通过mDiffNoteValues仅存储变化的字段,减少数据库操作开销;
- * 3. JSON序列化/反序列化:实现与JSON的互相转换,支撑GTask同步的网络数据传输;
- * 4. 数据持久化:支持新数据插入、已有数据更新,联动处理data表的提交,并提供版本验证机制保证同步一致性;
- * 5. 区分数据类型:对笔记(TYPE_NOTE)、文件夹(TYPE_FOLDER)、系统文件夹(TYPE_SYSTEM)做差异化处理。
- *
- * @author MiCode Open Source Community
- * @date 2010-2011
- */
+
public class SqlNote {
- /**
- * 日志标签,使用类的简单名称,便于调试时定位日志来源
- */
private static final String TAG = SqlNote.class.getSimpleName();
- /**
- * 无效的ID常量,用于标记note表ID尚未初始化或不存在(区别于数据库的自增ID)
- */
private static final int INVALID_ID = -99999;
- /**
- * note表的查询投影(Projection),定义了查询时需要返回的所有核心列
- * 包含note表的全部业务字段,减少数据传输开销,适配所有数据加载场景
- */
public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@@ -73,193 +52,139 @@ public class SqlNote {
NoteColumns.VERSION
};
- // ====================== PROJECTION_NOTE的列索引常量 ======================
- /** PROJECTION_NOTE中ID列的索引(对应NoteColumns.ID) */
public static final int ID_COLUMN = 0;
- /** PROJECTION_NOTE中提醒时间列的索引(对应NoteColumns.ALERTED_DATE) */
+
public static final int ALERTED_DATE_COLUMN = 1;
- /** PROJECTION_NOTE中背景颜色ID列的索引(对应NoteColumns.BG_COLOR_ID) */
+
public static final int BG_COLOR_ID_COLUMN = 2;
- /** PROJECTION_NOTE中创建时间列的索引(对应NoteColumns.CREATED_DATE) */
+
public static final int CREATED_DATE_COLUMN = 3;
- /** PROJECTION_NOTE中是否有附件列的索引(对应NoteColumns.HAS_ATTACHMENT) */
+
public static final int HAS_ATTACHMENT_COLUMN = 4;
- /** PROJECTION_NOTE中修改时间列的索引(对应NoteColumns.MODIFIED_DATE) */
+
public static final int MODIFIED_DATE_COLUMN = 5;
- /** PROJECTION_NOTE中文件夹笔记数量列的索引(对应NoteColumns.NOTES_COUNT) */
+
public static final int NOTES_COUNT_COLUMN = 6;
- /** PROJECTION_NOTE中父级ID列的索引(对应NoteColumns.PARENT_ID) */
+
public static final int PARENT_ID_COLUMN = 7;
- /** PROJECTION_NOTE中摘要/名称列的索引(对应NoteColumns.SNIPPET) */
+
public static final int SNIPPET_COLUMN = 8;
- /** PROJECTION_NOTE中类型列的索引(对应NoteColumns.TYPE) */
+
public static final int TYPE_COLUMN = 9;
- /** PROJECTION_NOTE中小组件ID列的索引(对应NoteColumns.WIDGET_ID) */
+
public static final int WIDGET_ID_COLUMN = 10;
- /** PROJECTION_NOTE中小组件类型列的索引(对应NoteColumns.WIDGET_TYPE) */
+
public static final int WIDGET_TYPE_COLUMN = 11;
- /** PROJECTION_NOTE中同步ID列的索引(对应NoteColumns.SYNC_ID) */
+
public static final int SYNC_ID_COLUMN = 12;
- /** PROJECTION_NOTE中本地修改标记列的索引(对应NoteColumns.LOCAL_MODIFIED) */
+
public static final int LOCAL_MODIFIED_COLUMN = 13;
- /** PROJECTION_NOTE中原始父级ID列的索引(对应NoteColumns.ORIGIN_PARENT_ID) */
+
public static final int ORIGIN_PARENT_ID_COLUMN = 14;
- /** PROJECTION_NOTE中GTask ID列的索引(对应NoteColumns.GTASK_ID) */
+
public static final int GTASK_ID_COLUMN = 15;
- /** PROJECTION_NOTE中版本号列的索引(对应NoteColumns.VERSION) */
+
public static final int VERSION_COLUMN = 16;
- // ====================== 成员变量 ======================
- /** 上下文对象,用于获取资源、ContentResolver等 */
private Context mContext;
- /** Android内容解析器,用于访问ContentProvider进行note/data表的增删改查 */
private ContentResolver mContentResolver;
- /** 数据创建标记:true表示新数据(需插入数据库),false表示已有数据(需更新数据库) */
private boolean mIsCreate;
- /** note表的主键ID,关联到具体的行数据 */
private long mId;
- /** 笔记的提醒时间戳(毫秒) */
private long mAlertDate;
- /** 笔记/文件夹的背景颜色ID(对应资源文件中的颜色配置) */
private int mBgColorId;
- /** 数据创建时间戳(毫秒) */
private long mCreatedDate;
- /** 是否有附件:0表示无,1表示有(整型标记) */
private int mHasAttachment;
- /** 数据最后修改时间戳(毫秒) */
private long mModifiedDate;
- /** 父级ID:关联到文件夹的note ID(根文件夹为0) */
private long mParentId;
- /** 摘要/名称:笔记的内容摘要、文件夹的名称 */
private String mSnippet;
- /** 数据类型:{@link Notes#TYPE_NOTE}(笔记)、{TYPE_FOLDER}(文件夹)、{TYPE_SYSTEM}(系统文件夹) */
private int mType;
- /** 关联的小组件ID(无效时为{@link AppWidgetManager#INVALID_APPWIDGET_ID}) */
private int mWidgetId;
- /** 关联的小组件类型(无效时为{@link Notes#TYPE_WIDGET_INVALIDE}) */
private int mWidgetType;
- /** 原始父级ID:用于记录文件夹移动前的原始父级,支撑同步回滚 */
private long mOriginParent;
- /** 版本号:用于同步时的版本验证,防止并发修改冲突 */
private long mVersion;
- /** note表的差异数据容器,仅存储有变化的字段,用于提交到数据库 */
private ContentValues mDiffNoteValues;
- /** 关联的data表数据列表(存储笔记的具体内容,如文本、通话记录等) */
private ArrayList mDataList;
- // ====================== 构造方法 ======================
- /**
- * 构造方法:初始化新的SqlNote对象(用于创建新笔记/文件夹)
- * 初始化所有成员变量为默认值,设置为新数据状态
- *
- * @param context 上下文对象
- */
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = true;
mId = INVALID_ID;
mAlertDate = 0;
- mBgColorId = ResourceParser.getDefaultBgId(context); // 默认背景颜色
- mCreatedDate = System.currentTimeMillis(); // 当前时间为创建时间
+ mBgColorId = ResourceParser.getDefaultBgId(context);
+ mCreatedDate = System.currentTimeMillis();
mHasAttachment = 0;
- mModifiedDate = System.currentTimeMillis(); // 当前时间为修改时间
+ mModifiedDate = System.currentTimeMillis();
mParentId = 0;
mSnippet = "";
- mType = Notes.TYPE_NOTE; // 默认类型为普通笔记
- mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; // 无效小组件ID
- mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 无效小组件类型
+ mType = Notes.TYPE_NOTE;
+ mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
+ mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
mOriginParent = 0;
mVersion = 0;
- mDiffNoteValues = new ContentValues(); // 初始化差异容器
- mDataList = new ArrayList(); // 初始化data数据列表
+ mDiffNoteValues = new ContentValues();
+ mDataList = new ArrayList();
}
- /**
- * 构造方法:从Cursor中加载已有note表数据初始化SqlNote对象
- * 同时加载关联的data表数据(仅笔记类型)
- *
- * @param context 上下文对象
- * @param c 包含note表数据的Cursor对象(需使用PROJECTION_NOTE投影查询)
- */
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
- mIsCreate = false; // 标记为已有数据
- loadFromCursor(c); // 从Cursor加载note表数据
+ mIsCreate = false;
+ loadFromCursor(c);
mDataList = new ArrayList();
- if (mType == Notes.TYPE_NOTE) // 仅笔记类型加载关联的data表数据
+ if (mType == Notes.TYPE_NOTE)
loadDataContent();
- mDiffNoteValues = new ContentValues(); // 初始化差异容器
+ mDiffNoteValues = new ContentValues();
}
- /**
- * 构造方法:根据note表ID加载已有数据初始化SqlNote对象
- * 先通过ID查询获取Cursor,再加载数据,最后加载关联的data表数据(仅笔记类型)
- *
- * @param context 上下文对象
- * @param id note表的主键ID
- */
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
- mIsCreate = false; // 标记为已有数据
- loadFromCursor(id); // 根据ID加载note表数据
+ mIsCreate = false;
+ loadFromCursor(id);
mDataList = new ArrayList();
- if (mType == Notes.TYPE_NOTE) // 仅笔记类型加载关联的data表数据
+ if (mType == Notes.TYPE_NOTE)
loadDataContent();
- mDiffNoteValues = new ContentValues(); // 初始化差异容器
+ mDiffNoteValues = new ContentValues();
+
}
- // ====================== 私有辅助方法 ======================
- /**
- * 根据note表ID查询数据,获取Cursor并加载到成员变量
- * 自动关闭Cursor,防止资源泄漏
- *
- * @param id note表的主键ID
- */
private void loadFromCursor(long id) {
Cursor c = null;
try {
- // 查询note表:根据ID获取单条数据
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
- new String[] { String.valueOf(id) }, null);
+ new String[] {
+ String.valueOf(id)
+ }, null);
if (c != null) {
- c.moveToNext(); // 移动到第一条数据(唯一结果)
- loadFromCursor(c); // 加载数据到成员变量
+ c.moveToNext();
+ loadFromCursor(c);
} else {
Log.w(TAG, "loadFromCursor: cursor = null");
}
} finally {
- // 最终关闭Cursor,释放资源
if (c != null)
c.close();
}
}
- /**
- * 从Cursor中加载note表数据到成员变量
- * 需保证Cursor使用PROJECTION_NOTE投影查询,否则会出现列索引越界异常
- *
- * @param c 包含note表数据的Cursor对象
- */
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
@@ -275,23 +200,19 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN);
}
- /**
- * 加载当前note关联的data表数据,存入mDataList
- * 根据note ID查询data表,创建SqlData对象并添加到列表中
- */
private void loadDataContent() {
Cursor c = null;
- mDataList.clear(); // 清空原有数据
+ mDataList.clear();
try {
- // 查询data表:根据note ID获取关联的所有数据
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
- "(note_id=?)", new String[] { String.valueOf(mId) }, null);
+ "(note_id=?)", new String[] {
+ String.valueOf(mId)
+ }, null);
if (c != null) {
if (c.getCount() == 0) {
Log.w(TAG, "it seems that the note has not data");
return;
}
- // 遍历Cursor,创建SqlData对象并添加到列表
while (c.moveToNext()) {
SqlData data = new SqlData(mContext, c);
mDataList.add(data);
@@ -300,154 +221,137 @@ public class SqlNote {
Log.w(TAG, "loadDataContent: cursor = null");
}
} finally {
- // 最终关闭Cursor,释放资源
if (c != null)
c.close();
}
}
- // ====================== 公共核心方法 ======================
- /**
- * 根据JSON对象设置笔记/文件夹内容,并记录数据差异到差异容器
- * 区分系统文件夹、普通文件夹、笔记类型做差异化处理:
- * - 系统文件夹:不允许修改,仅输出警告
- * - 普通文件夹:仅更新名称和类型
- * - 笔记:更新所有字段,并处理关联的data表数据
- *
- * @param js 包含笔记/文件夹数据的JSON对象
- * @return true表示设置成功,false表示JSON解析失败
- */
public boolean setContent(JSONObject js) {
try {
- // 获取JSON中的note核心数据(GTask约定的字段名)
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
-
- // 系统文件夹:不允许修改,输出警告
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
Log.w(TAG, "cannot set system folder");
- }
- // 普通文件夹:仅更新名称和类型
- else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
- // 更新摘要/名称
- String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
+ } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
+ // for folder we can only update the snnipet and type
+ String snippet = note.has(NoteColumns.SNIPPET) ? note
+ .getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
mSnippet = snippet;
- // 更新类型
- int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
+ int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
+ : Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
- }
- // 普通笔记:更新所有字段,并处理关联的data表数据
- else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
- // 获取JSON中的data数组(笔记的具体内容)
+ } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
-
- // 1. 处理note表的各个字段,记录差异
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id);
}
mId = id;
- long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note.getLong(NoteColumns.ALERTED_DATE) : 0;
+ long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
+ .getLong(NoteColumns.ALERTED_DATE) : 0;
if (mIsCreate || mAlertDate != alertDate) {
mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
}
mAlertDate = alertDate;
- int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
+ int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note
+ .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
if (mIsCreate || mBgColorId != bgColorId) {
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
}
mBgColorId = bgColorId;
- long createDate = note.has(NoteColumns.CREATED_DATE) ? note.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
+ long createDate = note.has(NoteColumns.CREATED_DATE) ? note
+ .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
if (mIsCreate || mCreatedDate != createDate) {
mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
}
mCreatedDate = createDate;
- int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note.getInt(NoteColumns.HAS_ATTACHMENT) : 0;
+ int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
+ .getInt(NoteColumns.HAS_ATTACHMENT) : 0;
if (mIsCreate || mHasAttachment != hasAttachment) {
mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
}
mHasAttachment = hasAttachment;
- long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
+ long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
+ .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
if (mIsCreate || mModifiedDate != modifiedDate) {
mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
}
mModifiedDate = modifiedDate;
- long parentId = note.has(NoteColumns.PARENT_ID) ? note.getLong(NoteColumns.PARENT_ID) : 0;
+ long parentId = note.has(NoteColumns.PARENT_ID) ? note
+ .getLong(NoteColumns.PARENT_ID) : 0;
if (mIsCreate || mParentId != parentId) {
mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
}
mParentId = parentId;
- String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
+ String snippet = note.has(NoteColumns.SNIPPET) ? note
+ .getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
mSnippet = snippet;
- int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
+ int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
+ : Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
- int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) : AppWidgetManager.INVALID_APPWIDGET_ID;
+ int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
+ : AppWidgetManager.INVALID_APPWIDGET_ID;
if (mIsCreate || mWidgetId != widgetId) {
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
}
mWidgetId = widgetId;
- int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
+ int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
+ .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
if (mIsCreate || mWidgetType != widgetType) {
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
}
mWidgetType = widgetType;
- long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
+ long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
+ .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
if (mIsCreate || mOriginParent != originParent) {
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
}
mOriginParent = originParent;
- // 2. 处理关联的data表数据
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null;
-
- // 根据data ID查找已有SqlData对象(更新场景)
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
for (SqlData temp : mDataList) {
if (dataId == temp.getId()) {
sqlData = temp;
- break;
}
}
}
- // 未找到则创建新SqlData对象(新增场景)
if (sqlData == null) {
sqlData = new SqlData(mContext);
mDataList.add(sqlData);
}
- // 设置data内容并记录差异
sqlData.setContent(data);
}
}
} catch (JSONException e) {
- // JSON解析失败,输出错误日志并返回false
Log.e(TAG, e.toString());
e.printStackTrace();
return false;
@@ -455,26 +359,16 @@ public class SqlNote {
return true;
}
- /**
- * 将笔记/文件夹数据及关联的data表数据序列化为JSON对象
- * 区分笔记、文件夹、系统文件夹做差异化序列化:
- * - 笔记:序列化所有note字段 + 关联的data数组
- * - 文件夹/系统文件夹:仅序列化核心字段(ID、类型、名称)
- *
- * @return 包含完整数据的JSON对象,若为新数据则返回null
- */
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
- // 新数据尚未持久化,输出错误日志并返回null
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
}
JSONObject note = new JSONObject();
- // 普通笔记:序列化所有字段 + 关联的data数组
if (mType == Notes.TYPE_NOTE) {
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate);
@@ -490,7 +384,6 @@ public class SqlNote {
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
- // 序列化关联的data表数据为JSON数组
JSONArray dataArray = new JSONArray();
for (SqlData sqlData : mDataList) {
JSONObject data = sqlData.getContent();
@@ -499,9 +392,7 @@ public class SqlNote {
}
}
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
- }
- // 文件夹/系统文件夹:仅序列化核心字段
- else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
+ } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.SNIPPET, mSnippet);
@@ -510,145 +401,92 @@ public class SqlNote {
return js;
} catch (JSONException e) {
- // JSON序列化失败,输出错误日志
Log.e(TAG, e.toString());
e.printStackTrace();
}
return null;
}
- // ====================== 字段设置方法(记录差异) ======================
- /**
- * 设置父级ID,并记录到差异容器
- * @param id 新的父级ID(文件夹的note ID)
- */
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
}
- /**
- * 设置GTask ID,并记录到差异容器
- * @param gid GTask的唯一标识ID
- */
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
- /**
- * 设置同步ID,并记录到差异容器
- * @param syncId 同步ID(用于标记同步状态)
- */
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
- /**
- * 重置本地修改标记为0,并记录到差异容器
- * 用于同步完成后标记数据已同步,无本地修改
- */
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}
- // ====================== 字段获取方法 ======================
- /**
- * 获取note表的主键ID
- * @return 主键ID,未初始化则返回INVALID_ID
- */
public long getId() {
return mId;
}
- /**
- * 获取父级ID
- * @return 父级文件夹的note ID
- */
public long getParentId() {
return mParentId;
}
- /**
- * 获取摘要/名称
- * @return 笔记摘要或文件夹名称
- */
public String getSnippet() {
return mSnippet;
}
- /**
- * 判断当前数据是否为笔记类型
- * @return true表示是笔记(TYPE_NOTE),false表示否
- */
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}
- /**
- * 提交数据变更到数据库(插入/更新),并联动处理关联的data表数据
- * 支持版本验证机制,保证同步过程中数据的一致性,提交后刷新本地数据。
- *
- * @param validateVersion 是否开启版本验证:true表示验证,false表示不验证
- */
public void commit(boolean validateVersion) {
- // 新数据:执行插入操作
if (mIsCreate) {
- // 若ID为无效值且差异容器中包含ID,移除该ID(数据库自增ID,无需手动设置)
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID);
}
- // 插入note表数据,获取返回的Uri(包含新数据的ID)
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
try {
- // 从Uri中解析出新数据的ID(Uri路径分段的第二个元素,如note/123中的123)
mId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
- // 解析ID失败,输出错误日志并抛出同步失败异常
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
}
- // ID为0表示创建失败,抛出异常
if (mId == 0) {
throw new IllegalStateException("Create thread id failed");
}
- // 笔记类型:联动提交关联的data表数据
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
- sqlData.commit(mId, false, -1); // 无需版本验证
+ sqlData.commit(mId, false, -1);
}
}
- }
- // 已有数据:执行更新操作
- else {
- // 验证ID有效性(排除系统文件夹的有效ID)
+ } else {
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id");
}
-
- // 仅当存在差异时执行更新操作
if (mDiffNoteValues.size() > 0) {
- mVersion ++; // 版本号自增
+ mVersion ++;
int result = 0;
if (!validateVersion) {
- // 不验证版本:直接更新数据(根据note ID)
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
- + NoteColumns.ID + "=?)", new String[] { String.valueOf(mId) });
+ + NoteColumns.ID + "=?)", new String[] {
+ String.valueOf(mId)
+ });
} else {
- // 验证版本:仅当note表的版本号小于等于当前版本时才更新
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
- + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
- new String[] { String.valueOf(mId), String.valueOf(mVersion) });
+ + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
+ new String[] {
+ String.valueOf(mId), String.valueOf(mVersion)
+ });
}
- // 更新结果为0,说明数据未更新(可能同步时用户修改了数据),输出警告日志
if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing");
}
}
- // 笔记类型:联动提交关联的data表数据(支持版本验证)
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion);
@@ -656,13 +494,12 @@ public class SqlNote {
}
}
- // 提交后刷新本地数据:重新加载note和关联的data表数据
+ // refresh local info
loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE)
loadDataContent();
- // 清空差异容器,标记为已有数据
mDiffNoteValues.clear();
mIsCreate = false;
}
-}
\ No newline at end of file
+}
diff --git a/java/net/micode/notes/gtask/data/Task.java b/java/net/micode/notes/gtask/data/Task.java
new file mode 100644
index 0000000..6a19454
--- /dev/null
+++ b/java/net/micode/notes/gtask/data/Task.java
@@ -0,0 +1,351 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.gtask.data;
+
+import android.database.Cursor;
+import android.text.TextUtils;
+import android.util.Log;
+
+import net.micode.notes.data.Notes;
+import net.micode.notes.data.Notes.DataColumns;
+import net.micode.notes.data.Notes.DataConstants;
+import net.micode.notes.data.Notes.NoteColumns;
+import net.micode.notes.gtask.exception.ActionFailureException;
+import net.micode.notes.tool.GTaskStringUtils;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+
+public class Task extends Node {
+ private static final String TAG = Task.class.getSimpleName();
+
+ private boolean mCompleted;
+
+ private String mNotes;
+
+ private JSONObject mMetaInfo;
+
+ private Task mPriorSibling;
+
+ private TaskList mParent;
+
+ public Task() {
+ super();
+ mCompleted = false;
+ mNotes = null;
+ mPriorSibling = null;
+ mParent = null;
+ mMetaInfo = null;
+ }
+
+ public JSONObject getCreateAction(int actionId) {
+ JSONObject js = new JSONObject();
+
+ try {
+ // action_type
+ js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
+ GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
+
+ // action_id
+ js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
+
+ // index
+ js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
+
+ // entity_delta
+ JSONObject entity = new JSONObject();
+ entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
+ entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
+ entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
+ GTaskStringUtils.GTASK_JSON_TYPE_TASK);
+ if (getNotes() != null) {
+ entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
+ }
+ js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
+
+ // parent_id
+ js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
+
+ // dest_parent_type
+ js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
+ GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
+
+ // list_id
+ js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
+
+ // prior_sibling_id
+ if (mPriorSibling != null) {
+ js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
+ }
+
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("fail to generate task-create jsonobject");
+ }
+
+ return js;
+ }
+
+ public JSONObject getUpdateAction(int actionId) {
+ JSONObject js = new JSONObject();
+
+ try {
+ // action_type
+ js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
+ GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
+
+ // action_id
+ js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
+
+ // id
+ js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
+
+ // entity_delta
+ JSONObject entity = new JSONObject();
+ entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
+ if (getNotes() != null) {
+ entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
+ }
+ entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
+ js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
+
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("fail to generate task-update jsonobject");
+ }
+
+ return js;
+ }
+
+ public void setContentByRemoteJSON(JSONObject js) {
+ if (js != null) {
+ try {
+ // id
+ if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
+ setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
+ }
+
+ // last_modified
+ if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
+ setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
+ }
+
+ // name
+ if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
+ setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
+ }
+
+ // notes
+ if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
+ setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
+ }
+
+ // deleted
+ if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
+ setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
+ }
+
+ // completed
+ if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
+ setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
+ }
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("fail to get task content from jsonobject");
+ }
+ }
+ }
+
+ public void setContentByLocalJSON(JSONObject js) {
+ if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
+ || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
+ Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
+ }
+
+ try {
+ JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
+ JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
+
+ if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
+ Log.e(TAG, "invalid type");
+ return;
+ }
+
+ for (int i = 0; i < dataArray.length(); i++) {
+ JSONObject data = dataArray.getJSONObject(i);
+ if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
+ setName(data.getString(DataColumns.CONTENT));
+ break;
+ }
+ }
+
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ }
+ }
+
+ public JSONObject getLocalJSONFromContent() {
+ String name = getName();
+ try {
+ if (mMetaInfo == null) {
+ // new task created from web
+ if (name == null) {
+ Log.w(TAG, "the note seems to be an empty one");
+ return null;
+ }
+
+ JSONObject js = new JSONObject();
+ JSONObject note = new JSONObject();
+ JSONArray dataArray = new JSONArray();
+ JSONObject data = new JSONObject();
+ data.put(DataColumns.CONTENT, name);
+ dataArray.put(data);
+ js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
+ note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
+ js.put(GTaskStringUtils.META_HEAD_NOTE, note);
+ return js;
+ } else {
+ // synced task
+ JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
+ JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
+
+ for (int i = 0; i < dataArray.length(); i++) {
+ JSONObject data = dataArray.getJSONObject(i);
+ if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
+ data.put(DataColumns.CONTENT, getName());
+ break;
+ }
+ }
+
+ note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
+ return mMetaInfo;
+ }
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ public void setMetaInfo(MetaData metaData) {
+ if (metaData != null && metaData.getNotes() != null) {
+ try {
+ mMetaInfo = new JSONObject(metaData.getNotes());
+ } catch (JSONException e) {
+ Log.w(TAG, e.toString());
+ mMetaInfo = null;
+ }
+ }
+ }
+
+ public int getSyncAction(Cursor c) {
+ try {
+ JSONObject noteInfo = null;
+ if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
+ noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
+ }
+
+ if (noteInfo == null) {
+ Log.w(TAG, "it seems that note meta has been deleted");
+ return SYNC_ACTION_UPDATE_REMOTE;
+ }
+
+ if (!noteInfo.has(NoteColumns.ID)) {
+ Log.w(TAG, "remote note id seems to be deleted");
+ return SYNC_ACTION_UPDATE_LOCAL;
+ }
+
+ // validate the note id now
+ if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
+ Log.w(TAG, "note id doesn't match");
+ return SYNC_ACTION_UPDATE_LOCAL;
+ }
+
+ if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
+ // there is no local update
+ if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
+ // no update both side
+ return SYNC_ACTION_NONE;
+ } else {
+ // apply remote to local
+ return SYNC_ACTION_UPDATE_LOCAL;
+ }
+ } else {
+ // validate gtask id
+ if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
+ Log.e(TAG, "gtask id doesn't match");
+ return SYNC_ACTION_ERROR;
+ }
+ if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
+ // local modification only
+ return SYNC_ACTION_UPDATE_REMOTE;
+ } else {
+ return SYNC_ACTION_UPDATE_CONFLICT;
+ }
+ }
+ } catch (Exception e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ }
+
+ return SYNC_ACTION_ERROR;
+ }
+
+ public boolean isWorthSaving() {
+ return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
+ || (getNotes() != null && getNotes().trim().length() > 0);
+ }
+
+ public void setCompleted(boolean completed) {
+ this.mCompleted = completed;
+ }
+
+ public void setNotes(String notes) {
+ this.mNotes = notes;
+ }
+
+ public void setPriorSibling(Task priorSibling) {
+ this.mPriorSibling = priorSibling;
+ }
+
+ public void setParent(TaskList parent) {
+ this.mParent = parent;
+ }
+
+ public boolean getCompleted() {
+ return this.mCompleted;
+ }
+
+ public String getNotes() {
+ return this.mNotes;
+ }
+
+ public Task getPriorSibling() {
+ return this.mPriorSibling;
+ }
+
+ public TaskList getParent() {
+ return this.mParent;
+ }
+
+}
diff --git a/java/net/micode/notes/gtask/data/TaskList.java b/java/net/micode/notes/gtask/data/TaskList.java
new file mode 100644
index 0000000..4ea21c5
--- /dev/null
+++ b/java/net/micode/notes/gtask/data/TaskList.java
@@ -0,0 +1,343 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.gtask.data;
+
+import android.database.Cursor;
+import android.util.Log;
+
+import net.micode.notes.data.Notes;
+import net.micode.notes.data.Notes.NoteColumns;
+import net.micode.notes.gtask.exception.ActionFailureException;
+import net.micode.notes.tool.GTaskStringUtils;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.ArrayList;
+
+
+public class TaskList extends Node {
+ private static final String TAG = TaskList.class.getSimpleName();
+
+ private int mIndex;
+
+ private ArrayList mChildren;
+
+ public TaskList() {
+ super();
+ mChildren = new ArrayList();
+ mIndex = 1;
+ }
+
+ public JSONObject getCreateAction(int actionId) {
+ JSONObject js = new JSONObject();
+
+ try {
+ // action_type
+ js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
+ GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
+
+ // action_id
+ js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
+
+ // index
+ js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
+
+ // entity_delta
+ JSONObject entity = new JSONObject();
+ entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
+ entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
+ entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
+ GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
+ js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
+
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("fail to generate tasklist-create jsonobject");
+ }
+
+ return js;
+ }
+
+ public JSONObject getUpdateAction(int actionId) {
+ JSONObject js = new JSONObject();
+
+ try {
+ // action_type
+ js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
+ GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
+
+ // action_id
+ js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
+
+ // id
+ js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
+
+ // entity_delta
+ JSONObject entity = new JSONObject();
+ entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
+ entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
+ js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
+
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("fail to generate tasklist-update jsonobject");
+ }
+
+ return js;
+ }
+
+ public void setContentByRemoteJSON(JSONObject js) {
+ if (js != null) {
+ try {
+ // id
+ if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
+ setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
+ }
+
+ // last_modified
+ if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
+ setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
+ }
+
+ // name
+ if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
+ setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
+ }
+
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ throw new ActionFailureException("fail to get tasklist content from jsonobject");
+ }
+ }
+ }
+
+ public void setContentByLocalJSON(JSONObject js) {
+ if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
+ Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
+ }
+
+ try {
+ JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
+
+ if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
+ String name = folder.getString(NoteColumns.SNIPPET);
+ setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
+ } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
+ if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
+ setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
+ else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
+ setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ + GTaskStringUtils.FOLDER_CALL_NOTE);
+ else
+ Log.e(TAG, "invalid system folder");
+ } else {
+ Log.e(TAG, "error type");
+ }
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ }
+ }
+
+ public JSONObject getLocalJSONFromContent() {
+ try {
+ JSONObject js = new JSONObject();
+ JSONObject folder = new JSONObject();
+
+ String folderName = getName();
+ if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
+ folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
+ folderName.length());
+ folder.put(NoteColumns.SNIPPET, folderName);
+ if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
+ || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
+ folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
+ else
+ folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
+
+ js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
+
+ return js;
+ } catch (JSONException e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ public int getSyncAction(Cursor c) {
+ try {
+ if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
+ // there is no local update
+ if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
+ // no update both side
+ return SYNC_ACTION_NONE;
+ } else {
+ // apply remote to local
+ return SYNC_ACTION_UPDATE_LOCAL;
+ }
+ } else {
+ // validate gtask id
+ if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
+ Log.e(TAG, "gtask id doesn't match");
+ return SYNC_ACTION_ERROR;
+ }
+ if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
+ // local modification only
+ return SYNC_ACTION_UPDATE_REMOTE;
+ } else {
+ // for folder conflicts, just apply local modification
+ return SYNC_ACTION_UPDATE_REMOTE;
+ }
+ }
+ } catch (Exception e) {
+ Log.e(TAG, e.toString());
+ e.printStackTrace();
+ }
+
+ return SYNC_ACTION_ERROR;
+ }
+
+ public int getChildTaskCount() {
+ return mChildren.size();
+ }
+
+ public boolean addChildTask(Task task) {
+ boolean ret = false;
+ if (task != null && !mChildren.contains(task)) {
+ ret = mChildren.add(task);
+ if (ret) {
+ // need to set prior sibling and parent
+ task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
+ .get(mChildren.size() - 1));
+ task.setParent(this);
+ }
+ }
+ return ret;
+ }
+
+ public boolean addChildTask(Task task, int index) {
+ if (index < 0 || index > mChildren.size()) {
+ Log.e(TAG, "add child task: invalid index");
+ return false;
+ }
+
+ int pos = mChildren.indexOf(task);
+ if (task != null && pos == -1) {
+ mChildren.add(index, task);
+
+ // update the task list
+ Task preTask = null;
+ Task afterTask = null;
+ if (index != 0)
+ preTask = mChildren.get(index - 1);
+ if (index != mChildren.size() - 1)
+ afterTask = mChildren.get(index + 1);
+
+ task.setPriorSibling(preTask);
+ if (afterTask != null)
+ afterTask.setPriorSibling(task);
+ }
+
+ return true;
+ }
+
+ public boolean removeChildTask(Task task) {
+ boolean ret = false;
+ int index = mChildren.indexOf(task);
+ if (index != -1) {
+ ret = mChildren.remove(task);
+
+ if (ret) {
+ // reset prior sibling and parent
+ task.setPriorSibling(null);
+ task.setParent(null);
+
+ // update the task list
+ if (index != mChildren.size()) {
+ mChildren.get(index).setPriorSibling(
+ index == 0 ? null : mChildren.get(index - 1));
+ }
+ }
+ }
+ return ret;
+ }
+
+ public boolean moveChildTask(Task task, int index) {
+
+ if (index < 0 || index >= mChildren.size()) {
+ Log.e(TAG, "move child task: invalid index");
+ return false;
+ }
+
+ int pos = mChildren.indexOf(task);
+ if (pos == -1) {
+ Log.e(TAG, "move child task: the task should in the list");
+ return false;
+ }
+
+ if (pos == index)
+ return true;
+ return (removeChildTask(task) && addChildTask(task, index));
+ }
+
+ public Task findChildTaskByGid(String gid) {
+ for (int i = 0; i < mChildren.size(); i++) {
+ Task t = mChildren.get(i);
+ if (t.getGid().equals(gid)) {
+ return t;
+ }
+ }
+ return null;
+ }
+
+ public int getChildTaskIndex(Task task) {
+ return mChildren.indexOf(task);
+ }
+
+ public Task getChildTaskByIndex(int index) {
+ if (index < 0 || index >= mChildren.size()) {
+ Log.e(TAG, "getTaskByIndex: invalid index");
+ return null;
+ }
+ return mChildren.get(index);
+ }
+
+ public Task getChilTaskByGid(String gid) {
+ for (Task task : mChildren) {
+ if (task.getGid().equals(gid))
+ return task;
+ }
+ return null;
+ }
+
+ public ArrayList getChildTaskList() {
+ return this.mChildren;
+ }
+
+ public void setIndex(int index) {
+ this.mIndex = index;
+ }
+
+ public int getIndex() {
+ return this.mIndex;
+ }
+}
diff --git a/java/net/micode/notes/gtask/exception/ActionFailureException.java b/java/net/micode/notes/gtask/exception/ActionFailureException.java
new file mode 100644
index 0000000..15504be
--- /dev/null
+++ b/java/net/micode/notes/gtask/exception/ActionFailureException.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.gtask.exception;
+
+public class ActionFailureException extends RuntimeException {
+ private static final long serialVersionUID = 4425249765923293627L;
+
+ public ActionFailureException() {
+ super();
+ }
+
+ public ActionFailureException(String paramString) {
+ super(paramString);
+ }
+
+ public ActionFailureException(String paramString, Throwable paramThrowable) {
+ super(paramString, paramThrowable);
+ }
+}
diff --git a/java/net/micode/notes/gtask/exception/NetworkFailureException.java b/java/net/micode/notes/gtask/exception/NetworkFailureException.java
new file mode 100644
index 0000000..b08cfb1
--- /dev/null
+++ b/java/net/micode/notes/gtask/exception/NetworkFailureException.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.gtask.exception;
+
+public class NetworkFailureException extends Exception {
+ private static final long serialVersionUID = 2107610287180234136L;
+
+ public NetworkFailureException() {
+ super();
+ }
+
+ public NetworkFailureException(String paramString) {
+ super(paramString);
+ }
+
+ public NetworkFailureException(String paramString, Throwable paramThrowable) {
+ super(paramString, paramThrowable);
+ }
+}
diff --git a/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/java/net/micode/notes/gtask/remote/GTaskASyncTask.java
new file mode 100644
index 0000000..4dd3b98
--- /dev/null
+++ b/java/net/micode/notes/gtask/remote/GTaskASyncTask.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.gtask.remote;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.os.AsyncTask;
+import android.os.Build;
+
+import androidx.core.app.NotificationCompat;
+
+import net.micode.notes.R;
+import net.micode.notes.ui.NotesListActivity;
+import net.micode.notes.ui.NotesPreferenceActivity;
+
+
+public class GTaskASyncTask extends AsyncTask {
+
+ private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
+ private static final String CHANNEL_ID = "gtask_sync_channel"; // 新增通知渠道ID
+
+ public interface OnCompleteListener {
+ void onComplete();
+ }
+
+ private Context mContext;
+
+ private NotificationManager mNotifiManager;
+
+ private GTaskManager mTaskManager;
+
+ private OnCompleteListener mOnCompleteListener;
+
+ public GTaskASyncTask(Context context, OnCompleteListener listener) {
+ mContext = context;
+ mOnCompleteListener = listener;
+ mNotifiManager = (NotificationManager) mContext
+ .getSystemService(Context.NOTIFICATION_SERVICE);
+ mTaskManager = GTaskManager.getInstance();
+ // 初始化通知渠道(仅Android 8.0+需要)
+ createNotificationChannel();
+ }
+
+ // 新增:创建通知渠道
+ private void createNotificationChannel() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ CharSequence name = mContext.getString(R.string.app_name); // 渠道名称
+ String description = "GTask同步通知"; // 渠道描述
+ int importance = NotificationManager.IMPORTANCE_DEFAULT;
+ NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
+ channel.setDescription(description);
+ // 向系统注册渠道
+ if (mNotifiManager != null) {
+ mNotifiManager.createNotificationChannel(channel);
+ }
+ }
+ }
+
+ public void cancelSync() {
+ mTaskManager.cancelSync();
+ }
+
+ public void publishProgess(String message) {
+ publishProgress(new String[] {
+ message
+ });
+ }
+
+ private void showNotification(int tickerId, String content) {
+ // 替换为NotificationCompat.Builder构建通知
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, CHANNEL_ID)
+ .setSmallIcon(R.drawable.notification) // 保持原图标
+ .setContentTitle(mContext.getString(R.string.app_name)) // 原标题
+ .setContentText(content) // 原内容
+ .setTicker(mContext.getString(tickerId)) // 原滚动提示文字
+ .setWhen(System.currentTimeMillis()) // 原时间戳
+ .setDefaults(Notification.DEFAULT_LIGHTS) // 保持原灯光效果
+ .setAutoCancel(true); // 保持点击自动取消
+
+ // 设置跳转意图(保持原逻辑)
+ PendingIntent pendingIntent;
+ if (tickerId != R.string.ticker_success) {
+ pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
+ NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE); // 适配高版本
+ } else {
+ pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
+ NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE); // 适配高版本
+ }
+ builder.setContentIntent(pendingIntent);
+
+ // 发送通知(保持原ID)
+ mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, builder.build());
+ }
+
+ @Override
+ protected Integer doInBackground(Void... unused) {
+ publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
+ .getSyncAccountName(mContext)));
+ return mTaskManager.sync(mContext, this);
+ }
+
+ @Override
+ protected void onProgressUpdate(String... progress) {
+ showNotification(R.string.ticker_syncing, progress[0]);
+ if (mContext instanceof GTaskSyncService) {
+ ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
+ }
+ }
+
+ @Override
+ protected void onPostExecute(Integer result) {
+ if (result == GTaskManager.STATE_SUCCESS) {
+ showNotification(R.string.ticker_success, mContext.getString(
+ R.string.success_sync_account, mTaskManager.getSyncAccount()));
+ NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
+ } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
+ showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
+ } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
+ showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
+ } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
+ showNotification(R.string.ticker_cancel, mContext
+ .getString(R.string.error_sync_cancelled));
+ }
+ if (mOnCompleteListener != null) {
+ new Thread(new Runnable() {
+
+ public void run() {
+ mOnCompleteListener.onComplete();
+ }
+ }).start();
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/notes/gtask/remote/GTaskClient.java b/java/net/micode/notes/gtask/remote/GTaskClient.java
similarity index 52%
rename from src/notes/gtask/remote/GTaskClient.java
rename to java/net/micode/notes/gtask/remote/GTaskClient.java
index fc25081..c67dfdf 100644
--- a/src/notes/gtask/remote/GTaskClient.java
+++ b/java/net/micode/notes/gtask/remote/GTaskClient.java
@@ -60,117 +60,48 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
-/**
- * GTask客户端核心类,采用**单例模式**实现,负责与Google Tasks(GTask)服务进行底层网络交互
- * 该类是GTask同步功能的核心通信层,主要完成以下职责:
- * 1. Google账户认证:获取Google账户的AuthToken,处理账户切换、Token失效重取逻辑;
- * 2. GTask服务登录:通过AuthToken登录GTask服务,获取认证Cookie和客户端版本号(client_version);
- * 3. HTTP请求处理:封装GET/POST请求,处理Gzip/Deflate压缩的响应数据,解析JSON结果;
- * 4. GTask核心操作:实现任务(Task)/任务列表(TaskList)的创建、更新、删除、移动,以及列表数据的获取;
- * 5. 批量更新优化:维护更新动作数组,限制单次批量更新的最大数量(10条),减少网络请求次数。
- *
- * 注意:该类依赖Apache HttpClient(已被Android高版本弃用,但保留原有逻辑),
- * 所有网络操作会抛出{@link NetworkFailureException}(网络异常)或{@link ActionFailureException}(业务逻辑异常)。
- *
- * @author MiCode Open Source Community
- * @date 2010-2011
- */
+
public class GTaskClient {
- /**
- * 日志标签,使用类的简单名称,便于调试时定位日志来源
- */
private static final String TAG = GTaskClient.class.getSimpleName();
- // ====================== GTask服务URL常量 ======================
- /**
- * GTask服务基础URL
- */
private static final String GTASK_URL = "https://mail.google.com/tasks/";
- /**
- * GTask服务GET请求URL(用于登录、获取任务列表元数据)
- */
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
- /**
- * GTask服务POST请求URL(用于执行创建、更新、移动、删除等操作)
- */
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
- // ====================== 单例模式相关 ======================
- /**
- * GTaskClient单例实例,通过{@link #getInstance()}获取
- */
private static GTaskClient mInstance = null;
- // ====================== 网络请求相关成员变量 ======================
- /**
- * Apache HttpClient实例,用于发送HTTP请求、管理Cookie
- */
private DefaultHttpClient mHttpClient;
- /**
- * 动态的GTask GET请求URL(适配自定义域名账户,如企业邮箱)
- */
private String mGetUrl;
- /**
- * 动态的GTask POST请求URL(适配自定义域名账户)
- */
private String mPostUrl;
- // ====================== GTask服务认证/版本相关 ======================
- /**
- * GTask客户端版本号(从GTask服务返回的JSON中解析,用于请求标识)
- */
private long mClientVersion;
- /**
- * 登录状态标记:true表示已成功登录GTask服务,false表示未登录/需要重新登录
- */
private boolean mLoggedin;
- /**
- * 最后一次登录时间戳(用于判断是否需要重新登录,默认5分钟有效期)
- */
private long mLastLoginTime;
- /**
- * 动作ID:自增的唯一标识,用于标记每个GTask操作的动作(创建、更新等)
- */
private int mActionId;
- /**
- * 当前同步的Google账户实例(存储账户名称、类型等信息)
- */
private Account mAccount;
- // ====================== 批量更新相关 ======================
- /**
- * 更新动作数组:存储待提交的更新动作(Task/TaskList的updateAction),用于批量提交
- */
private JSONArray mUpdateArray;
- /**
- * 私有构造方法:初始化GTaskClient的默认属性(单例模式禁止外部实例化)
- * 初始化URL、状态标记、计数器等为默认值,确保单例的唯一性
- */
private GTaskClient() {
mHttpClient = null;
- mGetUrl = GTASK_GET_URL; // 默认使用官方GET URL
- mPostUrl = GTASK_POST_URL; // 默认使用官方POST URL
- mClientVersion = -1; // 初始化为无效版本号
- mLoggedin = false; // 初始未登录
- mLastLoginTime = 0; // 初始无登录时间
- mActionId = 1; // 动作ID从1开始自增
- mAccount = null; // 初始无账户
- mUpdateArray = null; // 初始无批量更新动作
+ mGetUrl = GTASK_GET_URL;
+ mPostUrl = GTASK_POST_URL;
+ mClientVersion = -1;
+ mLoggedin = false;
+ mLastLoginTime = 0;
+ mActionId = 1;
+ mAccount = null;
+ mUpdateArray = null;
}
- /**
- * 获取GTaskClient的单例实例(线程安全的同步方法)
- * @return GTaskClient唯一实例
- */
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@@ -178,59 +109,49 @@ public class GTaskClient {
return mInstance;
}
- /**
- * 执行GTask服务的登录流程(核心登录方法)
- * 登录逻辑分为三步:
- * 1. 检查登录状态:若5分钟内已登录且账户未切换,直接返回成功;
- * 2. 获取Google账户的AuthToken:通过AccountManager获取当前同步账户的认证Token;
- * 3. 登录GTask服务:先尝试自定义域名URL(非Gmail账户),失败则使用官方URL;
- * @param activity 上下文Activity(用于AccountManager获取Token、处理账户授权)
- * @return true表示登录成功,false表示登录失败
- */
public boolean login(Activity activity) {
- // 步骤1:判断登录有效期(5分钟),超时则标记为未登录
- final long interval = 1000 * 60 * 5; // 5分钟毫秒数
+ // we suppose that the cookie would expire after 5 minutes
+ // then we need to re-login
+ final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
- // 步骤2:判断账户是否切换,切换则标记为未登录
- if (mLoggedin && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity.getSyncAccountName(activity))) {
+ // need to re-login after account switch
+ if (mLoggedin
+ && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
+ .getSyncAccountName(activity))) {
mLoggedin = false;
}
- // 步骤3:已登录则直接返回成功
if (mLoggedin) {
Log.d(TAG, "already logged in");
return true;
}
- // 步骤4:记录本次登录时间,开始新的登录流程
mLastLoginTime = System.currentTimeMillis();
- // 获取Google账户的AuthToken
String authToken = loginGoogleAccount(activity, false);
if (authToken == null) {
Log.e(TAG, "login google account failed");
return false;
}
- // 步骤5:处理非Gmail/GoogleMail账户(自定义域名,如企业邮箱)
- if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase().endsWith("googlemail.com"))) {
- // 构建自定义域名的GTask URL
+ // login with custom domain if necessary
+ if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
+ .endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
- int index = mAccount.name.indexOf('@') + 1; // 截取@后的域名部分
+ int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index);
url.append(suffix + "/");
- mGetUrl = url.toString() + "ig"; // 自定义GET URL
- mPostUrl = url.toString() + "r/ig"; // 自定义POST URL
+ mGetUrl = url.toString() + "ig";
+ mPostUrl = url.toString() + "r/ig";
- // 尝试使用自定义URL登录GTask
if (tryToLoginGtask(activity, authToken)) {
mLoggedin = true;
}
}
- // 步骤6:自定义URL登录失败/是Gmail账户,使用官方URL登录
+ // try to login with google official url
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
@@ -239,47 +160,28 @@ public class GTaskClient {
}
}
- // 登录成功,标记状态
mLoggedin = true;
return true;
}
- /**
- * 登录Google账户并获取AuthToken(底层账户认证方法)
- * 流程:
- * 1. 获取设备上的所有Google账户;
- * 2. 匹配设置中的同步账户名称;
- * 3. 通过AccountManager获取该账户的AuthToken(类型为goanna_mobile);
- * 4. 若传入invalidateToken为true,失效旧Token并重新获取;
- * @param activity 上下文Activity
- * @param invalidateToken 是否失效旧的AuthToken(用于Token过期时重取)
- * @return Google账户的AuthToken,获取失败则返回null
- */
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
- // 获取AccountManager服务
AccountManager accountManager = AccountManager.get(activity);
- // 获取所有Google类型的账户(type为com.google)
Account[] accounts = accountManager.getAccountsByType("com.google");
- // 无Google账户,返回null
if (accounts.length == 0) {
Log.e(TAG, "there is no available google account");
return null;
}
- // 获取设置中的同步账户名称
String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null;
- // 匹配账户名称
for (Account a : accounts) {
if (a.name.equals(accountName)) {
account = a;
break;
}
}
-
- // 匹配成功,存储账户实例
if (account != null) {
mAccount = account;
} else {
@@ -287,24 +189,15 @@ public class GTaskClient {
return null;
}
- // 获取AuthToken
- AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(
- account,
- "goanna_mobile", // GTask服务的Token类型
- null,
- activity,
- null,
- null
- );
-
+ // get the token now
+ AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account,
+ "goanna_mobile", null, activity, null, null);
try {
- // 获取Token结果
Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
- // 失效旧Token并重新获取(递归调用)
if (invalidateToken) {
accountManager.invalidateAuthToken("com.google", authToken);
- authToken = loginGoogleAccount(activity, false);
+ loginGoogleAccount(activity, false);
}
} catch (Exception e) {
Log.e(TAG, "get auth token failed");
@@ -314,26 +207,16 @@ public class GTaskClient {
return authToken;
}
- /**
- * 尝试登录GTask服务(处理Token失效重取逻辑)
- * 流程:
- * 1. 使用传入的AuthToken登录GTask;
- * 2. 若登录失败,失效旧Token并重新获取,再次尝试登录;
- * 3. 两次失败则返回false,否则返回true;
- * @param activity 上下文Activity
- * @param authToken Google账户的AuthToken
- * @return true表示登录成功,false表示登录失败
- */
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
- // Token过期,失效并重新获取
+ // maybe the auth token is out of date, now let's invalidate the
+ // token and try again
authToken = loginGoogleAccount(activity, true);
if (authToken == null) {
Log.e(TAG, "login google account failed");
return false;
}
- // 再次尝试登录
if (!loginGtask(authToken)) {
Log.e(TAG, "login gtask failed");
return false;
@@ -342,39 +225,25 @@ public class GTaskClient {
return true;
}
- /**
- * 实际执行GTask服务的登录(核心网络登录方法)
- * 流程:
- * 1. 初始化HttpClient:设置连接超时、Socket超时,配置CookieStore;
- * 2. 发送GET请求:携带AuthToken访问GTask的GET URL,获取响应;
- * 3. 检查认证Cookie:判断响应中是否包含GTL认证Cookie;
- * 4. 解析客户端版本号:从响应中提取_setup()方法内的JSON,获取client_version;
- * @param authToken Google账户的AuthToken
- * @return true表示登录成功,false表示登录失败
- */
private boolean loginGtask(String authToken) {
- // 配置HTTP参数:连接超时10秒,Socket超时15秒
int timeoutConnection = 10000;
int timeoutSocket = 15000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
-
- // 初始化HttpClient,配置CookieStore
mHttpClient = new DefaultHttpClient(httpParameters);
BasicCookieStore localBasicCookieStore = new BasicCookieStore();
mHttpClient.setCookieStore(localBasicCookieStore);
- // 禁用Expect-Continue头,避免部分服务器不兼容
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
- // 执行GTask登录
+ // login gtask
try {
- // 构建登录URL:携带AuthToken
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
- HttpResponse response = mHttpClient.execute(httpGet);
+ HttpResponse response = null;
+ response = mHttpClient.execute(httpGet);
- // 检查认证Cookie(GTL开头的Cookie为GTask认证Cookie)
+ // get the cookie now
List cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
@@ -386,18 +255,16 @@ public class GTaskClient {
Log.w(TAG, "it seems that there is no auth cookie");
}
- // 解析响应内容,获取客户端版本号(client_version)
+ // get the client version
String resString = getResponseContent(response.getEntity());
- String jsBegin = "_setup("; // JSON数据的起始标记
- String jsEnd = ")}"; // JSON数据的结束标记
+ String jsBegin = "_setup(";
+ String jsEnd = ")}";
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
String jsString = null;
- // 截取_setup()方法内的JSON字符串
if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end);
}
- // 解析JSON,获取client_version
JSONObject js = new JSONObject(jsString);
mClientVersion = js.getLong("v");
} catch (JSONException e) {
@@ -405,7 +272,7 @@ public class GTaskClient {
e.printStackTrace();
return false;
} catch (Exception e) {
- // 捕获所有异常(HTTP请求、IO、解析等)
+ // simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed");
return false;
}
@@ -413,89 +280,50 @@ public class GTaskClient {
return true;
}
- /**
- * 获取自增的动作ID(每次调用后ID+1)
- * 每个GTask操作(创建、更新、移动等)需要唯一的动作ID标识
- * @return 下一个动作ID
- */
private int getActionId() {
return mActionId++;
}
- /**
- * 创建HTTP POST请求(封装POST请求的公共配置)
- * 设置请求头:Content-Type为form-urlencoded,AT为1(GTask服务要求)
- * @return 配置好的HttpPost实例
- */
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
- // 设置内容类型:表单编码,UTF-8字符集
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
- // GTask服务要求的AT头(固定为1)
httpPost.setHeader("AT", "1");
return httpPost;
}
- /**
- * 解析HTTP响应的内容(处理Gzip/Deflate压缩)
- * 流程:
- * 1. 获取响应的编码类型(Content-Encoding);
- * 2. 根据编码类型创建对应的输入流(GzipInputStream/InflaterInputStream);
- * 3. 读取输入流内容,转换为字符串返回;
- * @param entity HTTP响应的实体(HttpEntity)
- * @return 响应的字符串内容
- * @throws IOException IO异常(流读取失败、关闭失败等)
- */
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
- // 获取响应的编码类型(gzip/deflate/null)
if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding);
}
- // 根据编码类型创建输入流
InputStream input = entity.getContent();
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
- // Gzip压缩:使用GZIPInputStream解压缩
input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
- // Deflate压缩:使用InflaterInputStream解压缩(启用nowrap模式)
Inflater inflater = new Inflater(true);
input = new InflaterInputStream(entity.getContent(), inflater);
}
- // 读取输入流内容
try {
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
- String buff;
- while ((buff = br.readLine()) != null) {
- sb.append(buff);
+ while (true) {
+ String buff = br.readLine();
+ if (buff == null) {
+ return sb.toString();
+ }
+ sb = sb.append(buff);
}
- return sb.toString();
} finally {
- // 确保输入流关闭,释放资源
input.close();
}
}
- /**
- * 发送POST请求到GTask服务(核心网络请求方法)
- * 流程:
- * 1. 检查登录状态:未登录则抛出异常;
- * 2. 构建POST请求:将JSON参数封装为表单参数(key为r);
- * 3. 执行POST请求:获取响应并解析为JSON对象返回;
- * 4. 异常处理:捕获不同异常,抛出对应的自定义异常;
- * @param js 要发送的JSON参数对象
- * @return GTask服务返回的JSON响应对象
- * @throws NetworkFailureException 网络异常(客户端协议错误、IO错误)
- * @throws ActionFailureException 业务逻辑异常(未登录、JSON解析失败)
- */
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
- // 检查登录状态
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
@@ -503,15 +331,13 @@ public class GTaskClient {
HttpPost httpPost = createHttpPost();
try {
- // 封装JSON参数为表单参数(key为r,值为JSON字符串)
LinkedList list = new LinkedList();
list.add(new BasicNameValuePair("r", js.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
- // 执行POST请求
+ // execute the post
HttpResponse response = mHttpClient.execute(httpPost);
- // 解析响应内容为JSON对象
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
@@ -534,33 +360,23 @@ public class GTaskClient {
}
}
- /**
- * 创建任务(Task)到GTask服务
- * 流程:
- * 1. 提交已有的批量更新动作(确保之前的更新生效);
- * 2. 构建创建任务的JSON请求:包含动作列表、客户端版本;
- * 3. 发送POST请求,获取响应中的新任务GID并设置到Task对象;
- * @param task 要创建的Task对象
- * @throws NetworkFailureException 网络异常
- * @throws ActionFailureException JSON解析/业务逻辑异常
- */
public void createTask(Task task) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
- // 添加创建任务的动作(getCreateAction返回创建动作的JSON)
+ // action_list
actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
- // 添加客户端版本号
+ // client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
- // 发送POST请求
+ // post
JSONObject jsResponse = postRequest(jsPost);
- // 解析响应中的新任务GID(NEW_ID字段)
- JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
+ JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
+ GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {
@@ -570,30 +386,23 @@ public class GTaskClient {
}
}
- /**
- * 创建任务列表(TaskList)到GTask服务
- * 流程与创建任务一致,区别在于使用TaskList的创建动作
- * @param tasklist 要创建的TaskList对象
- * @throws NetworkFailureException 网络异常
- * @throws ActionFailureException JSON解析/业务逻辑异常
- */
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
- // 添加创建任务列表的动作
+ // action_list
actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
- // 添加客户端版本号
+ // client version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
- // 发送POST请求
+ // post
JSONObject jsResponse = postRequest(jsPost);
- // 解析响应中的新列表GID
- JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
+ JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
+ GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {
@@ -603,26 +412,18 @@ public class GTaskClient {
}
}
- /**
- * 提交批量更新动作(将mUpdateArray中的更新动作发送到GTask服务)
- * 若更新数组不为空,则构建POST请求发送,发送后清空数组
- * @throws NetworkFailureException 网络异常
- * @throws ActionFailureException JSON解析/业务逻辑异常
- */
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
JSONObject jsPost = new JSONObject();
- // 添加更新动作列表
+ // action_list
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
- // 添加客户端版本号
+ // client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
- // 发送POST请求
postRequest(jsPost);
- // 清空更新数组
mUpdateArray = null;
} catch (JSONException e) {
Log.e(TAG, e.toString());
@@ -632,73 +433,48 @@ public class GTaskClient {
}
}
- /**
- * 添加更新动作到批量更新数组(优化网络请求,批量提交)
- * 逻辑:
- * 1. 若更新数组大小超过10,先提交已有动作(避免单次请求数据过大);
- * 2. 若数组为空,初始化数组;
- * 3. 将节点的更新动作添加到数组;
- * @param node 要更新的节点(Task/TaskList)
- * @throws NetworkFailureException 网络异常(提交时可能抛出)
- */
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
- // 限制单次批量更新的最大数量为10条,避免请求失败
+ // too many update items may result in an error
+ // set max to 10 items
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
- // 初始化更新数组
- if (mUpdateArray == null) {
+ if (mUpdateArray == null)
mUpdateArray = new JSONArray();
- }
- // 添加节点的更新动作
mUpdateArray.put(node.getUpdateAction(getActionId()));
}
}
- /**
- * 移动任务(在不同列表间/同列表内移动任务)
- * 流程:
- * 1. 提交已有批量更新动作;
- * 2. 构建移动动作的JSON请求:区分同列表/不同列表的参数;
- * 3. 发送POST请求执行移动操作;
- * @param task 要移动的任务
- * @param preParent 任务的原父列表
- * @param curParent 任务的新父列表
- * @throws NetworkFailureException 网络异常
- * @throws ActionFailureException JSON解析/业务逻辑异常
- */
- public void moveTask(Task task, TaskList preParent, TaskList curParent) throws NetworkFailureException {
+ public void moveTask(Task task, TaskList preParent, TaskList curParent)
+ throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
- // 配置移动动作的参数
- action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
+ // action_list
+ action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
+ GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
- action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); // 要移动的任务ID
-
- // 同列表移动且任务非第一个:添加前序兄弟ID(用于排序)
+ action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) {
+ // put prioring_sibing_id only if moving within the tasklist and
+ // it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
}
-
- // 原列表ID
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
- // 新父列表ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
-
- // 不同列表移动:添加目标列表ID
if (preParent != curParent) {
+ // put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
-
- // 添加动作到列表,发送请求
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
+
+ // client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
@@ -710,31 +486,20 @@ public class GTaskClient {
}
}
- /**
- * 删除节点(Task/TaskList):标记为已删除并发送更新请求
- * 流程:
- * 1. 提交已有批量更新动作;
- * 2. 设置节点的deleted标记为true;
- * 3. 构建删除动作的JSON请求并发送;
- * 4. 清空更新数组;
- * @param node 要删除的节点(Task/TaskList)
- * @throws NetworkFailureException 网络异常
- * @throws ActionFailureException JSON解析/业务逻辑异常
- */
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
- // 标记节点为已删除
+ // action_list
node.setDeleted(true);
- // 添加删除动作(更新动作包含deleted标记)
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
+
+ // client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
- // 发送请求,清空更新数组
postRequest(jsPost);
mUpdateArray = null;
} catch (JSONException e) {
@@ -744,16 +509,6 @@ public class GTaskClient {
}
}
- /**
- * 获取所有任务列表的元数据(从GTask服务获取)
- * 流程:
- * 1. 检查登录状态;
- * 2. 发送GET请求到GTask的GET URL;
- * 3. 解析响应中的任务列表JSON数组(lists字段);
- * @return 任务列表的JSON数组
- * @throws NetworkFailureException 网络异常
- * @throws ActionFailureException JSON解析/业务逻辑异常
- */
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@@ -762,9 +517,10 @@ public class GTaskClient {
try {
HttpGet httpGet = new HttpGet(mGetUrl);
- HttpResponse response = mHttpClient.execute(httpGet);
+ HttpResponse response = null;
+ response = mHttpClient.execute(httpGet);
- // 解析响应内容,获取任务列表数组
+ // get the task list
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}";
@@ -775,7 +531,6 @@ public class GTaskClient {
jsString = resString.substring(begin + jsBegin.length(), end);
}
JSONObject js = new JSONObject(jsString);
- // 返回lists字段的JSON数组
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
@@ -792,17 +547,6 @@ public class GTaskClient {
}
}
- /**
- * 获取指定任务列表下的所有任务(从GTask服务获取)
- * 流程:
- * 1. 提交已有批量更新动作;
- * 2. 构建GETALL动作的JSON请求:指定列表ID,不获取已删除任务;
- * 3. 发送POST请求,返回任务数组;
- * @param listGid 任务列表的GID
- * @return 任务的JSON数组
- * @throws NetworkFailureException 网络异常
- * @throws ActionFailureException JSON解析/业务逻辑异常
- */
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
try {
@@ -810,18 +554,18 @@ public class GTaskClient {
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
- // 配置GETALL动作:获取列表下的所有任务
- action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
+ // action_list
+ action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
+ GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
- action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); // 指定列表ID
- action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); // 不获取已删除任务
-
- // 添加动作到列表,发送请求
+ action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
+ action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
+
+ // client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
- // 解析响应中的任务数组
JSONObject jsResponse = postRequest(jsPost);
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
} catch (JSONException e) {
@@ -831,19 +575,11 @@ public class GTaskClient {
}
}
- /**
- * 获取当前同步的Google账户
- * @return 当前的Account实例,未登录则返回null
- */
public Account getSyncAccount() {
return mAccount;
}
- /**
- * 重置批量更新数组(清空待提交的更新动作)
- * 用于同步取消、异常处理时清空未提交的更新
- */
public void resetUpdateArray() {
mUpdateArray = null;
}
-}
\ No newline at end of file
+}
diff --git a/src/notes/gtask/remote/GTaskManager.java b/java/net/micode/notes/gtask/remote/GTaskManager.java
similarity index 54%
rename from src/notes/gtask/remote/GTaskManager.java
rename to java/net/micode/notes/gtask/remote/GTaskManager.java
index b544fc6..d2b4082 100644
--- a/src/notes/gtask/remote/GTaskManager.java
+++ b/java/net/micode/notes/gtask/remote/GTaskManager.java
@@ -47,148 +47,58 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
-/**
- * GTask同步核心管理类,采用**单例模式**实现,是GTask同步功能的统筹管理者
- * 该类负责整个GTask同步流程的调度和控制,主要完成以下职责:
- * 1. 同步状态管理:维护同步中、已取消等状态,防止并发同步;
- * 2. 数据映射存储:维护本地与远程的ID映射(GID→NID、NID→GID)、GTask列表/任务/元数据的缓存;
- * 3. 同步流程调度:执行登录→初始化GTask列表→同步文件夹→同步笔记→清理数据的完整流程;
- * 4. 内容同步处理:处理本地/远程的增、删、改、移动等同步动作,解决同步冲突;
- * 5. 元数据管理:处理GTask的元数据(MetaData)同步,关联笔记的额外信息;
- * 6. 异常处理:捕获网络/业务异常,返回对应的同步状态码。
- *
- * 同步状态码说明:
- * - {@link #STATE_SUCCESS}:同步成功
- * - {@link #STATE_NETWORK_ERROR}:网络异常(登录失败、请求失败等)
- * - {@link #STATE_INTERNAL_ERROR}:内部业务异常(JSON解析失败、未知同步动作等)
- * - {@link #STATE_SYNC_IN_PROGRESS}:同步正在进行中
- * - {@link #STATE_SYNC_CANCELLED}:同步被取消
- *
- * @author MiCode Open Source Community
- * @date 2010-2011
- */
+
public class GTaskManager {
- /**
- * 日志标签,使用类的简单名称,便于调试时定位日志来源
- */
private static final String TAG = GTaskManager.class.getSimpleName();
- // ====================== 同步状态码常量 ======================
- /**
- * 同步状态:成功
- */
public static final int STATE_SUCCESS = 0;
- /**
- * 同步状态:网络错误(登录失败、HTTP请求失败等)
- */
public static final int STATE_NETWORK_ERROR = 1;
- /**
- * 同步状态:内部错误(JSON解析失败、未知同步动作、数据不存在等)
- */
public static final int STATE_INTERNAL_ERROR = 2;
- /**
- * 同步状态:同步正在进行中(防止并发同步)
- */
public static final int STATE_SYNC_IN_PROGRESS = 3;
- /**
- * 同步状态:同步被取消
- */
public static final int STATE_SYNC_CANCELLED = 4;
- // ====================== 单例模式相关 ======================
- /**
- * GTaskManager单例实例,通过{link #getInstance()}获取
- */
private static GTaskManager mInstance = null;
- // ====================== 上下文/服务相关成员变量 ======================
- /**
- * Activity上下文,用于GTaskClient获取Google账户的AuthToken(需要Activity上下文处理授权)
- */
private Activity mActivity;
- /**
- * 应用上下文,用于获取ContentResolver、资源字符串等
- */
private Context mContext;
- /**
- * 内容解析器,用于访问本地笔记数据库(ContentProvider)
- */
private ContentResolver mContentResolver;
- // ====================== 同步状态相关成员变量 ======================
- /**
- * 同步状态标记:true表示正在同步,false表示同步未进行/已完成
- */
private boolean mSyncing;
- /**
- * 同步取消标记:true表示同步被取消,false表示同步正常执行
- */
private boolean mCancelled;
- // ====================== GTask远程数据缓存相关 ======================
- /**
- * GTask任务列表缓存:Key为GID(远程唯一标识),Value为TaskList对象
- */
private HashMap mGTaskListHashMap;
- /**
- * GTask节点缓存(包含TaskList和Task):Key为GID,Value为Node对象
- */
private HashMap mGTaskHashMap;
- /**
- * GTask元数据缓存:Key为关联的Task GID,Value为MetaData对象
- */
private HashMap mMetaHashMap;
- /**
- * 元数据任务列表(存储MetaData的TaskList,名称为MIUI_FOLDER_PREFFIX + FOLDER_META)
- */
private TaskList mMetaList;
- // ====================== 本地数据同步相关 ======================
- /**
- * 本地已删除笔记ID集合:存储需要从本地数据库批量删除的笔记ID(回收站中的笔记、远程删除的本地笔记)
- */
private HashSet mLocalDeleteIdMap;
- /**
- * GID→NID映射:Key为远程GID,Value为本地笔记ID(用于关联本地与远程数据)
- */
private HashMap mGidToNid;
- /**
- * NID→GID映射:Key为本地笔记ID,Value为远程GID(反向映射,便于快速查找)
- */
private HashMap mNidToGid;
- /**
- * 私有构造方法:初始化GTaskManager的默认属性(单例模式禁止外部实例化)
- * 初始化各类缓存集合、状态标记为默认值,确保单例的唯一性
- */
private GTaskManager() {
- mSyncing = false; // 初始未同步
- mCancelled = false; // 初始未取消
- mGTaskListHashMap = new HashMap(); // 初始化任务列表缓存
- mGTaskHashMap = new HashMap(); // 初始化节点缓存
- mMetaHashMap = new HashMap(); // 初始化元数据缓存
- mMetaList = null; // 初始无元数据列表
- mLocalDeleteIdMap = new HashSet(); // 初始化本地删除ID集合
- mGidToNid = new HashMap(); // 初始化GID→NID映射
- mNidToGid = new HashMap(); // 初始化NID→GID映射
+ mSyncing = false;
+ mCancelled = false;
+ mGTaskListHashMap = new HashMap();
+ mGTaskHashMap = new HashMap();
+ mMetaHashMap = new HashMap();
+ mMetaList = null;
+ mLocalDeleteIdMap = new HashSet();
+ mGidToNid = new HashMap();
+ mNidToGid = new HashMap();
}
- /**
- * 获取GTaskManager的单例实例(线程安全的同步方法)
- * @return GTaskManager唯一实例
- */
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@@ -196,44 +106,20 @@ public class GTaskManager {
return mInstance;
}
- /**
- * 设置Activity上下文(用于GTaskClient登录时获取AuthToken)
- * 该方法需要在同步前调用,传入处理账户授权的Activity
- * @param activity 用于获取AuthToken的Activity上下文
- */
public synchronized void setActivityContext(Activity activity) {
- // 注释:用于获取Google账户的AuthToken(需要Activity上下文处理用户授权)
+ // used for getting authtoken
mActivity = activity;
}
- /**
- * 执行GTask同步的核心方法(统筹整个同步流程)
- * 同步流程:
- * 1. 状态检查:若正在同步,返回STATE_SYNC_IN_PROGRESS;
- * 2. 初始化:清空缓存、重置状态、获取ContentResolver;
- * 3. 登录GTask:调用GTaskClient登录,失败则抛出网络异常;
- * 4. 初始化GTask列表:从远程获取TaskList和Task数据,缓存到本地集合;
- * 5. 同步内容:先处理回收站笔记,再同步文件夹,最后同步普通笔记;
- * 6. 异常处理:捕获网络/业务异常,返回对应状态码;
- * 7. 清理资源:清空缓存,重置同步状态;
- * 8. 返回结果:根据取消标记返回STATE_SYNC_CANCELLED或STATE_SUCCESS;
- * @param context 应用上下文(用于访问本地数据库、资源)
- * @param asyncTask GTaskASyncTask实例(用于发布同步进度)
- * @return 同步状态码(STATE_*常量)
- */
public int sync(Context context, GTaskASyncTask asyncTask) {
- // 步骤1:检查同步状态,正在同步则直接返回
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS;
}
-
- // 步骤2:初始化同步环境
mContext = context;
mContentResolver = mContext.getContentResolver();
mSyncing = true;
mCancelled = false;
- // 清空所有缓存集合,避免旧数据干扰
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
@@ -242,41 +128,34 @@ public class GTaskManager {
mNidToGid.clear();
try {
- // 步骤3:获取GTaskClient实例,重置批量更新数组
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
- // 步骤4:登录GTask服务(未取消则执行)
+ // login google task
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed");
}
}
- // 步骤5:发布进度:初始化GTask列表
+ // get the task list from google
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
- // 初始化GTask列表(从远程获取数据并缓存)
initGTaskList();
- // 步骤6:发布进度:正在同步内容
+ // do content sync work
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
- // 执行内容同步(文件夹、笔记、回收站)
syncContent();
} catch (NetworkFailureException e) {
- // 网络异常:返回STATE_NETWORK_ERROR
Log.e(TAG, e.toString());
return STATE_NETWORK_ERROR;
} catch (ActionFailureException e) {
- // 业务逻辑异常:返回STATE_INTERNAL_ERROR
Log.e(TAG, e.toString());
return STATE_INTERNAL_ERROR;
} catch (Exception e) {
- // 未知异常:返回STATE_INTERNAL_ERROR
Log.e(TAG, e.toString());
e.printStackTrace();
return STATE_INTERNAL_ERROR;
} finally {
- // 步骤7:清理资源,重置同步状态(无论成功/失败都会执行)
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
@@ -286,54 +165,36 @@ public class GTaskManager {
mSyncing = false;
}
- // 步骤8:返回结果:取消则返回STATE_SYNC_CANCELLED,否则返回STATE_SUCCESS
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
- /**
- * 初始化GTask列表(从远程获取TaskList、Task、MetaData并缓存)
- * 流程:
- * 1. 获取远程所有TaskList的JSON数组;
- * 2. 初始化元数据列表(MetaList):查找名称为MIUI_FOLDER_PREFFIX + FOLDER_META的TaskList,获取其下的MetaData;
- * 3. 若元数据列表不存在,则创建并上传到远程;
- * 4. 初始化普通TaskList:过滤以MIUI_FOLDER_PREFFIX开头的非MetaList,获取其下的Task并缓存;
- * @throws NetworkFailureException 网络异常(GTaskClient请求失败)
- * @throws ActionFailureException 业务异常(JSON解析失败)
- */
private void initGTaskList() throws NetworkFailureException {
- // 同步被取消则直接返回
- if (mCancelled) {
+ if (mCancelled)
return;
- }
-
GTaskClient client = GTaskClient.getInstance();
try {
- // 步骤1:从远程获取所有TaskList的JSON数组
JSONArray jsTaskLists = client.getTaskLists();
- // 步骤2:初始化元数据列表(MetaList)
+ // init meta list first
mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
- // 匹配元数据列表的名称:MIUI_FOLDER_PREFFIX + FOLDER_META
- if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
+ if (name
+ .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList();
- // 根据远程JSON初始化TaskList内容
mMetaList.setContentByRemoteJSON(object);
- // 步骤3:加载元数据列表下的MetaData
+ // load meta data
JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) {
- object = jsMetas.getJSONObject(j);
+ object = (JSONObject) jsMetas.getJSONObject(j);
MetaData metaData = new MetaData();
metaData.setContentByRemoteJSON(object);
- // 仅保存有价值的元数据(isWorthSaving为true)
if (metaData.isWorthSaving()) {
mMetaList.addChildTask(metaData);
- // 缓存元数据:Key为关联的Task GID(relatedGid)
if (metaData.getGid() != null) {
mMetaHashMap.put(metaData.getRelatedGid(), metaData);
}
@@ -342,152 +203,122 @@ public class GTaskManager {
}
}
- // 步骤4:若元数据列表不存在,则创建并上传到远程
+ // create meta list if not existed
if (mMetaList == null) {
mMetaList = new TaskList();
- mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META);
+ mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ + GTaskStringUtils.FOLDER_META);
GTaskClient.getInstance().createTaskList(mMetaList);
}
- // 步骤5:初始化普通TaskList(以MIUI_FOLDER_PREFFIX开头,非MetaList)
+ // init task list
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
- // 过滤条件:以MIUI_FOLDER_PREFFIX开头,且不是MetaList
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
- && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
+ && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ + GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object);
- // 缓存TaskList
mGTaskListHashMap.put(gid, tasklist);
- // 缓存到节点集合(包含TaskList和Task)
mGTaskHashMap.put(gid, tasklist);
- // 步骤6:加载该TaskList下的所有Task
+ // load tasks
JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) {
- object = jsTasks.getJSONObject(j);
+ object = (JSONObject) jsTasks.getJSONObject(j);
gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
Task task = new Task();
task.setContentByRemoteJSON(object);
- // 仅保存有价值的Task
if (task.isWorthSaving()) {
- // 设置元数据(从缓存中获取)
task.setMetaInfo(mMetaHashMap.get(gid));
tasklist.addChildTask(task);
- // 缓存Task
mGTaskHashMap.put(gid, task);
}
}
}
}
} catch (JSONException e) {
- // JSON解析失败,抛出业务异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("initGTaskList: handing JSONObject failed");
}
}
- /**
- * 同步内容(统筹本地与远程的笔记、文件夹同步)
- * 流程:
- * 1. 处理本地回收站中的笔记:远程删除对应节点,记录本地删除ID;
- * 2. 同步文件夹(优先同步文件夹,再同步笔记);
- * 3. 处理本地普通笔记:根据GID匹配远程节点,执行对应的同步动作;
- * 4. 处理远程新增的节点:本地添加对应笔记/文件夹;
- * 5. 批量删除本地标记的笔记:从数据库中删除回收站/远程删除的笔记;
- * 6. 提交剩余的批量更新,刷新本地同步ID(lastModified);
- * @throws NetworkFailureException 网络异常(GTaskClient请求失败)
- * @throws ActionFailureException 业务异常(批量删除失败、数据不存在等)
- */
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;
String gid;
Node node;
- // 清空本地删除ID集合
mLocalDeleteIdMap.clear();
- // 同步被取消则返回
if (mCancelled) {
return;
}
- // 步骤1:处理本地回收站中的笔记(标记为删除,需要远程删除对应节点)
+ // for local deleted note
try {
- // 查询回收站中的非系统笔记(parent_id=ID_TRASH_FOLER,type<>TYPE_SYSTEM)
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, null);
if (c != null) {
while (c.moveToNext()) {
- // 获取笔记的GTask ID
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- // 从远程缓存中获取对应节点
node = mGTaskHashMap.get(gid);
if (node != null) {
- // 从缓存中移除,执行远程删除动作
mGTaskHashMap.remove(gid);
doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c);
}
- // 记录本地删除ID,后续批量删除
+
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
}
} else {
Log.w(TAG, "failed to query trash folder");
}
} finally {
- // 关闭Cursor,释放资源
if (c != null) {
c.close();
c = null;
}
}
- // 步骤2:优先同步文件夹
+ // sync folder first
syncFolder();
- // 步骤3:处理本地普通笔记(非回收站的TYPE_NOTE类型)
+ // for note existing in database
try {
- // 查询非回收站的普通笔记(type=TYPE_NOTE,parent_id<>ID_TRASH_FOLER)
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
- // 获取笔记的GTask ID
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
- // 从远程缓存中获取对应节点
node = mGTaskHashMap.get(gid);
if (node != null) {
- // 从缓存中移除,记录ID映射
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
- // 获取同步动作类型(根据本地/远程的修改时间判断)
syncType = node.getSyncAction(c);
} else {
- // 远程无对应节点:判断是本地新增还是远程删除
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
- // GID为空:本地新增,需要远程添加
+ // local add
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
- // GID非空:远程已删除,需要本地删除
+ // remote delete
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
- // 执行同步动作
doContentSync(syncType, node, c);
}
} else {
Log.w(TAG, "failed to query existing note in database");
}
+
} finally {
if (c != null) {
c.close();
@@ -495,69 +326,58 @@ public class GTaskManager {
}
}
- // 步骤4:处理远程新增的节点(缓存中剩余的节点,本地无对应数据)
+ // go through remaining items
Iterator> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = iter.next();
node = entry.getValue();
- // 本地添加该节点
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
- // 步骤5:批量删除本地标记的笔记(未取消则执行)
+ // mCancelled can be set by another thread, so we neet to check one by
+ // one
+ // clear local delete table
if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes");
}
}
- // 步骤6:提交剩余的批量更新,刷新本地同步ID(未取消则执行)
+ // refresh local sync id
if (!mCancelled) {
GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId();
}
+
}
- /**
- * 同步文件夹(处理本地与远程的文件夹同步,优先于笔记同步)
- * 流程:
- * 1. 同步系统文件夹:根文件夹(ID_ROOT_FOLDER)、通话记录文件夹(ID_CALL_RECORD_FOLDER);
- * 2. 同步本地普通文件夹:非回收站的TYPE_FOLDER类型;
- * 3. 处理远程新增的文件夹:本地添加对应文件夹;
- * 4. 提交批量更新;
- * @throws NetworkFailureException 网络异常(GTaskClient请求失败)
- */
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
Node node;
int syncType;
- // 同步被取消则返回
if (mCancelled) {
return;
}
- // 步骤1:同步根文件夹(ID_ROOT_FOLDER)
+ // for root folder
try {
- // 查询根文件夹
- c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, Notes.ID_ROOT_FOLDER),
- SqlNote.PROJECTION_NOTE, null, null, null);
+ c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
+ Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
if (c != null) {
c.moveToNext();
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
- // 从缓存中移除,记录ID映射
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
- // 系统文件夹仅更新远程名称(若不一致)
- if (!node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
+ // for system folder, only update remote name if necessary
+ if (!node.getName().equals(
+ GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
- }
} else {
- // 远程无对应文件夹,添加到远程
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
}
} else {
@@ -570,26 +390,27 @@ public class GTaskManager {
}
}
- // 步骤2:同步通话记录文件夹(ID_CALL_RECORD_FOLDER)
+ // for call-note folder
try {
- // 查询通话记录文件夹
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
- new String[] { String.valueOf(Notes.ID_CALL_RECORD_FOLDER) }, null);
+ new String[] {
+ String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
+ }, null);
if (c != null) {
if (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
- // 从缓存中移除,记录ID映射
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
- // 系统文件夹仅更新远程名称(若不一致)
- if (!node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
+ // for system folder, only update remote name if
+ // necessary
+ if (!node.getName().equals(
+ GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ + GTaskStringUtils.FOLDER_CALL_NOTE))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
- }
} else {
- // 远程无对应文件夹,添加到远程
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
}
}
@@ -603,9 +424,8 @@ public class GTaskManager {
}
}
- // 步骤3:同步本地普通文件夹(非回收站的TYPE_FOLDER类型)
+ // for local existing folders
try {
- // 查询非回收站的文件夹(type=TYPE_FOLDER,parent_id<>ID_TRASH_FOLER)
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)
@@ -615,23 +435,19 @@ public class GTaskManager {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
- // 从缓存中移除,记录ID映射
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
- // 获取同步动作类型
syncType = node.getSyncAction(c);
} else {
- // 远程无对应文件夹:判断是本地新增还是远程删除
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
- // GID为空:本地新增,远程添加
+ // local add
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
- // GID非空:远程删除,本地删除
+ // remote delete
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
- // 执行同步动作
doContentSync(syncType, node, c);
}
} else {
@@ -644,62 +460,36 @@ public class GTaskManager {
}
}
- // 步骤4:处理远程新增的文件夹(本地无对应数据)
+ // for remote add folders
Iterator> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = iter.next();
gid = entry.getKey();
node = entry.getValue();
if (mGTaskHashMap.containsKey(gid)) {
- // 从缓存中移除,本地添加该文件夹
mGTaskHashMap.remove(gid);
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
}
- // 步骤5:提交批量更新(未取消则执行)
- if (!mCancelled) {
+ if (!mCancelled)
GTaskClient.getInstance().commitUpdate();
- }
}
- /**
- * 执行具体的内容同步动作(根据同步类型处理本地/远程的增删改)
- * 同步类型说明(Node类的SYNC_ACTION_*常量):
- * - ADD_LOCAL:远程新增,本地添加
- * - ADD_REMOTE:本地新增,远程添加
- * - DEL_LOCAL:远程删除,本地删除
- * - DEL_REMOTE:本地删除,远程删除
- * - UPDATE_LOCAL:远程更新,本地更新
- * - UPDATE_REMOTE:本地更新,远程更新
- * - UPDATE_CONFLICT:同步冲突(当前采用本地覆盖远程)
- * - NONE:无动作
- * - ERROR:错误动作(抛出异常)
- * @param syncType 同步动作类型(Node.SYNC_ACTION_*常量)
- * @param node 远程节点(Task/TaskList),可为null(如本地新增时)
- * @param c 本地数据库的Cursor(包含笔记/文件夹数据),可为null(如远程新增时)
- * @throws NetworkFailureException 网络异常(GTaskClient请求失败)
- * @throws ActionFailureException 业务异常(未知同步类型、数据不存在等)
- */
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
- // 同步被取消则返回
if (mCancelled) {
return;
}
MetaData meta;
- // 根据同步类型执行对应操作
switch (syncType) {
case Node.SYNC_ACTION_ADD_LOCAL:
- // 远程新增,本地添加
addLocalNode(node);
break;
case Node.SYNC_ACTION_ADD_REMOTE:
- // 本地新增,远程添加
addRemoteNode(node, c);
break;
case Node.SYNC_ACTION_DEL_LOCAL:
- // 远程删除,本地删除:先删除元数据,再记录本地删除ID
meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN));
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta);
@@ -707,7 +497,6 @@ public class GTaskManager {
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
break;
case Node.SYNC_ACTION_DEL_REMOTE:
- // 本地删除,远程删除:先删除元数据,再删除节点
meta = mMetaHashMap.get(node.getGid());
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta);
@@ -715,72 +504,57 @@ public class GTaskManager {
GTaskClient.getInstance().deleteNode(node);
break;
case Node.SYNC_ACTION_UPDATE_LOCAL:
- // 远程更新,本地更新
updateLocalNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_REMOTE:
- // 本地更新,远程更新
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_CONFLICT:
- // 同步冲突:当前采用本地覆盖远程的策略(可优化为合并修改)
+ // merging both modifications maybe a good idea
+ // right now just use local update simply
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_NONE:
- // 无动作,直接返回
break;
case Node.SYNC_ACTION_ERROR:
default:
- // 未知同步类型,抛出业务异常
throw new ActionFailureException("unkown sync action type");
}
}
- /**
- * 本地添加远程节点(远程新增,本地创建对应笔记/文件夹)
- * @param node 远程节点(Task/TaskList)
- * @throws NetworkFailureException 网络异常(元数据处理失败)
- * @throws ActionFailureException 业务异常(父节点不存在)
- */
private void addLocalNode(Node node) throws NetworkFailureException {
- // 同步被取消则返回
if (mCancelled) {
return;
}
SqlNote sqlNote;
- // 区分节点类型:TaskList(文件夹)或Task(笔记)
if (node instanceof TaskList) {
- // 处理文件夹节点
- if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
- // 根文件夹:使用固定ID(ID_ROOT_FOLDER)
+ if (node.getName().equals(
+ GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
- } else if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
- // 通话记录文件夹:使用固定ID(ID_CALL_RECORD_FOLDER)
+ } else if (node.getName().equals(
+ GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
} else {
- // 普通文件夹:创建新的SqlNote,设置内容和父节点(根文件夹)
sqlNote = new SqlNote(mContext);
sqlNote.setContent(node.getLocalJSONFromContent());
sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
}
} else {
- // 处理笔记节点(Task)
sqlNote = new SqlNote(mContext);
JSONObject js = node.getLocalJSONFromContent();
try {
- // 处理笔记ID冲突:若ID已存在,移除ID(由数据库自动生成)
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
+ // the id is not available, have to create a new one
note.remove(NoteColumns.ID);
}
}
}
- // 处理笔记数据ID冲突:若ID已存在,移除ID
if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
for (int i = 0; i < dataArray.length(); i++) {
@@ -788,60 +562,50 @@ public class GTaskManager {
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
+ // the data id is not available, have to create
+ // a new one
data.remove(DataColumns.ID);
}
}
}
+
}
} catch (JSONException e) {
Log.w(TAG, e.toString());
e.printStackTrace();
}
- // 设置笔记内容
sqlNote.setContent(js);
- // 获取父文件夹的本地ID(从GID→NID映射中获取)
Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot add local node");
}
- // 设置父节点ID
sqlNote.setParentId(parentId.longValue());
}
- // 步骤1:设置GTask ID,提交到本地数据库
+ // create the local node
sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false);
- // 步骤2:更新ID映射
+ // update gid-nid mapping
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
- // 步骤3:更新远程元数据
+ // update meta
updateRemoteMeta(node.getGid(), sqlNote);
}
- /**
- * 本地更新远程节点(远程更新,本地更新对应笔记/文件夹)
- * @param node 远程节点(Task/TaskList)
- * @param c 本地数据库的Cursor(包含旧数据)
- * @throws NetworkFailureException 网络异常(元数据处理失败)
- * @throws ActionFailureException 业务异常(父节点不存在)
- */
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
- // 同步被取消则返回
if (mCancelled) {
return;
}
SqlNote sqlNote;
- // 步骤1:创建SqlNote并加载本地旧数据
+ // update the note locally
sqlNote = new SqlNote(mContext, c);
- // 步骤2:更新内容为远程节点的内容
sqlNote.setContent(node.getLocalJSONFromContent());
- // 步骤3:设置父节点ID(区分Task和TaskList)
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
: new Long(Notes.ID_ROOT_FOLDER);
if (parentId == null) {
@@ -849,23 +613,13 @@ public class GTaskManager {
throw new ActionFailureException("cannot update local node");
}
sqlNote.setParentId(parentId.longValue());
-
- // 步骤4:提交更新到本地数据库
sqlNote.commit(true);
- // 步骤5:更新远程元数据
+ // update meta info
updateRemoteMeta(node.getGid(), sqlNote);
}
- /**
- * 远程添加本地节点(本地新增,远程创建对应Task/TaskList)
- * @param node 远程节点(可为null,本地新增时无远程节点)
- * @param c 本地数据库的Cursor(包含本地新增数据)
- * @throws NetworkFailureException 网络异常(GTaskClient创建节点失败)
- * @throws ActionFailureException 业务异常(父节点不存在)
- */
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
- // 同步被取消则返回
if (mCancelled) {
return;
}
@@ -873,42 +627,35 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c);
Node n;
- // 区分节点类型:笔记(TYPE_NOTE)或文件夹(TYPE_FOLDER)
+ // update remotely
if (sqlNote.isNoteType()) {
- // 处理笔记:创建远程Task
Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent());
- // 获取父文件夹的远程GID(从NID→GID映射中获取)
String parentGid = mNidToGid.get(sqlNote.getParentId());
if (parentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot add remote task");
}
- // 添加到父TaskList
mGTaskListHashMap.get(parentGid).addChildTask(task);
- // 远程创建Task
GTaskClient.getInstance().createTask(task);
n = (Node) task;
- // 添加元数据
+ // add meta
updateRemoteMeta(task.getGid(), sqlNote);
} else {
- // 处理文件夹:创建远程TaskList(先检查是否已存在)
TaskList tasklist = null;
- // 构建文件夹名称(MIUI_FOLDER_PREFFIX + 文件夹名称/固定标识)
+ // we need to skip folder if it has already existed
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
- if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) {
+ if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT;
- } else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER) {
+ else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER)
folderName += GTaskStringUtils.FOLDER_CALL_NOTE;
- } else {
+ else
folderName += sqlNote.getSnippet();
- }
- // 检查远程是否已存在该文件夹(避免重复创建)
Iterator> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = iter.next();
@@ -917,7 +664,6 @@ public class GTaskManager {
if (list.getName().equals(folderName)) {
tasklist = list;
- // 从缓存中移除,避免重复处理
if (mGTaskHashMap.containsKey(gid)) {
mGTaskHashMap.remove(gid);
}
@@ -925,7 +671,7 @@ public class GTaskManager {
}
}
- // 远程无该文件夹,创建并上传
+ // no match we can add now
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
@@ -935,47 +681,36 @@ public class GTaskManager {
n = (Node) tasklist;
}
- // 步骤1:更新本地笔记的GTask ID,提交到数据库
+ // update local note
sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false);
- // 步骤2:重置本地修改标记(同步完成)
sqlNote.resetLocalModified();
sqlNote.commit(true);
- // 步骤3:更新ID映射
+ // gid-id mapping
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
- /**
- * 远程更新本地节点(本地更新,远程更新对应Task/TaskList)
- * @param node 远程节点(Task/TaskList)
- * @param c 本地数据库的Cursor(包含本地更新数据)
- * @throws NetworkFailureException 网络异常(GTaskClient更新/移动节点失败)
- * @throws ActionFailureException 业务异常(父节点不存在)
- */
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
- // 同步被取消则返回
if (mCancelled) {
return;
}
SqlNote sqlNote = new SqlNote(mContext, c);
- // 步骤1:更新远程节点内容(从本地JSON加载)
+ // update remotely
node.setContentByLocalJSON(sqlNote.getContent());
- // 添加到批量更新数组
GTaskClient.getInstance().addUpdateNode(node);
- // 步骤2:更新元数据
+ // update meta
updateRemoteMeta(node.getGid(), sqlNote);
- // 步骤3:处理笔记的移动(父文件夹变化时)
+ // move task if necessary
if (sqlNote.isNoteType()) {
Task task = (Task) node;
TaskList preParentList = task.getParent();
- // 获取当前父文件夹的远程GID
String curParentGid = mNidToGid.get(sqlNote.getParentId());
if (curParentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
@@ -983,7 +718,6 @@ public class GTaskManager {
}
TaskList curParentList = mGTaskListHashMap.get(curParentGid);
- // 父文件夹变化,执行移动操作
if (preParentList != curParentList) {
preParentList.removeChildTask(task);
curParentList.addChildTask(task);
@@ -991,27 +725,18 @@ public class GTaskManager {
}
}
- // 步骤4:重置本地修改标记(同步完成)
+ // clear local modified flag
sqlNote.resetLocalModified();
sqlNote.commit(true);
}
- /**
- * 更新远程元数据(关联Task的MetaData,存储额外信息)
- * @param gid 关联的Task GID
- * @param sqlNote 本地笔记数据(包含元数据内容)
- * @throws NetworkFailureException 网络异常(GTaskClient创建/更新元数据失败)
- */
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
- // 仅处理笔记类型的元数据(文件夹无元数据)
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
if (metaData != null) {
- // 元数据已存在,更新内容并添加到批量更新
metaData.setMeta(gid, sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(metaData);
} else {
- // 元数据不存在,创建并上传到元数据列表
metaData = new MetaData();
metaData.setMeta(gid, sqlNote.getContent());
mMetaList.addChildTask(metaData);
@@ -1021,19 +746,12 @@ public class GTaskManager {
}
}
- /**
- * 刷新本地同步ID(将远程节点的lastModified更新到本地笔记的SYNC_ID字段)
- * 作用:用于后续同步时判断本地/远程的修改时间,确定同步动作类型
- * @throws NetworkFailureException 网络异常(重新初始化GTask列表失败)
- * @throws ActionFailureException 业务异常(本地笔记无对应GID)
- */
private void refreshLocalSyncId() throws NetworkFailureException {
- // 同步被取消则返回
if (mCancelled) {
return;
}
- // 步骤1:重新初始化GTask列表,获取最新的远程数据
+ // get the latest gtask list
mGTaskHashMap.clear();
mGTaskListHashMap.clear();
mMetaHashMap.clear();
@@ -1041,7 +759,6 @@ public class GTaskManager {
Cursor c = null;
try {
- // 步骤2:查询本地非系统、非回收站的笔记/文件夹
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
@@ -1051,23 +768,21 @@ public class GTaskManager {
String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
Node node = mGTaskHashMap.get(gid);
if (node != null) {
- // 从缓存中移除,更新本地SYNC_ID为远程的lastModified
mGTaskHashMap.remove(gid);
ContentValues values = new ContentValues();
values.put(NoteColumns.SYNC_ID, node.getLastModified());
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
c.getLong(SqlNote.ID_COLUMN)), values, null, null);
} else {
- // 本地笔记无对应远程GID,抛出异常
Log.e(TAG, "something is missed");
- throw new ActionFailureException("some local items don't have gid after sync");
+ throw new ActionFailureException(
+ "some local items don't have gid after sync");
}
}
} else {
Log.w(TAG, "failed to query local note to refresh sync id");
}
} finally {
- // 关闭Cursor,释放资源
if (c != null) {
c.close();
c = null;
@@ -1075,18 +790,11 @@ public class GTaskManager {
}
}
- /**
- * 获取当前同步的Google账户名称
- * @return Google账户名称(如xxx@gmail.com)
- */
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}
- /**
- * 取消当前的同步任务(设置mCancelled为true,同步流程会检测该标记并终止)
- */
public void cancelSync() {
mCancelled = true;
}
-}
\ No newline at end of file
+}
diff --git a/java/net/micode/notes/gtask/remote/GTaskSyncService.java b/java/net/micode/notes/gtask/remote/GTaskSyncService.java
new file mode 100644
index 0000000..cca36f7
--- /dev/null
+++ b/java/net/micode/notes/gtask/remote/GTaskSyncService.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.gtask.remote;
+
+import android.app.Activity;
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.IBinder;
+
+public class GTaskSyncService extends Service {
+ public final static String ACTION_STRING_NAME = "sync_action_type";
+
+ public final static int ACTION_START_SYNC = 0;
+
+ public final static int ACTION_CANCEL_SYNC = 1;
+
+ public final static int ACTION_INVALID = 2;
+
+ public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
+
+ public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
+
+ public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
+
+ private static GTaskASyncTask mSyncTask = null;
+
+ private static String mSyncProgress = "";
+
+ private void startSync() {
+ if (mSyncTask == null) {
+ mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
+ public void onComplete() {
+ mSyncTask = null;
+ sendBroadcast("");
+ stopSelf();
+ }
+ });
+ sendBroadcast("");
+ mSyncTask.execute();
+ }
+ }
+
+ private void cancelSync() {
+ if (mSyncTask != null) {
+ mSyncTask.cancelSync();
+ }
+ }
+
+ @Override
+ public void onCreate() {
+ mSyncTask = null;
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ Bundle bundle = intent.getExtras();
+ if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
+ switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
+ case ACTION_START_SYNC:
+ startSync();
+ break;
+ case ACTION_CANCEL_SYNC:
+ cancelSync();
+ break;
+ default:
+ break;
+ }
+ return START_STICKY;
+ }
+ return super.onStartCommand(intent, flags, startId);
+ }
+
+ @Override
+ public void onLowMemory() {
+ if (mSyncTask != null) {
+ mSyncTask.cancelSync();
+ }
+ }
+
+ public IBinder onBind(Intent intent) {
+ return null;
+ }
+
+ public void sendBroadcast(String msg) {
+ mSyncProgress = msg;
+ Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
+ intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);
+ intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
+ sendBroadcast(intent);
+ }
+
+ public static void startSync(Activity activity) {
+ GTaskManager.getInstance().setActivityContext(activity);
+ Intent intent = new Intent(activity, GTaskSyncService.class);
+ intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
+ activity.startService(intent);
+ }
+
+ public static void cancelSync(Context context) {
+ Intent intent = new Intent(context, GTaskSyncService.class);
+ intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
+ context.startService(intent);
+ }
+
+ public static boolean isSyncing() {
+ return mSyncTask != null;
+ }
+
+ public static String getProgressString() {
+ return mSyncProgress;
+ }
+}
diff --git a/java/net/micode/notes/model/Note.java b/java/net/micode/notes/model/Note.java
new file mode 100644
index 0000000..6706cf6
--- /dev/null
+++ b/java/net/micode/notes/model/Note.java
@@ -0,0 +1,253 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.model;
+import android.content.ContentProviderOperation;
+import android.content.ContentProviderResult;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.OperationApplicationException;
+import android.net.Uri;
+import android.os.RemoteException;
+import android.util.Log;
+
+import net.micode.notes.data.Notes;
+import net.micode.notes.data.Notes.CallNote;
+import net.micode.notes.data.Notes.DataColumns;
+import net.micode.notes.data.Notes.NoteColumns;
+import net.micode.notes.data.Notes.TextNote;
+
+import java.util.ArrayList;
+
+
+public class 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
+ */
+ public static synchronized long getNewNoteId(Context context, long folderId) {
+ // Create a new note in the database
+ ContentValues values = new ContentValues();
+ 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);
+ Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
+
+ long noteId = 0;
+ try {
+ noteId = Long.valueOf(uri.getPathSegments().get(1));
+ } catch (NumberFormatException e) {
+ Log.e(TAG, "Get note id error :" + e.toString());
+ noteId = 0;
+ }
+ if (noteId == -1) {
+ throw new IllegalStateException("Wrong note id:" + noteId);
+ }
+ return noteId;
+ }
+
+ public Note() {
+ mNoteDiffValues = new 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());
+ }
+
+ public void setTextData(String key, String value) {
+ mNoteData.setTextData(key, value);
+ }
+
+ public void setTextDataId(long id) {
+ mNoteData.setTextDataId(id);
+ }
+
+ public long getTextDataId() {
+ return mNoteData.mTextDataId;
+ }
+
+ 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();
+ }
+
+ public boolean syncNote(Context context, long noteId) {
+ if (noteId <= 0) {
+ throw new IllegalArgumentException("Wrong note id:" + noteId);
+ }
+
+ if (!isLocalModified()) {
+ 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
+ */
+ 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();
+
+ if (mNoteData.isLocalModified()
+ && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ private class NoteData {
+ private long mTextDataId;
+
+ private ContentValues mTextDataValues;
+
+ private long mCallDataId;
+
+ private ContentValues mCallDataValues;
+
+ private static final String TAG = "NoteData";
+
+ public NoteData() {
+ mTextDataValues = new ContentValues();
+ mCallDataValues = new ContentValues();
+ mTextDataId = 0;
+ mCallDataId = 0;
+ }
+
+ boolean isLocalModified() {
+ return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
+ }
+
+ void setTextDataId(long id) {
+ if(id <= 0) {
+ throw new IllegalArgumentException("Text data id should larger than 0");
+ }
+ mTextDataId = id;
+ }
+
+ void setCallDataId(long id) {
+ if (id <= 0) {
+ throw new IllegalArgumentException("Call data id should larger than 0");
+ }
+ 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());
+ }
+
+ void setTextData(String key, String value) {
+ mTextDataValues.put(key, value);
+ mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
+ mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
+ }
+
+ Uri pushIntoContentResolver(Context context, long noteId) {
+ /**
+ * Check for safety
+ */
+ if (noteId <= 0) {
+ throw new IllegalArgumentException("Wrong note id:" + noteId);
+ }
+
+ ArrayList operationList = new ArrayList();
+ ContentProviderOperation.Builder builder = null;
+
+ 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);
+ try {
+ setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
+ } catch (NumberFormatException e) {
+ Log.e(TAG, "Insert new text data fail with noteId" + noteId);
+ mTextDataValues.clear();
+ return null;
+ }
+ } else {
+ builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
+ Notes.CONTENT_DATA_URI, mTextDataId));
+ builder.withValues(mTextDataValues);
+ operationList.add(builder.build());
+ }
+ mTextDataValues.clear();
+ }
+
+ 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);
+ try {
+ setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
+ } catch (NumberFormatException e) {
+ Log.e(TAG, "Insert new call data fail with noteId" + noteId);
+ mCallDataValues.clear();
+ return null;
+ }
+ } else {
+ 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(
+ Notes.AUTHORITY, operationList);
+ return (results == null || results.length == 0 || results[0] == null) ? null
+ : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
+ } catch (RemoteException e) {
+ Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
+ return null;
+ } catch (OperationApplicationException e) {
+ Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
+ return null;
+ }
+ }
+ return null;
+ }
+ }
+}
diff --git a/java/net/micode/notes/model/WorkingNote.java b/java/net/micode/notes/model/WorkingNote.java
new file mode 100644
index 0000000..a8e6b7b
--- /dev/null
+++ b/java/net/micode/notes/model/WorkingNote.java
@@ -0,0 +1,400 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.model;
+
+import android.appwidget.AppWidgetManager;
+import android.content.ContentUris;
+import android.content.Context;
+import android.database.Cursor;
+import android.text.TextUtils;
+import android.util.Log;
+
+import net.micode.notes.data.Notes;
+import net.micode.notes.data.Notes.CallNote;
+import net.micode.notes.data.Notes.DataColumns;
+import net.micode.notes.data.Notes.DataConstants;
+import net.micode.notes.data.Notes.NoteColumns;
+import net.micode.notes.data.Notes.TextNote;
+
+import net.micode.notes.tool.ResourceParser.NoteBgResources;
+
+
+public class WorkingNote {
+ // Note for the working note
+ private Note mNote;
+ // Note Id
+ private long mNoteId;
+ // Note content
+ private String mContent;
+ // Note mode
+ private int mMode;
+
+ private long mAlertDate;
+
+ private long mModifiedDate;
+
+ private int mBgColorId;
+
+ private int mWidgetId;
+
+ private int mWidgetType;
+
+ 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,
+ DataColumns.MIME_TYPE,
+ DataColumns.DATA1,
+ DataColumns.DATA2,
+ DataColumns.DATA3,
+ DataColumns.DATA4,
+ };
+
+ public static final String[] NOTE_PROJECTION = new String[] {
+ NoteColumns.PARENT_ID,
+ NoteColumns.ALERTED_DATE,
+ NoteColumns.BG_COLOR_ID,
+ NoteColumns.WIDGET_ID,
+ NoteColumns.WIDGET_TYPE,
+ 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;
+ mModifiedDate = System.currentTimeMillis();
+ mFolderId = folderId;
+ mNote = new Note();
+ mNoteId = 0;
+ mIsDeleted = false;
+ mMode = 0;
+ 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();
+ }
+
+ private void loadNote() {
+ Cursor cursor = mContext.getContentResolver().query(
+ ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
+ null, null);
+
+ if (cursor != null) {
+ if (cursor.moveToFirst()) {
+ mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
+ mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
+ mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
+ mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
+ mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
+ mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
+ }
+ cursor.close();
+ } else {
+ Log.e(TAG, "No note with id:" + mNoteId);
+ throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
+ }
+ loadNoteData();
+ }
+
+ private void loadNoteData() {
+ Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
+ DataColumns.NOTE_ID + "=?", new String[] {
+ String.valueOf(mNoteId)
+ }, null);
+
+ if (cursor != null) {
+ if (cursor.moveToFirst()) {
+ do {
+ String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
+ if (DataConstants.NOTE.equals(type)) {
+ mContent = cursor.getString(DATA_CONTENT_COLUMN);
+ mMode = cursor.getInt(DATA_MODE_COLUMN);
+ mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
+ } else if (DataConstants.CALL_NOTE.equals(type)) {
+ mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
+ } else {
+ Log.d(TAG, "Wrong note type with type:" + type);
+ }
+ } while (cursor.moveToNext());
+ }
+ cursor.close();
+ } else {
+ Log.e(TAG, "No data with id:" + mNoteId);
+ throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
+ }
+ }
+
+ public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
+ int widgetType, int defaultBgColorId) {
+ WorkingNote note = new WorkingNote(context, folderId);
+ note.setBgColorId(defaultBgColorId);
+ note.setWidgetId(widgetId);
+ note.setWidgetType(widgetType);
+ return note;
+ }
+
+ public static WorkingNote load(Context context, long id) {
+ return new WorkingNote(context, id, 0);
+ }
+
+ public synchronized boolean saveNote() {
+ if (mIsDeleted && existInDatabase()) {
+ // 如果便签已被标记为删除且存在于数据库中,则执行删除操作
+ int rows = mContext.getContentResolver().delete(
+ ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId),
+ null, null);
+ if (rows > 0) {
+ Log.d(TAG, "Deleted empty note with id:" + mNoteId);
+ } else {
+ Log.e(TAG, "Failed to delete empty note with id:" + mNoteId);
+ }
+ return true;
+ }
+
+ if (isWorthSaving()) {
+ if (!existInDatabase()) {
+ if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
+ Log.e(TAG, "Create new note fail with id:" + mNoteId);
+ return false;
+ }
+ }
+
+ // 更新便签数据
+ mNote.setTextData(DataColumns.CONTENT, mContent);
+
+ // 同步到数据库
+ boolean result = 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) {
+ mNoteSettingStatusListener.onWidgetChanged();
+ }
+ return result;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean existInDatabase() {
+ return mNoteId > 0;
+ }
+
+ private boolean isWorthSaving() {
+ if (mIsDeleted) {
+ return false;
+ }
+ // 如果便签不存在于数据库且内容为空,则不值得保存
+ if (!existInDatabase() && TextUtils.isEmpty(mContent)) {
+ return false;
+ }
+ // 如果便签已存在于数据库但内容为空,则需要删除它
+ if (existInDatabase() && TextUtils.isEmpty(mContent)) {
+ // 标记为需要删除
+ mIsDeleted = true;
+ return false;
+ }
+ // 如果便签已存在于数据库但未被修改,则不需要保存
+ if (existInDatabase() && !mNote.isLocalModified()) {
+ return false;
+ }
+ return true;
+ }
+
+ public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
+ mNoteSettingStatusListener = l;
+ }
+
+ public void setAlertDate(long date, boolean set) {
+ if (date != mAlertDate) {
+ mAlertDate = date;
+ mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
+ }
+ if (mNoteSettingStatusListener != null) {
+ mNoteSettingStatusListener.onClockAlertChanged(date, set);
+ }
+ }
+
+ public void markDeleted(boolean mark) {
+ mIsDeleted = mark;
+ if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
+ && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
+ mNoteSettingStatusListener.onWidgetChanged();
+ }
+ }
+
+ public void setBgColorId(int id) {
+ if (id != mBgColorId) {
+ mBgColorId = id;
+ if (mNoteSettingStatusListener != null) {
+ mNoteSettingStatusListener.onBackgroundColorChanged();
+ }
+ mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
+ }
+ }
+
+ public void setCheckListMode(int mode) {
+ if (mMode != mode) {
+ if (mNoteSettingStatusListener != null) {
+ mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
+ }
+ mMode = mode;
+ mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
+ }
+ }
+
+ public void setWidgetType(int type) {
+ if (type != mWidgetType) {
+ mWidgetType = type;
+ mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
+ }
+ }
+
+ public void setWidgetId(int id) {
+ if (id != mWidgetId) {
+ mWidgetId = id;
+ mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
+ }
+ }
+
+ public void setWorkingText(String text) {
+ if (!TextUtils.equals(mContent, text)) {
+ mContent = text;
+ mNote.setTextData(DataColumns.CONTENT, mContent);
+ }
+ }
+
+ 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);
+ }
+
+ public String getContent() {
+ return mContent;
+ }
+
+ public long getAlertDate() {
+ return mAlertDate;
+ }
+
+ public long getModifiedDate() {
+ return mModifiedDate;
+ }
+
+ public int getBgColorResId() {
+ return NoteBgResources.getNoteBgResource(mBgColorId);
+ }
+
+ public int getBgColorId() {
+ return mBgColorId;
+ }
+
+ public int getTitleBgResId() {
+ return NoteBgResources.getNoteTitleBgResource(mBgColorId);
+ }
+
+ public int getCheckListMode() {
+ return mMode;
+ }
+
+ public long getNoteId() {
+ return mNoteId;
+ }
+
+ public long getFolderId() {
+ return mFolderId;
+ }
+
+ 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);
+ }
+}
diff --git a/src/notes/tool/BackupUtils.java b/java/net/micode/notes/tool/BackupUtils.java
similarity index 99%
rename from src/notes/tool/BackupUtils.java
rename to java/net/micode/notes/tool/BackupUtils.java
index b9f0b86..bc1dfff 100644
--- a/src/notes/tool/BackupUtils.java
+++ b/java/net/micode/notes/tool/BackupUtils.java
@@ -355,8 +355,7 @@ public class BackupUtils {
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, // 便签表
NOTE_PROJECTION, // 查询字段
- "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
- + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER,
null, // 查询参数
null // 排序
diff --git a/src/notes/tool/DataUtils.java b/java/net/micode/notes/tool/DataUtils.java
similarity index 96%
rename from src/notes/tool/DataUtils.java
rename to java/net/micode/notes/tool/DataUtils.java
index 4c6ecdd..9eec99f 100644
--- a/src/notes/tool/DataUtils.java
+++ b/java/net/micode/notes/tool/DataUtils.java
@@ -181,13 +181,12 @@ public class DataUtils {
* @return 用户文件夹数量
*/
public static int getUserFolderCount(ContentResolver resolver) {
- // 查询条件:类型为文件夹 且 不在回收站中
+ // 查询条件:类型为文件夹
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" }, // 只查询数量
- NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", // 查询条件
+ NoteColumns.TYPE + "=?", // 查询条件
new String[] {
- String.valueOf(Notes.TYPE_FOLDER), // 参数1:文件夹类型
- String.valueOf(Notes.ID_TRASH_FOLER) // 参数2:排除回收站
+ String.valueOf(Notes.TYPE_FOLDER) // 参数1:文件夹类型
},
null);
@@ -218,7 +217,7 @@ public class DataUtils {
// 查询指定便签
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, // 查询所有列
- NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
+ NoteColumns.TYPE + "=?",
new String [] {String.valueOf(type)}, // 类型参数
null);
@@ -284,10 +283,9 @@ public class DataUtils {
* @return true: 已存在; false: 不存在
*/
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 + "=?", // SNIPPET字段存储文件夹名称
new String[] { name }, null);
diff --git a/src/notes/tool/GTaskStringUtils.java b/java/net/micode/notes/tool/GTaskStringUtils.java
similarity index 100%
rename from src/notes/tool/GTaskStringUtils.java
rename to java/net/micode/notes/tool/GTaskStringUtils.java
diff --git a/src/notes/tool/ResourceParser.java b/java/net/micode/notes/tool/ResourceParser.java
similarity index 99%
rename from src/notes/tool/ResourceParser.java
rename to java/net/micode/notes/tool/ResourceParser.java
index 13b5cdb..af9099f 100644
--- a/src/notes/tool/ResourceParser.java
+++ b/java/net/micode/notes/tool/ResourceParser.java
@@ -115,7 +115,7 @@ public class ResourceParser {
*/
public static int getDefaultBgId(Context context) {
// 从偏好设置读取是否启用随机背景颜色
- if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
+ if (context.getSharedPreferences(NotesPreferenceActivity.PREFERENCE_NAME, Context.MODE_PRIVATE).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, // 偏好设置键名
false)) { // 默认值为false(不随机)
// 随机选择一种颜色
diff --git a/java/net/micode/notes/tool/SearchHistoryManager.java b/java/net/micode/notes/tool/SearchHistoryManager.java
new file mode 100644
index 0000000..d33a004
--- /dev/null
+++ b/java/net/micode/notes/tool/SearchHistoryManager.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.micode.notes.tool;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.text.TextUtils;
+import android.util.Log;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * SearchHistoryManager - 搜索历史记录管理类
+ * 使用SharedPreferences存储搜索历史记录
+ */
+public class SearchHistoryManager {
+ private static final String TAG = "SearchHistoryManager";
+
+ // SharedPreferences文件名
+ private static final String PREFERENCE_NAME = "search_history";
+
+ // 搜索历史键
+ private static final String KEY_SEARCH_HISTORY = "search_history";
+
+ // 最大历史记录数量
+ private static final int MAX_HISTORY_COUNT = 10;
+
+ // 单例实例
+ private static SearchHistoryManager sInstance;
+
+ // SharedPreferences实例
+ private SharedPreferences mSharedPreferences;
+
+ /**
+ * 私有构造函数
+ * @param context 上下文
+ */
+ private SearchHistoryManager(Context context) {
+ mSharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
+ }
+
+ /**
+ * 获取单例实例
+ * @param context 上下文
+ * @return SearchHistoryManager实例
+ */
+ public static synchronized SearchHistoryManager getInstance(Context context) {
+ if (sInstance == null) {
+ sInstance = new SearchHistoryManager(context.getApplicationContext());
+ }
+ return sInstance;
+ }
+
+ /**
+ * 保存搜索关键词到历史记录
+ * @param keyword 搜索关键词
+ */
+ public void saveSearchKeyword(String keyword) {
+ if (TextUtils.isEmpty(keyword)) {
+ return;
+ }
+
+ // 获取现有历史记录
+ List historyList = getSearchHistoryList();
+
+ // 如果已存在,移除旧的位置
+ if (historyList.contains(keyword)) {
+ historyList.remove(keyword);
+ }
+
+ // 添加到最前面
+ historyList.add(0, keyword);
+
+ // 限制历史记录数量
+ if (historyList.size() > MAX_HISTORY_COUNT) {
+ historyList = historyList.subList(0, MAX_HISTORY_COUNT);
+ }
+
+ // 保存到SharedPreferences
+ saveHistoryList(historyList);
+ }
+
+ /**
+ * 获取搜索历史记录列表
+ * @return 搜索历史记录列表
+ */
+ public List getSearchHistoryList() {
+ List historyList = new ArrayList<>();
+
+ try {
+ String historyJson = mSharedPreferences.getString(KEY_SEARCH_HISTORY, "[]");
+ JSONArray jsonArray = new JSONArray(historyJson);
+
+ for (int i = 0; i < jsonArray.length(); i++) {
+ historyList.add(jsonArray.getString(i));
+ }
+ } catch (JSONException e) {
+ Log.e(TAG, "Failed to parse search history: " + e.getMessage());
+ }
+
+ return historyList;
+ }
+
+ /**
+ * 清除所有搜索历史记录
+ */
+ public void clearSearchHistory() {
+ mSharedPreferences.edit().remove(KEY_SEARCH_HISTORY).apply();
+ }
+
+ /**
+ * 保存历史记录列表到SharedPreferences
+ * @param historyList 历史记录列表
+ */
+ private void saveHistoryList(List historyList) {
+ try {
+ JSONArray jsonArray = new JSONArray(historyList);
+ mSharedPreferences.edit().putString(KEY_SEARCH_HISTORY, jsonArray.toString()).apply();
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to save search history: " + e.getMessage());
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/notes/ui/AlarmAlertActivity.java b/java/net/micode/notes/ui/AlarmAlertActivity.java
similarity index 100%
rename from src/notes/ui/AlarmAlertActivity.java
rename to java/net/micode/notes/ui/AlarmAlertActivity.java
diff --git a/src/notes/ui/AlarmInitReceiver.java b/java/net/micode/notes/ui/AlarmInitReceiver.java
similarity index 100%
rename from src/notes/ui/AlarmInitReceiver.java
rename to java/net/micode/notes/ui/AlarmInitReceiver.java
diff --git a/src/notes/ui/AlarmReceiver.java b/java/net/micode/notes/ui/AlarmReceiver.java
similarity index 100%
rename from src/notes/ui/AlarmReceiver.java
rename to java/net/micode/notes/ui/AlarmReceiver.java
diff --git a/src/notes/ui/DateTimePicker.java b/java/net/micode/notes/ui/DateTimePicker.java
similarity index 100%
rename from src/notes/ui/DateTimePicker.java
rename to java/net/micode/notes/ui/DateTimePicker.java
diff --git a/src/notes/ui/DateTimePickerDialog.java b/java/net/micode/notes/ui/DateTimePickerDialog.java
similarity index 100%
rename from src/notes/ui/DateTimePickerDialog.java
rename to java/net/micode/notes/ui/DateTimePickerDialog.java
diff --git a/src/notes/ui/DropdownMenu.java b/java/net/micode/notes/ui/DropdownMenu.java
similarity index 100%
rename from src/notes/ui/DropdownMenu.java
rename to java/net/micode/notes/ui/DropdownMenu.java
diff --git a/src/notes/ui/FoldersListAdapter.java b/java/net/micode/notes/ui/FoldersListAdapter.java
similarity index 100%
rename from src/notes/ui/FoldersListAdapter.java
rename to java/net/micode/notes/ui/FoldersListAdapter.java
diff --git a/src/notes/ui/NoteEditActivity.java b/java/net/micode/notes/ui/NoteEditActivity.java
similarity index 91%
rename from src/notes/ui/NoteEditActivity.java
rename to java/net/micode/notes/ui/NoteEditActivity.java
index 0f28da1..03fedc5 100644
--- a/src/notes/ui/NoteEditActivity.java
+++ b/java/net/micode/notes/ui/NoteEditActivity.java
@@ -35,11 +35,15 @@ import android.graphics.Paint; // 画笔,用于文本样式
import android.os.Bundle; // 状态保存
import android.preference.PreferenceManager; // 偏好设置管理器
// Android文本处理
+import android.text.Editable; // 可编辑文本
import android.text.Spannable; // 可设置样式的文本
import android.text.SpannableString; // 可设置样式的字符串
import android.text.TextUtils; // 文本工具
+import android.text.TextWatcher; // 文本变化监听
import android.text.format.DateUtils; // 日期工具
import android.text.style.BackgroundColorSpan; // 背景色样式
+// Android网络
+import android.net.Uri; // URI工具
import android.util.Log; // 日志工具
// Android视图
import android.view.LayoutInflater; // 布局加载器
@@ -71,6 +75,8 @@ import net.micode.notes.model.WorkingNote.NoteSettingChangedListener; // 便签
import net.micode.notes.tool.DataUtils; // 数据工具
import net.micode.notes.tool.ResourceParser; // 资源解析器
import net.micode.notes.tool.ResourceParser.TextAppearanceResources; // 文本外观资源
+import net.micode.notes.tool.SearchHistoryManager; // 搜索历史管理器
+
// 应用对话框
import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener; // 日期时间设置监听
// 应用自定义控件
@@ -82,6 +88,7 @@ import net.micode.notes.widget.NoteWidgetProvider_4x; // 4x小部件
// Java集合
import java.util.HashMap; // 哈希映射
import java.util.HashSet; // 哈希集合
+import java.util.List; // 列表接口
import java.util.Map; // 映射接口
// Java正则表达式
import java.util.regex.Matcher; // 正则匹配器
@@ -181,6 +188,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
private EditText mNoteEditor; // 便签编辑器
private View mNoteEditorPanel; // 编辑器面板
private LinearLayout mEditTextList; // 列表模式编辑容器
+ private TextView mWordCountView; // 字数统计视图
// 业务模型
private WorkingNote mWorkingNote; // 工作便签模型
@@ -196,6 +204,9 @@ public class NoteEditActivity extends Activity implements OnClickListener,
// 清单模式常量
public static final String TAG_CHECKED = String.valueOf('\u221A'); // 已勾选符号 √
public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); // 未勾选符号 □
+
+ // 请求码常量
+ private static final int REQUEST_CODE_IMAGE_SELECTION = 1;
// 搜索高亮相关
private String mUserQuery; // 用户搜索关键词
@@ -263,6 +274,9 @@ public class NoteEditActivity extends Activity implements OnClickListener,
if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);
+
+ // 保存搜索关键词到历史记录
+ SearchHistoryManager.getInstance(this).saveSearchKeyword(mUserQuery);
}
// 检查便签是否存在
@@ -387,6 +401,9 @@ public class NoteEditActivity extends Activity implements OnClickListener,
// 显示提醒信息
showAlertHeader();
+
+ // 更新字数统计
+ updateWordCount();
}
/**
@@ -498,6 +515,25 @@ public class NoteEditActivity extends Activity implements OnClickListener,
// 编辑视图
mNoteEditor = (EditText) findViewById(R.id.note_edit_view);
mNoteEditorPanel = findViewById(R.id.sv_note_edit);
+
+ // 字数统计视图
+ mWordCountView = (TextView) findViewById(R.id.tv_word_count);
+
+ // 设置文本变化监听
+ mNoteEditor.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ updateWordCount();
+ }
+
+ @Override
+ public void afterTextChanged(Editable s) {
+ }
+ });
// 背景选择器
mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);
@@ -514,7 +550,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
};
// 偏好设置
- mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
+ mSharedPrefs = getSharedPreferences(NotesPreferenceActivity.PREFERENCE_NAME, Context.MODE_PRIVATE);
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);
// 修复字体大小ID可能越界的bug
@@ -541,6 +577,25 @@ public class NoteEditActivity extends Activity implements OnClickListener,
clearSettingState();
}
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (requestCode == REQUEST_CODE_IMAGE_SELECTION && resultCode == RESULT_OK) {
+ if (data != null && data.getData() != null) {
+ // 获取选中图片的Uri
+ Uri imageUri = data.getData();
+ // 将图片Uri插入到当前编辑位置
+ String imageTag = "[IMAGE:" + imageUri.toString() + "]";
+ int currentPosition = mNoteEditor.getSelectionStart();
+ Editable text = mNoteEditor.getText();
+ text.insert(currentPosition, imageTag);
+ // 保存便签内容
+ getWorkingText();
+ }
+ } else {
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+ }
+
// ======================= 小部件更新 =======================
/**
@@ -732,6 +787,11 @@ public class NoteEditActivity extends Activity implements OnClickListener,
setReminder();
} else if (itemId == R.id.menu_delete_remind) {
mWorkingNote.setAlertDate(0, false);
+ } else if (itemId == R.id.menu_insert_image) {
+ // 启动图片选择器
+ Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
+ intent.setType("image/*");
+ startActivityForResult(intent, REQUEST_CODE_IMAGE_SELECTION);
} else {
// 默认分支(原default)
}
@@ -781,6 +841,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
startActivity(intent);
}
+
+
+
+
+ /**
+ * 显示Toast消息
+ * @param resId 字符串资源ID
+ */
+ // 已删除重复的showToast方法,使用第1383行定义的更灵活的方法
+
/**
* 删除当前便签
*/
@@ -793,15 +863,9 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} 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");
- }
+ // 统一使用永久删除方式
+ if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) {
+ Log.e(TAG, "Delete Note error");
}
}
mWorkingNote.markDeleted(true);
@@ -1006,6 +1070,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} else {
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE);
}
+ // 更新字数统计
+ updateWordCount();
}
// ======================= 清单模式变化回调 =======================
@@ -1027,6 +1093,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mEditTextList.setVisibility(View.GONE);
mNoteEditor.setVisibility(View.VISIBLE);
}
+ // 更新字数统计
+ updateWordCount();
}
// ======================= 获取工作文本 =======================
@@ -1063,6 +1131,28 @@ public class NoteEditActivity extends Activity implements OnClickListener,
// ======================= 保存便签 =======================
+ /**
+ * 更新字数统计
+ * 根据当前模式计算并显示字数
+ */
+ private void updateWordCount() {
+ int wordCount = 0;
+ if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
+ // 清单模式:计算所有列表项的字数
+ StringBuilder content = 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);
+ content.append(edit.getText().toString());
+ }
+ wordCount = content.length();
+ } else {
+ // 普通模式:直接计算文本长度
+ wordCount = mNoteEditor.getText().length();
+ }
+ mWordCountView.setText(String.valueOf(wordCount));
+ }
+
/**
* 保存便签
* @return true: 保存成功; false: 保存失败
diff --git a/src/notes/ui/NoteEditText.java b/java/net/micode/notes/ui/NoteEditText.java
similarity index 73%
rename from src/notes/ui/NoteEditText.java
rename to java/net/micode/notes/ui/NoteEditText.java
index d07dbe2..c63a751 100644
--- a/src/notes/ui/NoteEditText.java
+++ b/java/net/micode/notes/ui/NoteEditText.java
@@ -21,6 +21,7 @@ package net.micode.notes.ui;
// ======================= 导入区域 =======================
// Android基础
import android.content.Context; // 上下文
+import android.content.ContentResolver; // 内容解析器
import android.graphics.Rect; // 矩形区域
// Android文本处理
import android.text.Layout; // 文本布局
@@ -36,8 +37,22 @@ import android.view.KeyEvent; // 按键事件
import android.view.MenuItem; // 菜单项
import android.view.MenuItem.OnMenuItemClickListener; // 菜单项点击监听
import android.view.MotionEvent; // 触摸事件
+// Android文本处理
+import android.text.InputType; // 输入类型
+import android.text.Spannable; // 可设置样式的文本
+import android.text.SpannableStringBuilder; // 可设置样式的字符串构建器
+import android.text.style.ImageSpan; // 图片样式
+// Android输入法
+import android.view.inputmethod.EditorInfo; // 输入法编辑器信息
// Android控件
-import android.widget.EditText; // 编辑文本控件基类
+import android.widget.EditText; // 编辑文本控件基类
+import android.widget.ImageView; // 图片视图
+// Android图形
+import android.graphics.Bitmap; // 位图
+import android.graphics.BitmapFactory; // 位图工厂
+import android.graphics.drawable.Drawable; // 可绘制对象
+// Android网络
+import android.net.Uri; // URI工具
// 应用内部资源
import net.micode.notes.R; // 资源文件R类
@@ -127,7 +142,7 @@ public class NoteEditText extends EditText {
* @param context 上下文
*/
public NoteEditText(Context context) {
- super(context, null);
+ this(context, null);
mIndex = 0; // 默认索引为0
}
@@ -137,7 +152,7 @@ public class NoteEditText extends EditText {
* @param attrs 属性集
*/
public NoteEditText(Context context, AttributeSet attrs) {
- super(context, attrs, android.R.attr.editTextStyle);
+ this(context, attrs, android.R.attr.editTextStyle);
}
/**
@@ -148,7 +163,98 @@ public class NoteEditText extends EditText {
*/
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
- // TODO: 可在此处添加额外初始化代码
+ // 确保输入法支持中文输入
+ setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
+ setImeOptions(EditorInfo.IME_ACTION_NONE);
+ }
+
+ /**
+ * 从URI加载图片
+ * @param uri 图片URI
+ * @return 加载的Bitmap对象
+ */
+ private Bitmap loadImageFromUri(Uri uri) {
+ try {
+ ContentResolver resolver = getContext().getContentResolver();
+ Bitmap bitmap = BitmapFactory.decodeStream(resolver.openInputStream(uri));
+ if (bitmap != null) {
+ // 调整图片大小以适应编辑框
+ int maxWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
+ if (bitmap.getWidth() > maxWidth) {
+ float scale = (float) maxWidth / bitmap.getWidth();
+ int newHeight = (int) (bitmap.getHeight() * scale);
+ bitmap = Bitmap.createScaledBitmap(bitmap, maxWidth, newHeight, true);
+ }
+ }
+ return bitmap;
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to load image from URI: " + uri, e);
+ return null;
+ }
+ }
+
+ /**
+ * 解析文本中的[IMAGE:uri]标签并替换为图片
+ * @param text 包含图片标签的文本
+ * @return 处理后的SpannableStringBuilder,包含图片
+ */
+ private SpannableStringBuilder parseImageTags(CharSequence text) {
+ SpannableStringBuilder builder = new SpannableStringBuilder(text);
+ String content = text.toString();
+ int startIndex = 0;
+
+ while (true) {
+ startIndex = content.indexOf("[IMAGE:", startIndex);
+ if (startIndex == -1) break;
+
+ int endIndex = content.indexOf("]", startIndex);
+ if (endIndex == -1) break;
+
+ String imageTag = content.substring(startIndex, endIndex + 1);
+ String imageUriStr = imageTag.substring(7, imageTag.length() - 1); // 去掉[IMAGE:和]
+
+ try {
+ Uri imageUri = Uri.parse(imageUriStr);
+ Bitmap bitmap = loadImageFromUri(imageUri);
+
+ if (bitmap != null) {
+ // 创建一个占位符文本,用于放置图片
+ String placeholder = "[图片]";
+ int placeholderLength = placeholder.length();
+
+ // 替换图片标签为占位符
+ builder.replace(startIndex, endIndex + 1, placeholder);
+
+ // 创建ImageSpan并添加到占位符位置
+ ImageSpan imageSpan = new ImageSpan(getContext(), bitmap);
+ builder.setSpan(imageSpan, startIndex, startIndex + placeholderLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
+
+ // 更新content和startIndex以继续处理
+ content = builder.toString();
+ startIndex += placeholderLength;
+ } else {
+ startIndex = endIndex + 1;
+ }
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to parse image URI: " + imageUriStr, e);
+ startIndex = endIndex + 1;
+ }
+ }
+
+ return builder;
+ }
+
+ /**
+ * 重写setText方法,解析图片标签并显示图片
+ */
+ @Override
+ public void setText(CharSequence text, BufferType type) {
+ if (text != null) {
+ SpannableStringBuilder builder = parseImageTags(text);
+ super.setText(builder, BufferType.SPANNABLE);
+ } else {
+ super.setText(text, type);
+ }
}
// ======================= 设置方法 =======================
diff --git a/src/notes/ui/NoteItemData.java b/java/net/micode/notes/ui/NoteItemData.java
similarity index 96%
rename from src/notes/ui/NoteItemData.java
rename to java/net/micode/notes/ui/NoteItemData.java
index 2b970e5..c3c56f2 100644
--- a/src/notes/ui/NoteItemData.java
+++ b/java/net/micode/notes/ui/NoteItemData.java
@@ -58,6 +58,7 @@ public class NoteItemData {
NoteColumns.TYPE, // 9 - 便签类型
NoteColumns.WIDGET_ID, // 10 - 小部件ID
NoteColumns.WIDGET_TYPE, // 11 - 小部件类型
+ NoteColumns.PINNED // 12 - 是否置顶
};
// ======================= 字段索引常量 =======================
@@ -75,6 +76,7 @@ public class NoteItemData {
private static final int TYPE_COLUMN = 9; // 类型字段索引
private static final int WIDGET_ID_COLUMN = 10; // 小部件ID字段索引
private static final int WIDGET_TYPE_COLUMN = 11; // 小部件类型字段索引
+ private static final int PINNED_COLUMN = 12; // 是否置顶字段索引
// ======================= 数据成员 =======================
@@ -91,6 +93,7 @@ public class NoteItemData {
private int mType; // 便签类型
private int mWidgetId; // 小部件ID
private int mWidgetType; // 小部件类型
+ private boolean mPinned; // 是否置顶
// 通话记录相关
private String mName; // 联系人姓名
@@ -131,6 +134,7 @@ public class NoteItemData {
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
+ mPinned = (cursor.getInt(PINNED_COLUMN) > 0) ? true : false;
// 2. 清理摘要中的清单标记
// 移除已勾选(√)和未勾选(□)标记,只显示纯文本
@@ -356,6 +360,16 @@ public class NoteItemData {
public int getWidgetType() {
return mWidgetType;
}
+
+ /**
+ * 获取便签是否置顶
+ * @return true: 置顶, false: 不置顶
+ */
+ public boolean isPinned() {
+ return mPinned;
+ }
+
+
/**
* 获取小部件ID
diff --git a/src/notes/ui/NotesListActivity.java b/java/net/micode/notes/ui/NotesListActivity.java
similarity index 87%
rename from src/notes/ui/NotesListActivity.java
rename to java/net/micode/notes/ui/NotesListActivity.java
index 0081235..a5349ff 100644
--- a/src/notes/ui/NotesListActivity.java
+++ b/java/net/micode/notes/ui/NotesListActivity.java
@@ -62,6 +62,7 @@ import android.widget.AdapterView.OnItemClickListener; // 列表项点击监听
import android.widget.AdapterView.OnItemLongClickListener; // 列表项长按监听
import android.widget.Button; // 按钮
import android.widget.EditText; // 编辑框
+import android.widget.ImageView; // 图片视图
import android.widget.ListView; // 列表视图
import android.widget.PopupMenu; // 弹出菜单
import android.widget.TextView; // 文本视图
@@ -72,6 +73,7 @@ import net.micode.notes.R; // 资源文件R类
// 应用数据模型
import net.micode.notes.data.Notes; // Notes主类
import net.micode.notes.data.Notes.NoteColumns; // 便签表列定义
+import net.micode.notes.data.NotesDatabaseHelper; // 数据库帮助类
// 应用同步服务
import net.micode.notes.gtask.remote.GTaskSyncService; // Google任务同步服务
// 应用业务模型
@@ -79,6 +81,7 @@ import net.micode.notes.model.WorkingNote; // 工作便签模型
// 应用工具
import net.micode.notes.tool.BackupUtils; // 备份工具
import net.micode.notes.tool.DataUtils; // 数据工具
+
import net.micode.notes.tool.ResourceParser; // 资源解析器
// 应用适配器
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; // 小部件属性
@@ -93,6 +96,8 @@ import java.io.InputStream; // 输入流
import java.io.InputStreamReader; // 输入流读取器
// Java集合
import java.util.HashSet; // 哈希集合
+import java.util.List; // 列表接口
+import java.util.Map; // 映射接口
// ======================= 便签列表主Activity =======================
/**
@@ -113,11 +118,17 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
/** 文件夹列表查询令牌 - 查询所有文件夹(用于移动操作) */
private static final int FOLDER_LIST_QUERY_TOKEN = 1;
- // ======================= 上下文菜单项ID常量 =======================
+ // ======================= 文件夹上下文菜单常量 =======================
private static final int MENU_FOLDER_DELETE = 0; // 删除文件夹
private static final int MENU_FOLDER_VIEW = 1; // 查看文件夹
private static final int MENU_FOLDER_CHANGE_NAME = 2; // 重命名文件夹
+
+ // ======================= 便签上下文菜单常量 =======================
+
+ private static final int MENU_NOTE_PIN = 3; // 置顶便签
+ private static final int MENU_NOTE_UNPIN = 4; // 取消置顶便签
+ private static final int MENU_NOTE_BATCH_SELECT = 5; // 批量选择
// ======================= 偏好设置常量 =======================
@@ -183,6 +194,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
/** 当前焦点便签数据项 - 用于上下文菜单和长按操作 */
private NoteItemData mFocusNoteDataItem;
+ /** 当前选中的标签ID - 用于按标签筛选便签,-1表示不筛选 */
+
+
// ======================= 数据库查询条件常量 =======================
/** 普通文件夹查询条件 - 查询指定父文件夹下的便签 */
@@ -243,7 +257,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
* 首次启动时从R.raw.introduction读取介绍文本并创建便签
*/
private void setAppInfoFromRawRes() {
- SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
+ SharedPreferences sp = getSharedPreferences(NotesPreferenceActivity.PREFERENCE_NAME, Context.MODE_PRIVATE);
// 检查是否已添加过介绍
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
StringBuilder sb = new StringBuilder();
@@ -326,8 +340,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mDispatchY = 0;
mOriginY = 0;
mTitleBar = (TextView) findViewById(R.id.tv_title_bar);
+
mState = ListEditState.NOTE_LIST; // 初始状态为便签列表
mModeCallBack = new ModeCallback(); // 创建多选模式回调
+
+ // 更新标题栏
+ updateTitleBar();
}
// ======================= 多选模式回调类 =======================
@@ -358,6 +376,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mMoveMenu.setVisible(true);
mMoveMenu.setOnMenuItemClickListener(this);
}
+
+ // 设置置顶和取消置顶菜单项的点击监听器
+ MenuItem pinMenuItem = menu.findItem(R.id.pin);
+ MenuItem unpinMenuItem = menu.findItem(R.id.unpin);
+ pinMenuItem.setOnMenuItemClickListener(this);
+ unpinMenuItem.setOnMenuItemClickListener(this);
+
mActionMode = mode;
mNotesListAdapter.setChoiceMode(true); // 进入选择模式
mNotesListView.setLongClickable(false); // 禁用长按
@@ -473,6 +498,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} else if (itemId == R.id.move) {
// 查询目标文件夹
startQueryDestinationFolders();
+ } else if (itemId == R.id.pin) {
+ // 批量置顶选中的便签
+ batchPinNotes(true);
+ } else if (itemId == R.id.unpin) {
+ // 批量取消置顶选中的便签
+ batchPinNotes(false);
} else {
return false;
}
@@ -554,10 +585,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private void startAsyncNotesListQuery() {
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
: NORMAL_SELECTION;
+ String[] selectionArgs = { String.valueOf(mCurrentFolderId) };
+
mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
- Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] {
- String.valueOf(mCurrentFolderId)
- }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
+ Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, selectionArgs,
+ NoteColumns.PINNED + " DESC," + NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
}
/**
@@ -640,21 +672,60 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
protected HashSet doInBackground(Void... unused) {
// 获取选中便签关联的小部件
HashSet widgets = mNotesListAdapter.getSelectedWidget();
- if (!isSyncMode()) {
- // 非同步模式:直接删除
- if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
- .getSelectedItemIds())) {
- // 删除成功
- } else {
- Log.e(TAG, "Delete notes error, should not happens");
+
+ // 统一使用永久删除方式
+ if (!DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter.getSelectedItemIds())) {
+ Log.e(TAG, "Delete notes error, should not happens");
+ }
+
+ return widgets;
+ }
+
+ @Override
+ protected void onPostExecute(HashSet widgets) {
+ // 更新关联的小部件
+ if (widgets != null) {
+ for (AppWidgetAttribute widget : widgets) {
+ if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
+ && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
+ updateWidget(widget.widgetId, widget.widgetType);
+ }
}
- } else {
- // 同步模式:移动到回收站
- if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter
- .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) {
- Log.e(TAG, "Move notes to trash folder error, should not happens");
+ }
+ mModeCallBack.finishActionMode();
+ }
+ }.execute();
+ }
+
+ /**
+ * 批量设置便签置顶状态
+ * @param pin true: 置顶, false: 取消置顶
+ */
+ private void batchPinNotes(final boolean pin) {
+ new AsyncTask>() {
+ protected HashSet doInBackground(Void... unused) {
+ // 获取选中便签关联的小部件
+ HashSet widgets = mNotesListAdapter.getSelectedWidget();
+
+ // 批量设置置顶状态
+ ContentValues values = new ContentValues();
+ values.put(NoteColumns.PINNED, pin ? 1 : 0);
+ values.put(NoteColumns.LOCAL_MODIFIED, 1);
+
+ StringBuffer selection = new StringBuffer();
+ HashSet ids = mNotesListAdapter.getSelectedItemIds();
+ String[] selectionArgs = new String[ids.size()];
+ int i = 0;
+ for (Long id : ids) {
+ if (i > 0) {
+ selection.append(" OR ");
}
+ selection.append(NoteColumns.ID + "=?");
+ selectionArgs[i++] = String.valueOf(id);
}
+
+ mContentResolver.update(Notes.CONTENT_NOTE_URI, values, selection.toString(), selectionArgs);
+
return widgets;
}
@@ -676,6 +747,50 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
// ======================= 删除文件夹 =======================
+ /**
+ * 切换便签置顶状态
+ * @param noteId 便签ID
+ * @param currentPinned 当前置顶状态
+ */
+ private void togglePinNote(long noteId, boolean currentPinned) {
+ ContentValues values = new ContentValues();
+ values.put(NoteColumns.PINNED, currentPinned ? 0 : 1);
+ values.put(NoteColumns.LOCAL_MODIFIED, 1);
+ mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + "=?",
+ new String[] { String.valueOf(noteId) });
+ }
+
+ /**
+ * 显示标签筛选对话框
+ */
+
+
+ /**
+ * 更新标题栏,显示当前文件夹和筛选状态
+ */
+ private void updateTitleBar() {
+ String title = getString(R.string.app_name);
+
+ // 如果不是根文件夹,显示文件夹名称
+ if (mCurrentFolderId != Notes.ID_ROOT_FOLDER) {
+ Cursor cursor = mContentResolver.query(Notes.CONTENT_NOTE_URI,
+ new String[] { NoteColumns.SNIPPET },
+ NoteColumns.ID + "=?",
+ new String[] { String.valueOf(mCurrentFolderId) },
+ null);
+
+ if (cursor != null && cursor.moveToFirst()) {
+ title = cursor.getString(0);
+ cursor.close();
+ }
+ }
+
+ mTitleBar.setText(title);
+ mTitleBar.setVisibility(View.VISIBLE);
+ }
+
+
+
/**
* 删除文件夹
* @param folderId 文件夹ID
@@ -946,6 +1061,22 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
};
+
+ private final OnCreateContextMenuListener mNoteOnCreateContextMenuListener = new OnCreateContextMenuListener() {
+ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
+ if (mFocusNoteDataItem != null) {
+ menu.setHeaderTitle(R.string.app_name);
+ // 根据当前置顶状态添加不同的菜单项
+ if (mFocusNoteDataItem.isPinned()) {
+ menu.add(0, MENU_NOTE_UNPIN, 0, R.string.menu_unpin);
+ } else {
+ menu.add(0, MENU_NOTE_PIN, 0, R.string.menu_pin);
+ }
+ // 添加批量选择菜单项
+ menu.add(0, MENU_NOTE_BATCH_SELECT, 1, R.string.menu_batch_select);
+ }
+ }
+ };
/**
* 上下文菜单关闭
@@ -985,7 +1116,18 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.show();
} else if (itemId == MENU_FOLDER_CHANGE_NAME) {
showCreateOrModifyFolderDialog(false);
+ } else if (itemId == MENU_NOTE_PIN) {
+ togglePinNote(mFocusNoteDataItem.getId(), false);
+ } else if (itemId == MENU_NOTE_UNPIN) {
+ togglePinNote(mFocusNoteDataItem.getId(), true);
+ } else if (itemId == MENU_NOTE_BATCH_SELECT) {
+ // 进入批量选择模式
+ // 启动多选模式
+ mModeCallBack = new ModeCallback();
+ mNotesListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
+ mNotesListView.setMultiChoiceModeListener(mModeCallBack);
}
+
return true;
}
@@ -1202,14 +1344,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
public boolean onItemLongClick(AdapterView> parent, View view, int position, long id) {
if (view instanceof NotesListItem) {
mFocusNoteDataItem = ((NotesListItem) view).getItemData();
- // 便签长按:启动多选模式
- if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {
- if (mNotesListView.startActionMode(mModeCallBack) != null) {
- mModeCallBack.onItemCheckedStateChanged(null, position, id, true);
- mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
- } else {
- Log.e(TAG, "startActionMode fails");
- }
+
+ if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE) {
+ // 便签长按:显示上下文菜单
+ mNotesListView.setOnCreateContextMenuListener(mNoteOnCreateContextMenuListener);
} else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {
// 文件夹长按:显示上下文菜单
mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener);
diff --git a/src/notes/ui/NotesListAdapter.java b/java/net/micode/notes/ui/NotesListAdapter.java
similarity index 100%
rename from src/notes/ui/NotesListAdapter.java
rename to java/net/micode/notes/ui/NotesListAdapter.java
diff --git a/src/notes/ui/NotesListItem.java b/java/net/micode/notes/ui/NotesListItem.java
similarity index 96%
rename from src/notes/ui/NotesListItem.java
rename to java/net/micode/notes/ui/NotesListItem.java
index 342f1f5..ab1ba72 100644
--- a/src/notes/ui/NotesListItem.java
+++ b/java/net/micode/notes/ui/NotesListItem.java
@@ -53,6 +53,9 @@ public class NotesListItem extends LinearLayout {
/** 提醒图标 - 显示便签是否有提醒 */
private ImageView mAlert;
+ /** 置顶图标 - 显示便签是否置顶 */
+ private ImageView mPinned;
+
/** 标题文本 - 显示便签摘要或文件夹名称 */
private TextView mTitle;
@@ -84,6 +87,7 @@ public class NotesListItem extends LinearLayout {
// 2. 查找并保存子视图引用
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
+ mPinned = (ImageView) findViewById(R.id.iv_pinned_icon);
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name);
@@ -216,6 +220,12 @@ public class NotesListItem extends LinearLayout {
} else {
mAlert.setVisibility(View.GONE);
}
+ // 根据是否置顶设置置顶图标
+ if (data.isPinned()) {
+ mPinned.setVisibility(View.VISIBLE);
+ } else {
+ mPinned.setVisibility(View.GONE);
+ }
}
}
diff --git a/src/notes/ui/NotesPreferenceActivity.java b/java/net/micode/notes/ui/NotesPreferenceActivity.java
similarity index 94%
rename from src/notes/ui/NotesPreferenceActivity.java
rename to java/net/micode/notes/ui/NotesPreferenceActivity.java
index 8be7b04..48373b2 100644
--- a/src/notes/ui/NotesPreferenceActivity.java
+++ b/java/net/micode/notes/ui/NotesPreferenceActivity.java
@@ -41,6 +41,7 @@ import android.preference.Preference; // 偏好设置项
import android.preference.Preference.OnPreferenceClickListener; // 偏好设置点击监听
import android.preference.PreferenceActivity; // 偏好设置Activity基类
import android.preference.PreferenceCategory; // 偏好设置分类
+import android.preference.PreferenceManager; // 偏好设置管理器
// Android工具
import android.text.TextUtils; // 文本工具
import android.text.format.DateFormat; // 日期格式化
@@ -49,6 +50,7 @@ import android.view.LayoutInflater; // 布局加载器
import android.view.Menu; // 菜单
import android.view.MenuItem; // 菜单项
import android.view.View; // 视图基类
+import android.widget.ListView; // 列表视图
// Android控件
import android.widget.Button; // 按钮
import android.widget.TextView; // 文本视图
@@ -61,6 +63,8 @@ import net.micode.notes.data.Notes; // Notes主类
import net.micode.notes.data.Notes.NoteColumns; // 便签表列定义
// 应用同步服务
import net.micode.notes.gtask.remote.GTaskSyncService; // Google任务同步服务
+// 应用工具
+import net.micode.notes.tool.SearchHistoryManager; // 搜索历史管理器
// ======================= 便签设置Activity =======================
/**
@@ -114,14 +118,25 @@ public class NotesPreferenceActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
-
- /* 使用应用图标作为导航按钮 */
- getActionBar().setDisplayHomeAsUpEnabled(true);
-
// 从XML加载偏好设置
addPreferencesFromResource(R.xml.preferences);
+
// 获取账户设置分类
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
+
+ // 设置清除搜索历史按钮的点击事件
+ Preference clearSearchHistoryPref = findPreference("pref_key_clear_search_history");
+ if (clearSearchHistoryPref != null) {
+ clearSearchHistoryPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+ public boolean onPreferenceClick(Preference preference) {
+ // 清除搜索历史
+ SearchHistoryManager.getInstance(NotesPreferenceActivity.this).clearSearchHistory();
+ Toast.makeText(NotesPreferenceActivity.this,
+ "Search history cleared", Toast.LENGTH_SHORT).show();
+ return true;
+ }
+ });
+ }
// 创建并注册同步广播接收器
mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter();
@@ -131,7 +146,16 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mOriAccounts = null; // 初始化原始账户列表
// 添加设置界面头部
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
- getListView().addHeaderView(header, null, true);
+ ListView listView = getListView();
+ if (listView != null) {
+ listView.addHeaderView(header, null, true);
+ }
+
+ /* 使用应用图标作为导航按钮 */
+ ActionBar actionBar = getActionBar();
+ if (actionBar != null) {
+ actionBar.setDisplayHomeAsUpEnabled(true);
+ }
}
/**
diff --git a/src/notes/widget/NoteWidgetProvider.java b/java/net/micode/notes/widget/NoteWidgetProvider.java
similarity index 100%
rename from src/notes/widget/NoteWidgetProvider.java
rename to java/net/micode/notes/widget/NoteWidgetProvider.java
diff --git a/src/notes/widget/NoteWidgetProvider_2x.java b/java/net/micode/notes/widget/NoteWidgetProvider_2x.java
similarity index 100%
rename from src/notes/widget/NoteWidgetProvider_2x.java
rename to java/net/micode/notes/widget/NoteWidgetProvider_2x.java
diff --git a/src/notes/widget/NoteWidgetProvider_4x.java b/java/net/micode/notes/widget/NoteWidgetProvider_4x.java
similarity index 100%
rename from src/notes/widget/NoteWidgetProvider_4x.java
rename to java/net/micode/notes/widget/NoteWidgetProvider_4x.java
diff --git a/res/color/primary_text_dark.xml b/res/color/primary_text_dark.xml
new file mode 100644
index 0000000..4fef9ab
--- /dev/null
+++ b/res/color/primary_text_dark.xml
@@ -0,0 +1,77 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/res/color/secondary_text_dark.xml b/res/color/secondary_text_dark.xml
new file mode 100644
index 0000000..eee5cdc
--- /dev/null
+++ b/res/color/secondary_text_dark.xml
@@ -0,0 +1,58 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/res/drawable-hdpi/bg_btn_set_color.png b/res/drawable-hdpi/bg_btn_set_color.png
new file mode 100644
index 0000000..5eb5d44
Binary files /dev/null and b/res/drawable-hdpi/bg_btn_set_color.png differ
diff --git a/res/drawable-hdpi/bg_color_btn_mask.png b/res/drawable-hdpi/bg_color_btn_mask.png
new file mode 100644
index 0000000..100db77
Binary files /dev/null and b/res/drawable-hdpi/bg_color_btn_mask.png differ
diff --git a/res/drawable-hdpi/call_record.png b/res/drawable-hdpi/call_record.png
new file mode 100644
index 0000000..fb88ca4
Binary files /dev/null and b/res/drawable-hdpi/call_record.png differ
diff --git a/res/drawable-hdpi/clock.png b/res/drawable-hdpi/clock.png
new file mode 100644
index 0000000..5f2ae9a
Binary files /dev/null and b/res/drawable-hdpi/clock.png differ
diff --git a/res/drawable-hdpi/dropdown_icon.9.png b/res/drawable-hdpi/dropdown_icon.9.png
new file mode 100644
index 0000000..5525025
Binary files /dev/null and b/res/drawable-hdpi/dropdown_icon.9.png differ
diff --git a/res/drawable-hdpi/edit_blue.9.png b/res/drawable-hdpi/edit_blue.9.png
new file mode 100644
index 0000000..55a1856
Binary files /dev/null and b/res/drawable-hdpi/edit_blue.9.png differ
diff --git a/res/drawable-hdpi/edit_green.9.png b/res/drawable-hdpi/edit_green.9.png
new file mode 100644
index 0000000..2cb2d60
Binary files /dev/null and b/res/drawable-hdpi/edit_green.9.png differ
diff --git a/res/drawable-hdpi/edit_red.9.png b/res/drawable-hdpi/edit_red.9.png
new file mode 100644
index 0000000..bae944a
Binary files /dev/null and b/res/drawable-hdpi/edit_red.9.png differ
diff --git a/res/drawable-hdpi/edit_title_blue.9.png b/res/drawable-hdpi/edit_title_blue.9.png
new file mode 100644
index 0000000..96e6092
Binary files /dev/null and b/res/drawable-hdpi/edit_title_blue.9.png differ
diff --git a/res/drawable-hdpi/edit_title_green.9.png b/res/drawable-hdpi/edit_title_green.9.png
new file mode 100644
index 0000000..08d8644
Binary files /dev/null and b/res/drawable-hdpi/edit_title_green.9.png differ
diff --git a/res/drawable-hdpi/edit_title_red.9.png b/res/drawable-hdpi/edit_title_red.9.png
new file mode 100644
index 0000000..9c430e5
Binary files /dev/null and b/res/drawable-hdpi/edit_title_red.9.png differ
diff --git a/res/drawable-hdpi/edit_title_white.9.png b/res/drawable-hdpi/edit_title_white.9.png
new file mode 100644
index 0000000..19e8d95
Binary files /dev/null and b/res/drawable-hdpi/edit_title_white.9.png differ
diff --git a/res/drawable-hdpi/edit_title_yellow.9.png b/res/drawable-hdpi/edit_title_yellow.9.png
new file mode 100644
index 0000000..bf8f580
Binary files /dev/null and b/res/drawable-hdpi/edit_title_yellow.9.png differ
diff --git a/res/drawable-hdpi/edit_white.9.png b/res/drawable-hdpi/edit_white.9.png
new file mode 100644
index 0000000..918f7a6
Binary files /dev/null and b/res/drawable-hdpi/edit_white.9.png differ
diff --git a/res/drawable-hdpi/edit_yellow.9.png b/res/drawable-hdpi/edit_yellow.9.png
new file mode 100644
index 0000000..10cb642
Binary files /dev/null and b/res/drawable-hdpi/edit_yellow.9.png differ
diff --git a/res/drawable-hdpi/font_large.png b/res/drawable-hdpi/font_large.png
new file mode 100644
index 0000000..78cf2e6
Binary files /dev/null and b/res/drawable-hdpi/font_large.png differ
diff --git a/res/drawable-hdpi/font_normal.png b/res/drawable-hdpi/font_normal.png
new file mode 100644
index 0000000..9de7ced
Binary files /dev/null and b/res/drawable-hdpi/font_normal.png differ
diff --git a/res/drawable-hdpi/font_size_selector_bg.9.png b/res/drawable-hdpi/font_size_selector_bg.9.png
new file mode 100644
index 0000000..be8e64c
Binary files /dev/null and b/res/drawable-hdpi/font_size_selector_bg.9.png differ
diff --git a/res/drawable-hdpi/font_small.png b/res/drawable-hdpi/font_small.png
new file mode 100644
index 0000000..d3ff104
Binary files /dev/null and b/res/drawable-hdpi/font_small.png differ
diff --git a/res/drawable-hdpi/font_super.png b/res/drawable-hdpi/font_super.png
new file mode 100644
index 0000000..85b13a1
Binary files /dev/null and b/res/drawable-hdpi/font_super.png differ
diff --git a/res/drawable-hdpi/icon_app.png b/res/drawable-hdpi/icon_app.png
new file mode 100644
index 0000000..418aadc
Binary files /dev/null and b/res/drawable-hdpi/icon_app.png differ
diff --git a/res/drawable-hdpi/list_background.png b/res/drawable-hdpi/list_background.png
new file mode 100644
index 0000000..087e1f9
Binary files /dev/null and b/res/drawable-hdpi/list_background.png differ
diff --git a/res/drawable-hdpi/list_blue_down.9.png b/res/drawable-hdpi/list_blue_down.9.png
new file mode 100644
index 0000000..b88eebf
Binary files /dev/null and b/res/drawable-hdpi/list_blue_down.9.png differ
diff --git a/res/drawable-hdpi/list_blue_middle.9.png b/res/drawable-hdpi/list_blue_middle.9.png
new file mode 100644
index 0000000..96b1c8b
Binary files /dev/null and b/res/drawable-hdpi/list_blue_middle.9.png differ
diff --git a/res/drawable-hdpi/list_blue_single.9.png b/res/drawable-hdpi/list_blue_single.9.png
new file mode 100644
index 0000000..d7e7206
Binary files /dev/null and b/res/drawable-hdpi/list_blue_single.9.png differ
diff --git a/res/drawable-hdpi/list_blue_up.9.png b/res/drawable-hdpi/list_blue_up.9.png
new file mode 100644
index 0000000..632e88c
Binary files /dev/null and b/res/drawable-hdpi/list_blue_up.9.png differ
diff --git a/res/drawable-hdpi/list_folder.9.png b/res/drawable-hdpi/list_folder.9.png
new file mode 100644
index 0000000..829f61b
Binary files /dev/null and b/res/drawable-hdpi/list_folder.9.png differ
diff --git a/res/drawable-hdpi/list_footer_bg.9.png b/res/drawable-hdpi/list_footer_bg.9.png
new file mode 100644
index 0000000..5325c25
Binary files /dev/null and b/res/drawable-hdpi/list_footer_bg.9.png differ
diff --git a/res/drawable-hdpi/list_green_down.9.png b/res/drawable-hdpi/list_green_down.9.png
new file mode 100644
index 0000000..64a39d9
Binary files /dev/null and b/res/drawable-hdpi/list_green_down.9.png differ
diff --git a/res/drawable-hdpi/list_green_middle.9.png b/res/drawable-hdpi/list_green_middle.9.png
new file mode 100644
index 0000000..897325a
Binary files /dev/null and b/res/drawable-hdpi/list_green_middle.9.png differ
diff --git a/res/drawable-hdpi/list_green_single.9.png b/res/drawable-hdpi/list_green_single.9.png
new file mode 100644
index 0000000..c83405f
Binary files /dev/null and b/res/drawable-hdpi/list_green_single.9.png differ
diff --git a/res/drawable-hdpi/list_green_up.9.png b/res/drawable-hdpi/list_green_up.9.png
new file mode 100644
index 0000000..141f9e1
Binary files /dev/null and b/res/drawable-hdpi/list_green_up.9.png differ
diff --git a/res/drawable-hdpi/list_red_down.9.png b/res/drawable-hdpi/list_red_down.9.png
new file mode 100644
index 0000000..4224309
Binary files /dev/null and b/res/drawable-hdpi/list_red_down.9.png differ
diff --git a/res/drawable-hdpi/list_red_middle.9.png b/res/drawable-hdpi/list_red_middle.9.png
new file mode 100644
index 0000000..9988f17
Binary files /dev/null and b/res/drawable-hdpi/list_red_middle.9.png differ
diff --git a/res/drawable-hdpi/list_red_single.9.png b/res/drawable-hdpi/list_red_single.9.png
new file mode 100644
index 0000000..587c348
Binary files /dev/null and b/res/drawable-hdpi/list_red_single.9.png differ
diff --git a/res/drawable-hdpi/list_red_up.9.png b/res/drawable-hdpi/list_red_up.9.png
new file mode 100644
index 0000000..46b4757
Binary files /dev/null and b/res/drawable-hdpi/list_red_up.9.png differ
diff --git a/res/drawable-hdpi/list_white_down.9.png b/res/drawable-hdpi/list_white_down.9.png
new file mode 100644
index 0000000..29f9d8c
Binary files /dev/null and b/res/drawable-hdpi/list_white_down.9.png differ
diff --git a/res/drawable-hdpi/list_white_middle.9.png b/res/drawable-hdpi/list_white_middle.9.png
new file mode 100644
index 0000000..77a4ab4
Binary files /dev/null and b/res/drawable-hdpi/list_white_middle.9.png differ
diff --git a/res/drawable-hdpi/list_white_single.9.png b/res/drawable-hdpi/list_white_single.9.png
new file mode 100644
index 0000000..3e79189
Binary files /dev/null and b/res/drawable-hdpi/list_white_single.9.png differ
diff --git a/res/drawable-hdpi/list_white_up.9.png b/res/drawable-hdpi/list_white_up.9.png
new file mode 100644
index 0000000..e23cd5c
Binary files /dev/null and b/res/drawable-hdpi/list_white_up.9.png differ
diff --git a/res/drawable-hdpi/list_yellow_down.9.png b/res/drawable-hdpi/list_yellow_down.9.png
new file mode 100644
index 0000000..31cfc1e
Binary files /dev/null and b/res/drawable-hdpi/list_yellow_down.9.png differ
diff --git a/res/drawable-hdpi/list_yellow_middle.9.png b/res/drawable-hdpi/list_yellow_middle.9.png
new file mode 100644
index 0000000..b6549b2
Binary files /dev/null and b/res/drawable-hdpi/list_yellow_middle.9.png differ
diff --git a/res/drawable-hdpi/list_yellow_single.9.png b/res/drawable-hdpi/list_yellow_single.9.png
new file mode 100644
index 0000000..3faf507
Binary files /dev/null and b/res/drawable-hdpi/list_yellow_single.9.png differ
diff --git a/res/drawable-hdpi/list_yellow_up.9.png b/res/drawable-hdpi/list_yellow_up.9.png
new file mode 100644
index 0000000..4ae791c
Binary files /dev/null and b/res/drawable-hdpi/list_yellow_up.9.png differ
diff --git a/res/drawable-hdpi/menu_delete.png b/res/drawable-hdpi/menu_delete.png
new file mode 100644
index 0000000..ccdfc4b
Binary files /dev/null and b/res/drawable-hdpi/menu_delete.png differ
diff --git a/res/drawable-hdpi/menu_move.png b/res/drawable-hdpi/menu_move.png
new file mode 100644
index 0000000..1140b71
Binary files /dev/null and b/res/drawable-hdpi/menu_move.png differ
diff --git a/res/drawable-hdpi/new_note_normal.png b/res/drawable-hdpi/new_note_normal.png
new file mode 100644
index 0000000..e24e0d1
Binary files /dev/null and b/res/drawable-hdpi/new_note_normal.png differ
diff --git a/res/drawable-hdpi/new_note_pressed.png b/res/drawable-hdpi/new_note_pressed.png
new file mode 100644
index 0000000..c748936
Binary files /dev/null and b/res/drawable-hdpi/new_note_pressed.png differ
diff --git a/res/drawable-hdpi/note_edit_color_selector_panel.png b/res/drawable-hdpi/note_edit_color_selector_panel.png
new file mode 100644
index 0000000..fc49552
Binary files /dev/null and b/res/drawable-hdpi/note_edit_color_selector_panel.png differ
diff --git a/res/drawable-hdpi/notification.png b/res/drawable-hdpi/notification.png
new file mode 100644
index 0000000..b13ab4a
Binary files /dev/null and b/res/drawable-hdpi/notification.png differ
diff --git a/res/drawable-hdpi/search_result.png b/res/drawable-hdpi/search_result.png
new file mode 100644
index 0000000..ff2befd
Binary files /dev/null and b/res/drawable-hdpi/search_result.png differ
diff --git a/res/drawable-hdpi/selected.png b/res/drawable-hdpi/selected.png
new file mode 100644
index 0000000..b889bef
Binary files /dev/null and b/res/drawable-hdpi/selected.png differ
diff --git a/res/drawable-hdpi/title_alert.png b/res/drawable-hdpi/title_alert.png
new file mode 100644
index 0000000..544ee9c
Binary files /dev/null and b/res/drawable-hdpi/title_alert.png differ
diff --git a/res/drawable-hdpi/title_bar_bg.9.png b/res/drawable-hdpi/title_bar_bg.9.png
new file mode 100644
index 0000000..eb6bff0
Binary files /dev/null and b/res/drawable-hdpi/title_bar_bg.9.png differ
diff --git a/res/drawable-hdpi/widget_2x_blue.png b/res/drawable-hdpi/widget_2x_blue.png
new file mode 100644
index 0000000..a1707f4
Binary files /dev/null and b/res/drawable-hdpi/widget_2x_blue.png differ
diff --git a/res/drawable-hdpi/widget_2x_green.png b/res/drawable-hdpi/widget_2x_green.png
new file mode 100644
index 0000000..f86886c
Binary files /dev/null and b/res/drawable-hdpi/widget_2x_green.png differ
diff --git a/res/drawable-hdpi/widget_2x_red.png b/res/drawable-hdpi/widget_2x_red.png
new file mode 100644
index 0000000..0e66c29
Binary files /dev/null and b/res/drawable-hdpi/widget_2x_red.png differ
diff --git a/res/drawable-hdpi/widget_2x_white.png b/res/drawable-hdpi/widget_2x_white.png
new file mode 100644
index 0000000..5f0619a
Binary files /dev/null and b/res/drawable-hdpi/widget_2x_white.png differ
diff --git a/res/drawable-hdpi/widget_2x_yellow.png b/res/drawable-hdpi/widget_2x_yellow.png
new file mode 100644
index 0000000..12d1c2b
Binary files /dev/null and b/res/drawable-hdpi/widget_2x_yellow.png differ
diff --git a/res/drawable-hdpi/widget_4x_blue.png b/res/drawable-hdpi/widget_4x_blue.png
new file mode 100644
index 0000000..9183738
Binary files /dev/null and b/res/drawable-hdpi/widget_4x_blue.png differ
diff --git a/res/drawable-hdpi/widget_4x_green.png b/res/drawable-hdpi/widget_4x_green.png
new file mode 100644
index 0000000..fa8b452
Binary files /dev/null and b/res/drawable-hdpi/widget_4x_green.png differ
diff --git a/res/drawable-hdpi/widget_4x_red.png b/res/drawable-hdpi/widget_4x_red.png
new file mode 100644
index 0000000..62de074
Binary files /dev/null and b/res/drawable-hdpi/widget_4x_red.png differ
diff --git a/res/drawable-hdpi/widget_4x_white.png b/res/drawable-hdpi/widget_4x_white.png
new file mode 100644
index 0000000..a37d67c
Binary files /dev/null and b/res/drawable-hdpi/widget_4x_white.png differ
diff --git a/res/drawable-hdpi/widget_4x_yellow.png b/res/drawable-hdpi/widget_4x_yellow.png
new file mode 100644
index 0000000..d7c5fa4
Binary files /dev/null and b/res/drawable-hdpi/widget_4x_yellow.png differ
diff --git a/res/drawable/new_note.xml b/res/drawable/new_note.xml
new file mode 100644
index 0000000..2154ebc
--- /dev/null
+++ b/res/drawable/new_note.xml
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+
+
diff --git a/res/layout/account_dialog_title.xml b/res/layout/account_dialog_title.xml
new file mode 100644
index 0000000..7717112
--- /dev/null
+++ b/res/layout/account_dialog_title.xml
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/res/layout/add_account_text.xml b/res/layout/add_account_text.xml
new file mode 100644
index 0000000..c799178
--- /dev/null
+++ b/res/layout/add_account_text.xml
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/res/layout/datetime_picker.xml b/res/layout/datetime_picker.xml
new file mode 100644
index 0000000..f10d592
--- /dev/null
+++ b/res/layout/datetime_picker.xml
@@ -0,0 +1,56 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/res/layout/dialog_edit_text.xml b/res/layout/dialog_edit_text.xml
new file mode 100644
index 0000000..361b39a
--- /dev/null
+++ b/res/layout/dialog_edit_text.xml
@@ -0,0 +1,23 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/res/layout/folder_list_item.xml b/res/layout/folder_list_item.xml
new file mode 100644
index 0000000..77e8148
--- /dev/null
+++ b/res/layout/folder_list_item.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/res/layout/note_edit.xml b/res/layout/note_edit.xml
new file mode 100644
index 0000000..3ebe56c
--- /dev/null
+++ b/res/layout/note_edit.xml
@@ -0,0 +1,411 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/res/layout/note_edit_list_item.xml b/res/layout/note_edit_list_item.xml
new file mode 100644
index 0000000..6497c25
--- /dev/null
+++ b/res/layout/note_edit_list_item.xml
@@ -0,0 +1,40 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/res/layout/note_item.xml b/res/layout/note_item.xml
new file mode 100644
index 0000000..eb899ed
--- /dev/null
+++ b/res/layout/note_item.xml
@@ -0,0 +1,89 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/res/layout/note_list.xml b/res/layout/note_list.xml
new file mode 100644
index 0000000..63cf765
--- /dev/null
+++ b/res/layout/note_list.xml
@@ -0,0 +1,68 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/res/layout/note_list_dropdown_menu.xml b/res/layout/note_list_dropdown_menu.xml
new file mode 100644
index 0000000..3fa271d
--- /dev/null
+++ b/res/layout/note_list_dropdown_menu.xml
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/res/layout/note_list_footer.xml b/res/layout/note_list_footer.xml
new file mode 100644
index 0000000..5ca7b22
--- /dev/null
+++ b/res/layout/note_list_footer.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/res/layout/settings_header.xml b/res/layout/settings_header.xml
new file mode 100644
index 0000000..5eb8c50
--- /dev/null
+++ b/res/layout/settings_header.xml
@@ -0,0 +1,41 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/res/layout/widget_2x.xml b/res/layout/widget_2x.xml
new file mode 100644
index 0000000..55970ce
--- /dev/null
+++ b/res/layout/widget_2x.xml
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
diff --git a/res/layout/widget_4x.xml b/res/layout/widget_4x.xml
new file mode 100644
index 0000000..dc9bb51
--- /dev/null
+++ b/res/layout/widget_4x.xml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/res/menu/call_note_edit.xml b/res/menu/call_note_edit.xml
new file mode 100644
index 0000000..02c0528
--- /dev/null
+++ b/res/menu/call_note_edit.xml
@@ -0,0 +1,48 @@
+
+
+
+
+
diff --git a/res/menu/call_record_folder.xml b/res/menu/call_record_folder.xml
new file mode 100644
index 0000000..c664346
--- /dev/null
+++ b/res/menu/call_record_folder.xml
@@ -0,0 +1,23 @@
+
+
+
+
+
diff --git a/res/menu/note_edit.xml b/res/menu/note_edit.xml
new file mode 100644
index 0000000..42440a1
--- /dev/null
+++ b/res/menu/note_edit.xml
@@ -0,0 +1,57 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/res/menu/note_list.xml b/res/menu/note_list.xml
new file mode 100644
index 0000000..42ea736
--- /dev/null
+++ b/res/menu/note_list.xml
@@ -0,0 +1,39 @@
+
+
+
+
+
diff --git a/res/menu/note_list_dropdown.xml b/res/menu/note_list_dropdown.xml
new file mode 100644
index 0000000..7cbaadc
--- /dev/null
+++ b/res/menu/note_list_dropdown.xml
@@ -0,0 +1,20 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/res/menu/note_list_options.xml b/res/menu/note_list_options.xml
new file mode 100644
index 0000000..04a00b9
--- /dev/null
+++ b/res/menu/note_list_options.xml
@@ -0,0 +1,41 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/res/menu/sub_folder.xml b/res/menu/sub_folder.xml
new file mode 100644
index 0000000..b00de26
--- /dev/null
+++ b/res/menu/sub_folder.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/res/raw-zh-rCN/introduction b/res/raw-zh-rCN/introduction
new file mode 100644
index 0000000..7188359
--- /dev/null
+++ b/res/raw-zh-rCN/introduction
@@ -0,0 +1,7 @@
+欢迎使用MIUI便签!
+
+ 无论从软件中直接添加,还是从桌面拖出widget,MIUI便签能让你快速建立和保存便签;
+
+ 除了调整文字大小、便签背景、文件夹等基础功能外,你会发现MIUI便签也提供了清单模式、便签提醒、软件加密、导出到SD卡、同步google task的高级功能,让你的生活记录更加美好和安全;
+
+ 来分享你的使用体验吧:http://www.miui.com/index.php
diff --git a/res/raw/introduction b/res/raw/introduction
new file mode 100644
index 0000000..269cf7b
--- /dev/null
+++ b/res/raw/introduction
@@ -0,0 +1 @@
+Welcome to use MIUI notes!
\ No newline at end of file
diff --git a/res/values-zh-rCN/arrays.xml b/res/values-zh-rCN/arrays.xml
new file mode 100644
index 0000000..114e52e
--- /dev/null
+++ b/res/values-zh-rCN/arrays.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml
new file mode 100644
index 0000000..07915bb
--- /dev/null
+++ b/res/values-zh-rCN/strings.xml
@@ -0,0 +1,119 @@
+
+
+
+
+
+ 便签
+ 便签2x2
+ 便签4x4
+ 没有关联内容,点击新建便签。
+ 访客模式下,便签内容不可见
+ ...
+ 新建便签
+ 已过期
+ yyyyMMdd
+ MM月dd日 kk:mm
+ 知道了
+ 查看
+ 呼叫电话
+ 发送邮件
+ 浏览网页
+ 打开地图
+
+ 新建文件夹
+ 导出文本
+ 同步
+ 取消同步
+ 设置
+ 搜索
+ 删除
+ 移动到文件夹
+ 选中了 %d 项
+ 没有选中项,操作无效
+ 全选
+ 取消全选
+ 文字大小
+ 小
+ 正常
+ 大
+ 超大
+ 进入清单模式
+ 退出清单模式
+ 查看文件夹
+ 刪除文件夹
+ 修改文件夹名称
+ 文件夹 %1$s 已存在,请重新命名
+ 分享
+ 发送到桌面
+ 提醒我
+ 删除提醒
+ 选择文件夹
+ 上一级文件夹
+ 已添加到桌面
+ 删除
+ 确认要删除所选的 %d 条便签吗?
+ 确认要删除该条便签吗?
+ 确认删除文件夹及所包含的便签吗?
+ 已将所选 %1$d 条便签移到 %2$s 文件夹
+
+ SD卡被占用,不能操作
+ 导出文本时发生错误,请检查SD卡
+ 要查看的便签不存在
+ 不能为空便签设置闹钟提醒
+ 不能将空便签发送到桌面
+ 导出成功
+ 导出失败
+ 已将文本文件(%1$s)输出至SD卡(%2$s)目录
+
+ 同步便签...
+ 同步成功
+ 同步失败
+ 同步已取消
+ 与%1$s同步成功
+ 同步失败,请检查网络和帐号设置
+ 同步失败,发生内部错误
+ 同步已取消
+ 登录%1$s...
+ 正在获取服务器便签列表...
+ 正在同步本地便签...
+
+ 设置
+ 同步账号
+ 与google task同步便签记录
+ 上次同步于 %1$s
+ 添加账号
+ 更换账号
+ 删除账号
+ 取消
+ 立即同步
+ 取消同步
+ 当前帐号 %1$s
+ 如更换同步帐号,过去的帐号同步信息将被清空,再次切换的同时可能会造成数据重复
+ 同步便签
+ 请选择google帐号,便签将与该帐号的google task内容同步。
+ 正在同步中,不能修改同步帐号
+ 同步帐号已设置为%1$s
+ 新建便签背景颜色随机
+ 通话便签
+ 请输入名称
+ 正在搜索便签
+ 搜索便签
+ 便签中的文字
+ 设置
+ 取消
+
+
diff --git a/res/values-zh-rTW/arrays.xml b/res/values-zh-rTW/arrays.xml
new file mode 100644
index 0000000..114e52e
--- /dev/null
+++ b/res/values-zh-rTW/arrays.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml
new file mode 100644
index 0000000..059f157
--- /dev/null
+++ b/res/values-zh-rTW/strings.xml
@@ -0,0 +1,120 @@
+
+
+
+
+
+ 便簽
+ 便簽2x2
+ 便簽4x4
+ 沒有關聯內容,點擊新建便簽。
+ 訪客模式下,便籤內容不可見
+ ...
+ 新建便簽
+ 已過期
+ yyyyMMdd
+ MM月dd日 kk:mm
+ 知道了
+ 查看
+ 呼叫電話
+ 發送郵件
+ 浏覽網頁
+ 打開地圖
+ 已將所選 %1$d 便籤移到 %2$s 文件夾
+
+ 新建文件夾
+ 導出文本
+ 同步
+ 取消同步
+ 設置
+ 搜尋
+ 刪除
+ 移動到文件夾
+ 選中了 %d 項
+ 沒有選中項,操作無效
+ 全選
+ 取消全選
+ 文字大小
+ 小
+ 正常
+ 大
+ 超大
+ 進入清單模式
+ 退出清單模式
+ 查看文件夾
+ 刪除文件夾
+ 修改文件夾名稱
+ 文件夾 %1$s 已存在,請重新命名
+ 分享
+ 發送到桌面
+ 提醒我
+ 刪除提醒
+ 選擇文件夾
+ 上一級文件夾
+ 已添加到桌面
+ 刪除
+ 确认要刪除所選的 %d 條便籤嗎?
+ 确认要删除該條便籤嗎?
+ 確認刪除檔夾及所包含的便簽嗎?
+ SD卡被佔用,不能操作
+ 導出TXT時發生錯誤,請檢查SD卡
+ 要查看的便籤不存在
+ 不能爲空便籤設置鬧鐘提醒
+ 不能將空便籤發送到桌面
+ 導出成功
+ 導出失敗
+ 已將文本文件(%1$s)導出至SD(%2$s)目錄
+
+ 同步便簽...
+ 同步成功
+ 同步失敗
+ 同步已取消
+ 與%1$s同步成功
+ 同步失敗,請檢查網絡和帳號設置
+ 同步失敗,發生內部錯誤
+ 同步已取消
+ 登陸%1$s...
+ 正在獲取服務器便籤列表...
+ 正在同步本地便籤...
+
+ 設置
+ 同步賬號
+ 与google task同步便簽記錄
+ 上次同步于 %1$s
+ 添加賬號
+ 更換賬號
+ 刪除賬號
+ 取消
+ 立即同步
+ 取消同步
+ 當前帳號 %1$s
+ 如更換同步帳號,過去的帳號同步信息將被清空,再次切換的同時可能會造成數據重復
+ 同步便簽
+ 請選擇google帳號,便簽將與該帳號的google task內容同步。
+ 正在同步中,不能修改同步帳號
+ 同步帳號已設置為%1$s
+ 新建便籤背景顏色隨機
+
+ 通話便籤
+ 請輸入名稱
+
+ 正在搜索便籤
+ 搜索便籤
+ 便籤中的文字
+ 設置
+ 取消
+
+
diff --git a/res/values-zh/strings.xml b/res/values-zh/strings.xml
new file mode 100644
index 0000000..959840d
--- /dev/null
+++ b/res/values-zh/strings.xml
@@ -0,0 +1,137 @@
+
+
+
+ 便签
+ 便签 2x2
+ 便签 4x4
+
+
+ 未找到关联便签,点击创建关联便签。
+ 隐私模式,无法查看便签内容
+ ...
+ 新建便签
+
+
+ 已过期
+ yyyyMMdd
+ MMMd kk:mm
+ 知道了
+ 查看
+
+
+ 拨号
+ 发送邮件
+ 浏览网页
+ 打开地图
+
+
+ /MIUI/notes/
+ notes_%s.txt
+
+
+ (%d)
+ 新建文件夹
+ 导出文本
+ 同步
+ 取消同步
+ 设置
+ 搜索
+ 置顶
+ 取消置顶
+ 删除
+ 移动到文件夹
+ 已选择 %d 项
+ 未选择任何项,操作无效
+ 全选
+ 取消全选
+ 批量选择
+
+
+ 字体大小
+ 小
+ 中
+ 大
+ 超大
+
+
+ 进入清单模式
+ 退出清单模式
+
+
+ 查看文件夹
+ 删除文件夹
+ 重命名文件夹
+ 文件夹 %1$s 已存在,请重新命名
+
+
+ 分享
+ 发送到桌面
+ 提醒我
+ 删除提醒
+ 插入图片
+ 选择文件夹
+ 父文件夹
+ 便签已添加到桌面
+
+
+ 确认删除文件夹及其包含的便签?
+ 删除选择的便签
+ 确认删除选择的 %d 个便签?
+ 确认删除此便签?
+ 已将选择的 %1$d 个便签移动到 %2$s 文件夹
+
+
+ SD卡正忙,暂不可用
+ 导出失败,请检查SD卡
+ 便签不存在
+ 抱歉,不能为空便签设置提醒
+ 抱歉,不能将空便签发送到桌面
+ 导出成功
+ 导出失败
+ 已将文本文件 (%1$s) 导出到SD卡 (%2$s) 目录
+
+
+ 正在同步便签...
+ 同步成功
+ 同步失败
+ 同步已取消
+ 已成功与账户 %1$s 同步
+ 同步失败,请检查网络和账户设置
+ 同步失败,发生内部错误
+ 同步已取消
+ 正在登录 %1$s...
+ 正在获取远程便签列表...
+ 正在将本地便签与Google Task同步...
+
+
+ 设置
+ 同步账户
+ 将便签与Google Task同步
+ 上次同步时间 %1$s
+ yyyy-MM-dd hh:mm:ss
+ 添加账户
+ 更改同步账户
+ 移除同步账户
+ 取消
+ 立即同步
+ 取消同步
+ 当前账户 %1$s
+ 将删除所有同步相关信息,可能会导致某些项目重复
+ 同步便签
+ 请选择一个Google账户。本地便签将与Google Task同步。
+ 无法更改账户,因为同步正在进行中
+ %1$s 已被设置为同步账户
+ 新便签背景颜色随机
+
+
+ 通话便签
+ 输入名称
+ 搜索便签
+ 搜索便签
+ 便签中的文本
+ 搜索历史
+ 设置
+ 取消
+
+
+
\ No newline at end of file
diff --git a/res/values/arrays.xml b/res/values/arrays.xml
new file mode 100644
index 0000000..62336e5
--- /dev/null
+++ b/res/values/arrays.xml
@@ -0,0 +1,105 @@
+
+
+
+
+
+
+
+
+ - -%s
+
+
+ - --%s
+
+
+ - --%s
+
+
+ - --%s
+
+
+
\ No newline at end of file
diff --git a/res/values/colors.xml b/res/values/colors.xml
new file mode 100644
index 0000000..2b72ca2
--- /dev/null
+++ b/res/values/colors.xml
@@ -0,0 +1,59 @@
+
+
+
+
+
+
+
+ #335b5b5b
+
+
+ #ffffff
+
\ No newline at end of file
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
new file mode 100644
index 0000000..fd60fb0
--- /dev/null
+++ b/res/values/dimens.xml
@@ -0,0 +1,145 @@
+
+
+
+
+
+
+
+ 33sp
+
+
+ 26sp
+
+
+ 20sp
+
+
+ 17sp
+
+
+ 14sp
+
\ No newline at end of file
diff --git a/res/values/strings.xml b/res/values/strings.xml
new file mode 100644
index 0000000..6cc899d
--- /dev/null
+++ b/res/values/strings.xml
@@ -0,0 +1,135 @@
+
+
+
+ Notes
+ Notes 2x2
+ Notes 4x4
+
+
+ No associated note found, click to create an associated note.
+ Privacy mode, cannot view note content
+ ...
+ New Note
+
+
+ Expired
+ yyyyMMdd
+ MMMd kk:mm
+ OK
+ View
+
+
+ Call
+ Send Email
+ Browse Web
+ Open Map
+
+
+ /MIUI/notes/
+ notes_%s.txt
+
+
+ (%d)
+ New Folder
+ Export Text
+ Sync
+ Cancel Sync
+ Settings
+ Search
+ Pin
+ Unpin
+ Delete
+ Move to Folder
+ Selected %d items
+ No items selected, operation invalid
+ Select All
+ Deselect All
+ Batch Select
+
+
+ Font Size
+ Small
+ Medium
+ Large
+ Extra Large
+
+
+ Enter List Mode
+ Exit List Mode
+
+
+ View Folder
+ Delete Folder
+ Rename Folder
+ Folder %1$s already exists, please rename
+
+
+ Share
+ Send to Desktop
+ Remind Me
+ Remove Reminder
+ Insert Image
+ Select Folder
+ Parent Folder
+ Note added to desktop
+
+
+ Confirm delete folder and its notes?
+ Delete Selected Notes
+ Confirm delete selected %d notes?
+ Confirm delete this note?
+ Moved selected %1$d notes to %2$s folder
+
+
+ SD card is busy, temporarily unavailable
+ Export failed, please check SD card
+ Note does not exist
+ Sorry, cannot set reminder for empty note
+ Sorry, cannot send empty note to desktop
+ Export successful
+ Export failed
+ Exported text file (%1$s) to SD card (%2$s) directory
+
+
+ Syncing notes...
+ Sync successful
+ Sync failed
+ Sync cancelled
+ Successfully synced with account %1$s
+ Sync failed, please check network and account settings
+ Sync failed, internal error occurred
+ Sync cancelled
+ Logging in to %1$s...
+ Retrieving remote notes list...
+ Syncing local notes with Google Task...
+
+
+ Settings
+ Sync Account
+ Sync notes with Google Task
+ Last sync time %1$s
+ yyyy-MM-dd hh:mm:ss
+ Add Account
+ Change Sync Account
+ Remove Sync Account
+ Cancel
+ Sync Now
+ Cancel Sync
+ Current account %1$s
+ All sync-related information will be deleted, which may cause some items to be duplicated
+ Sync Notes
+ Please select a Google account. Local notes will be synced with Google Task.
+ Cannot change account because sync is in progress
+ %1$s has been set as the sync account
+ New note background color random
+
+
+ Call Notes
+ Enter name
+ Search Notes
+ Search notes
+ Text in notes
+ Search History
+ Set
+ Cancel
+
\ No newline at end of file
diff --git a/res/values/styles.xml b/res/values/styles.xml
new file mode 100644
index 0000000..eebb6bc
--- /dev/null
+++ b/res/values/styles.xml
@@ -0,0 +1,310 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/res/xml/preferences.xml b/res/xml/preferences.xml
new file mode 100644
index 0000000..e139868
--- /dev/null
+++ b/res/xml/preferences.xml
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/res/xml/searchable.xml b/res/xml/searchable.xml
new file mode 100644
index 0000000..f2e0bab
--- /dev/null
+++ b/res/xml/searchable.xml
@@ -0,0 +1,148 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/res/xml/widget_2x_info.xml b/res/xml/widget_2x_info.xml
new file mode 100644
index 0000000..b079004
--- /dev/null
+++ b/res/xml/widget_2x_info.xml
@@ -0,0 +1,71 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/res/xml/widget_4x_info.xml b/res/xml/widget_4x_info.xml
new file mode 100644
index 0000000..a827879
--- /dev/null
+++ b/res/xml/widget_4x_info.xml
@@ -0,0 +1,76 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/notes/gtask/data/Task.java b/src/notes/gtask/data/Task.java
deleted file mode 100644
index 885b80e..0000000
--- a/src/notes/gtask/data/Task.java
+++ /dev/null
@@ -1,510 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.data;
-
-import android.database.Cursor;
-import android.text.TextUtils;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.DataConstants;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.gtask.exception.ActionFailureException;
-import net.micode.notes.tool.GTaskStringUtils;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-/**
- * GTask任务节点类,继承自核心抽象节点类{@link Node}
- * 该类是GTask中「任务(Task)」的具体实现,封装了GTask任务的核心属性(完成状态、备注、元信息、层级关系等),
- * 并实现了父类的抽象方法,完成以下核心功能:
- * 1. 生成GTask的创建/更新动作JSON(用于向远程GTask服务发送请求);
- * 2. 从远程GTask的JSON数据初始化任务内容(远程→本地同步);
- * 3. 从本地笔记的JSON数据初始化任务内容(本地→远程同步);
- * 4. 将任务内容序列化为本地笔记的JSON数据(GTask→本地笔记转换);
- * 5. 根据本地数据库Cursor判断同步动作类型(核心同步逻辑);
- * 6. 管理任务的层级关系(父任务列表、前序兄弟任务)。
- *
- * @author MiCode Open Source Community
- * @date 2010-2011
- */
-public class Task extends Node {
- /**
- * 日志标签,使用类的简单名称,便于调试时定位日志来源
- */
- private static final String TAG = Task.class.getSimpleName();
-
- // ====================== 成员变量 ======================
- /**
- * 任务完成状态:true表示已完成,false表示未完成
- */
- private boolean mCompleted;
-
- /**
- * 任务的备注信息(GTask的Notes字段,对应本地笔记的附加内容)
- */
- private String mNotes;
-
- /**
- * 本地笔记的元信息JSON对象,存储笔记的完整数据(用于GTask与本地笔记的映射)
- */
- private JSONObject mMetaInfo;
-
- /**
- * 前序兄弟任务:用于维护GTask任务的排序(当前任务的上一个同级任务)
- */
- private Task mPriorSibling;
-
- /**
- * 父任务列表:当前任务所属的GTask列表({TaskList}实例),维护层级关系
- */
- private TaskList mParent;
-
- /**
- * 构造方法:初始化GTask任务节点的默认属性
- * 调用父类{@link Node}的构造方法,同时初始化当前类的成员变量为默认值
- */
- public Task() {
- super();
- mCompleted = false; // 默认未完成
- mNotes = null; // 默认无备注
- mPriorSibling = null; // 默认无前序兄弟任务
- mParent = null; // 默认无父任务列表
- mMetaInfo = null; // 默认无本地元信息
- }
-
- /**
- * 实现父类抽象方法:生成创建GTask任务的动作JSON对象
- * 该JSON遵循GTask服务的接口规范,包含创建任务所需的所有参数(动作类型、ID、名称、父节点、排序等),
- * 用于向远程GTask服务发送创建任务的请求。
- *
- * @param actionId 动作唯一标识ID(用于GTask服务识别本次动作)
- * @return 包含创建任务动作的JSON对象
- * @throws ActionFailureException JSON生成失败时抛出该异常
- */
- public JSONObject getCreateAction(int actionId) {
- JSONObject js = new JSONObject();
-
- try {
- // 1. 动作类型:创建(CREATE)
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
-
- // 2. 动作ID:唯一标识本次创建动作
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
-
- // 3. 任务索引:当前任务在父列表中的位置(用于排序)
- js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
-
- // 4. 实体增量:任务的核心属性(名称、创建者、类型、备注等)
- JSONObject entity = new JSONObject();
- entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务名称(对应笔记标题/内容)
- entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 创建者ID(此处设为null)
- entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
- GTaskStringUtils.GTASK_JSON_TYPE_TASK); // 实体类型:任务(TASK)
- if (getNotes() != null) {
- entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 任务备注(非空时添加)
- }
- js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
-
- // 5. 父节点ID:当前任务所属父列表的GID
- js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
-
- // 6. 目标父类型:父节点的类型为分组(GROUP,对应TaskList)
- js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
- GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
-
- // 7. 列表ID:所属父列表的GID(与父节点ID一致)
- js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
-
- // 8. 前序兄弟ID:存在前序兄弟任务时添加该字段(用于排序)
- if (mPriorSibling != null) {
- js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
- }
-
- } catch (JSONException e) {
- // JSON解析/写入失败,输出日志并抛出同步失败异常
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to generate task-create jsonobject");
- }
-
- return js;
- }
-
- /**
- * 实现父类抽象方法:生成更新GTask任务的动作JSON对象
- * 该JSON遵循GTask服务的接口规范,包含更新任务所需的核心参数(动作类型、ID、名称、备注、删除标记等),
- * 用于向远程GTask服务发送更新任务的请求。
- *
- * @param actionId 动作唯一标识ID(用于GTask服务识别本次动作)
- * @return 包含更新任务动作的JSON对象
- * @throws ActionFailureException JSON生成失败时抛出该异常
- */
- public JSONObject getUpdateAction(int actionId) {
- JSONObject js = new JSONObject();
-
- try {
- // 1. 动作类型:更新(UPDATE)
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
-
- // 2. 动作ID:唯一标识本次更新动作
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
-
- // 3. 任务ID:当前任务的GID(标识要更新的任务)
- js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
-
- // 4. 实体增量:需要更新的任务属性(名称、备注、删除标记)
- JSONObject entity = new JSONObject();
- entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务名称
- if (getNotes() != null) {
- entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 任务备注(非空时添加)
- }
- entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 删除标记(是否被删除)
- js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
-
- } catch (JSONException e) {
- // JSON解析/写入失败,输出日志并抛出同步失败异常
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to generate task-update jsonobject");
- }
-
- return js;
- }
-
- /**
- * 实现父类抽象方法:根据远程GTask的JSON数据设置任务内容
- * 从远程GTask返回的JSON中解析出任务的核心属性(GID、修改时间、名称、备注、删除标记、完成状态等),
- * 完成远程GTask数据到本地Task对象的映射(远程→本地同步)。
- *
- * @param js 远程GTask返回的任务JSON对象
- * @throws ActionFailureException JSON解析失败时抛出该异常
- */
- public void setContentByRemoteJSON(JSONObject js) {
- if (js != null) {
- try {
- // 1. 任务GID:远程GTask的唯一标识
- if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
- setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
- }
-
- // 2. 最后修改时间:用于同步时的版本对比
- if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
- setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
- }
-
- // 3. 任务名称:对应本地笔记的内容
- if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
- setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
- }
-
- // 4. 任务备注:对应本地笔记的附加内容
- if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
- setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
- }
-
- // 5. 删除标记:是否被远程删除(用于同步删除操作)
- if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
- setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
- }
-
- // 6. 完成状态:任务是否被远程标记为完成
- if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
- setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
- }
- } catch (JSONException e) {
- // JSON解析失败,输出日志并抛出同步失败异常
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to get task content from jsonobject");
- }
- }
- }
-
- /**
- * 实现父类抽象方法:根据本地笔记的JSON数据设置任务内容
- * 从本地笔记的JSON中解析出核心内容(仅处理普通笔记类型),将笔记内容映射为GTask任务的名称,
- * 完成本地笔记数据到GTask Task对象的映射(本地→远程同步)。
- *
- * @param js 本地笔记的JSON对象(包含note和data字段)
- */
- public void setContentByLocalJSON(JSONObject js) {
- // 校验JSON的有效性:必须包含note和data核心字段
- if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
- || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
- Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
- return;
- }
-
- try {
- // 1. 解析note核心字段(笔记基础信息)
- JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
- // 2. 解析data数组(笔记具体内容)
- JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
-
- // 仅处理普通笔记类型(TYPE_NOTE),其他类型直接返回
- if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
- Log.e(TAG, "invalid type");
- return;
- }
-
- // 3. 遍历data数组,获取文本笔记的内容并设置为任务名称
- for (int i = 0; i < dataArray.length(); i++) {
- JSONObject data = dataArray.getJSONObject(i);
- // 匹配文本笔记的MIME类型(DataConstants.NOTE)
- if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
- setName(data.getString(DataColumns.CONTENT));
- break; // 仅取第一个文本内容
- }
- }
-
- } catch (JSONException e) {
- // JSON解析失败,输出日志
- Log.e(TAG, e.toString());
- e.printStackTrace();
- }
- }
-
- /**
- * 实现父类抽象方法:将任务内容序列化为本地笔记的JSON对象
- * 根据任务的元信息(mMetaInfo)状态,分为两种场景:
- * 1. 无元信息:新创建的GTask任务,生成空的本地笔记JSON(仅包含核心字段);
- * 2. 有元信息:已同步的任务,更新笔记的内容字段为当前任务名称,保留原有元信息;
- * 最终完成GTask Task对象到本地笔记JSON的映射(GTask→本地笔记转换)。
- *
- * @return 本地笔记的JSON对象,若序列化失败则返回null
- */
- public JSONObject getLocalJSONFromContent() {
- String name = getName(); // 获取当前任务名称
- try {
- // 场景1:无元信息(新任务,从GTask网页端创建)
- if (mMetaInfo == null) {
- // 任务名称为空,输出警告并返回null
- if (name == null) {
- Log.w(TAG, "the note seems to be an empty one");
- return null;
- }
-
- // 构建空的本地笔记JSON对象
- JSONObject js = new JSONObject();
- JSONObject note = new JSONObject();
- JSONArray dataArray = new JSONArray();
- JSONObject data = new JSONObject();
- data.put(DataColumns.CONTENT, name); // 任务名称作为笔记内容
- dataArray.put(data);
- js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); // 写入data数组
- note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 标记为普通笔记
- js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 写入note字段
- return js;
- }
- // 场景2:有元信息(已同步的任务,更新内容)
- else {
- // 从元信息中解析note和data字段
- JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
- JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
-
- // 遍历data数组,更新文本笔记的内容为当前任务名称
- for (int i = 0; i < dataArray.length(); i++) {
- JSONObject data = dataArray.getJSONObject(i);
- if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
- data.put(DataColumns.CONTENT, getName());
- break;
- }
- }
-
- // 标记为普通笔记类型
- note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
- return mMetaInfo; // 返回更新后的元信息
- }
- } catch (JSONException e) {
- // JSON序列化失败,输出日志并返回null
- Log.e(TAG, e.toString());
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * 设置本地笔记的元信息(从MetaData对象中解析)
- * 将MetaData中的笔记JSON字符串转换为JSONObject,存储到mMetaInfo成员变量,
- * 用于GTask任务与本地笔记的映射。
- *
- * @param metaData 本地笔记的元数据对象(包含笔记的JSON字符串)
- */
- public void setMetaInfo(MetaData metaData) {
- if (metaData != null && metaData.getNotes() != null) {
- try {
- // 将JSON字符串转换为JSONObject
- mMetaInfo = new JSONObject(metaData.getNotes());
- } catch (JSONException e) {
- // 解析失败,输出警告并置空元信息
- Log.w(TAG, e.toString());
- mMetaInfo = null;
- }
- }
- }
-
- /**
- * 实现父类抽象方法:根据本地数据库Cursor判断当前任务的同步动作类型
- * 核心同步逻辑:对比本地笔记数据与远程GTask任务数据的状态(ID、修改时间、本地修改标记、GID等),
- * 返回对应的同步动作常量(无操作、更新本地、更新远程、冲突、错误等)。
- *
- * @param c 本地数据库的Cursor对象(包含note表的核心字段)
- * @return 同步动作类型(对应{@link Node}中的SYNC_ACTION_*常量)
- */
- public int getSyncAction(Cursor c) {
- try {
- // 从元信息中解析note核心字段(笔记基础信息)
- JSONObject noteInfo = null;
- if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
- noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
- }
-
- // 场景1:元信息中无note字段(笔记元数据被删除)→ 更新远程
- if (noteInfo == null) {
- Log.w(TAG, "it seems that note meta has been deleted");
- return SYNC_ACTION_UPDATE_REMOTE;
- }
-
- // 场景2:note字段中无ID(远程笔记ID丢失)→ 更新本地
- if (!noteInfo.has(NoteColumns.ID)) {
- Log.w(TAG, "remote note id seems to be deleted");
- return SYNC_ACTION_UPDATE_LOCAL;
- }
-
- // 校验笔记ID:本地Cursor中的ID与元信息中的ID必须匹配
- if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
- Log.w(TAG, "note id doesn't match");
- return SYNC_ACTION_UPDATE_LOCAL;
- }
-
- // 核心同步逻辑:根据本地修改标记和同步时间判断
- if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
- // 子场景1:本地无修改
- if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
- // 本地和远程都无修改 → 无操作
- return SYNC_ACTION_NONE;
- } else {
- // 远程有修改 → 更新本地
- return SYNC_ACTION_UPDATE_LOCAL;
- }
- } else {
- // 子场景2:本地有修改
- // 校验GTask ID:本地Cursor中的GID与任务的GID必须匹配,否则为错误
- if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
- Log.e(TAG, "gtask id doesn't match");
- return SYNC_ACTION_ERROR;
- }
- if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
- // 仅本地有修改 → 更新远程
- return SYNC_ACTION_UPDATE_REMOTE;
- } else {
- // 本地和远程都有修改 → 冲突
- return SYNC_ACTION_UPDATE_CONFLICT;
- }
- }
- } catch (Exception e) {
- // 异常捕获:所有异常都标记为同步错误
- Log.e(TAG, e.toString());
- e.printStackTrace();
- }
-
- return SYNC_ACTION_ERROR;
- }
-
- /**
- * 判断当前任务是否值得保存(是否有有效数据)
- * 判定条件:有元信息,或任务名称非空,或任务备注非空 → 值得保存
- *
- * @return true表示值得保存,false表示无需保存(空任务)
- */
- public boolean isWorthSaving() {
- return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
- || (getNotes() != null && getNotes().trim().length() > 0);
- }
-
- // ====================== 成员变量的setter/getter方法 ======================
- /**
- * 设置任务的完成状态
- * @param completed true表示已完成,false表示未完成
- */
- public void setCompleted(boolean completed) {
- this.mCompleted = completed;
- }
-
- /**
- * 设置任务的备注信息
- * @param notes 备注字符串
- */
- public void setNotes(String notes) {
- this.mNotes = notes;
- }
-
- /**
- * 设置任务的前序兄弟任务(用于排序)
- * @param priorSibling 前序兄弟任务实例
- */
- public void setPriorSibling(Task priorSibling) {
- this.mPriorSibling = priorSibling;
- }
-
- /**
- * 设置任务的父任务列表(维护层级关系)
- * @param parent 父任务列表实例
- */
- public void setParent(TaskList parent) {
- this.mParent = parent;
- }
-
- /**
- * 获取任务的完成状态
- * @return true表示已完成,false表示未完成
- */
- public boolean getCompleted() {
- return this.mCompleted;
- }
-
- /**
- * 获取任务的备注信息
- * @return 备注字符串,若未设置则返回null
- */
- public String getNotes() {
- return this.mNotes;
- }
-
- /**
- * 获取任务的前序兄弟任务
- * @return 前序兄弟任务实例,若未设置则返回null
- */
- public Task getPriorSibling() {
- return this.mPriorSibling;
- }
-
- /**
- * 获取任务的父任务列表
- * @return 父任务列表实例,若未设置则返回null
- */
- public TaskList getParent() {
- return this.mParent;
- }
-
-}
\ No newline at end of file
diff --git a/src/notes/gtask/data/TaskList.java b/src/notes/gtask/data/TaskList.java
deleted file mode 100644
index 28c6bc7..0000000
--- a/src/notes/gtask/data/TaskList.java
+++ /dev/null
@@ -1,516 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.data;
-
-import android.database.Cursor;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.gtask.exception.ActionFailureException;
-import net.micode.notes.tool.GTaskStringUtils;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.util.ArrayList;
-
-/**
- * GTask任务列表类,继承自核心抽象节点类{@link Node}
- * 该类是GTask中「任务列表(TaskList/Group)」的具体实现,对应本地笔记的「文件夹」/「系统文件夹」,
- * 封装了任务列表的核心属性(排序索引、子任务列表),并实现了父类的抽象方法,完成以下核心功能:
- * 1. 生成GTask的创建/更新动作JSON(用于向远程GTask服务发送请求);
- * 2. 从远程GTask的JSON数据初始化列表内容(远程→本地同步);
- * 3. 从本地文件夹的JSON数据初始化列表内容(本地→远程同步,区分普通文件夹/系统文件夹);
- * 4. 将列表内容序列化为本地文件夹的JSON数据(GTask→本地文件夹转换);
- * 5. 根据本地数据库Cursor判断同步动作类型(核心同步逻辑,文件夹冲突直接采用本地修改);
- * 6. 管理子任务的增删改查、排序与层级关系(维护子任务的前序兄弟、父列表关联)。
- *
- * @author MiCode Open Source Community
- * @date 2010-2011
- */
-public class TaskList extends Node {
- /**
- * 日志标签,使用类的简单名称,便于调试时定位日志来源
- */
- private static final String TAG = TaskList.class.getSimpleName();
-
- // ====================== 成员变量 ======================
- /**
- * 任务列表的排序索引:用于GTask服务中任务列表的显示排序(默认值为1)
- */
- private int mIndex;
-
- /**
- * 子任务列表:存储当前任务列表下的所有{@link Task}实例,维护父子层级关系
- */
- private ArrayList mChildren;
-
- /**
- * 构造方法:初始化GTask任务列表的默认属性
- * 调用父类{@link Node}的构造方法,初始化子任务列表为空集合,排序索引为1
- */
- public TaskList() {
- super();
- mChildren = new ArrayList(); // 初始化子任务列表
- mIndex = 1; // 默认排序索引为1
- }
-
- /**
- * 实现父类抽象方法:生成创建GTask任务列表的动作JSON对象
- * 该JSON遵循GTask服务的接口规范,包含创建列表所需的所有参数(动作类型、ID、名称、类型、排序索引等),
- * 用于向远程GTask服务发送创建任务列表的请求。
- *
- * @param actionId 动作唯一标识ID(用于GTask服务识别本次动作)
- * @return 包含创建任务列表动作的JSON对象
- * @throws ActionFailureException JSON生成失败时抛出该异常
- */
- public JSONObject getCreateAction(int actionId) {
- JSONObject js = new JSONObject();
-
- try {
- // 1. 动作类型:创建(CREATE)
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
-
- // 2. 动作ID:唯一标识本次创建动作
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
-
- // 3. 列表索引:用于GTask服务中列表的排序
- js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
-
- // 4. 实体增量:任务列表的核心属性(名称、创建者、类型)
- JSONObject entity = new JSONObject();
- entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 列表名称(对应文件夹名称)
- entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 创建者ID(此处设为null)
- entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
- GTaskStringUtils.GTASK_JSON_TYPE_GROUP); // 实体类型:分组(GROUP,对应任务列表)
- js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
-
- } catch (JSONException e) {
- // JSON解析/写入失败,输出日志并抛出同步失败异常
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to generate tasklist-create jsonobject");
- }
-
- return js;
- }
-
- /**
- * 实现父类抽象方法:生成更新GTask任务列表的动作JSON对象
- * 该JSON遵循GTask服务的接口规范,包含更新列表所需的核心参数(动作类型、ID、名称、删除标记等),
- * 用于向远程GTask服务发送更新任务列表的请求。
- *
- * @param actionId 动作唯一标识ID(用于GTask服务识别本次动作)
- * @return 包含更新任务列表动作的JSON对象
- * @throws ActionFailureException JSON生成失败时抛出该异常
- */
- public JSONObject getUpdateAction(int actionId) {
- JSONObject js = new JSONObject();
-
- try {
- // 1. 动作类型:更新(UPDATE)
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
- GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
-
- // 2. 动作ID:唯一标识本次更新动作
- js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
-
- // 3. 列表ID:当前任务列表的GID(标识要更新的列表)
- js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
-
- // 4. 实体增量:需要更新的列表属性(名称、删除标记)
- JSONObject entity = new JSONObject();
- entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 列表名称
- entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 删除标记(是否被删除)
- js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
-
- } catch (JSONException e) {
- // JSON解析/写入失败,输出日志并抛出同步失败异常
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to generate tasklist-update jsonobject");
- }
-
- return js;
- }
-
- /**
- * 实现父类抽象方法:根据远程GTask的JSON数据设置任务列表内容
- * 从远程GTask返回的JSON中解析出列表的核心属性(GID、修改时间、名称),
- * 完成远程GTask数据到本地TaskList对象的映射(远程→本地同步)。
- *
- * @param js 远程GTask返回的任务列表JSON对象
- * @throws ActionFailureException JSON解析失败时抛出该异常
- */
- public void setContentByRemoteJSON(JSONObject js) {
- if (js != null) {
- try {
- // 1. 列表GID:远程GTask的唯一标识
- if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
- setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
- }
-
- // 2. 最后修改时间:用于同步时的版本对比
- if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
- setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
- }
-
- // 3. 列表名称:对应本地文件夹的名称
- if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
- setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
- }
-
- } catch (JSONException e) {
- // JSON解析失败,输出日志并抛出同步失败异常
- Log.e(TAG, e.toString());
- e.printStackTrace();
- throw new ActionFailureException("fail to get tasklist content from jsonobject");
- }
- }
- }
-
- /**
- * 实现父类抽象方法:根据本地文件夹的JSON数据设置任务列表内容
- * 从本地文件夹的JSON中解析出核心信息(区分普通文件夹/系统文件夹),
- * 将文件夹名称(添加MIUI前缀)映射为GTask列表名称,完成本地文件夹到GTask TaskList对象的映射(本地→远程同步)。
- *
- * @param js 本地文件夹的JSON对象(包含note核心字段)
- */
- public void setContentByLocalJSON(JSONObject js) {
- // 校验JSON的有效性:必须包含note核心字段
- if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
- Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
- return;
- }
-
- try {
- // 解析note核心字段(文件夹基础信息)
- JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
-
- // 场景1:普通文件夹(TYPE_FOLDER)→ 名称添加MIUI前缀
- if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
- String name = folder.getString(NoteColumns.SNIPPET);
- setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
- }
- // 场景2:系统文件夹(TYPE_SYSTEM)→ 根据ID映射为固定名称(根文件夹/通话记录文件夹)
- else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
- if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) {
- // 根文件夹:映射为默认文件夹名称(添加MIUI前缀)
- setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
- } else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) {
- // 通话记录文件夹:映射为通话笔记文件夹名称(添加MIUI前缀)
- setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE);
- } else {
- Log.e(TAG, "invalid system folder");
- }
- }
- // 场景3:无效类型 → 输出错误日志
- else {
- Log.e(TAG, "error type");
- }
- } catch (JSONException e) {
- // JSON解析失败,输出日志
- Log.e(TAG, e.toString());
- e.printStackTrace();
- }
- }
-
- /**
- * 实现父类抽象方法:将任务列表内容序列化为本地文件夹的JSON对象
- * 移除列表名称的MIUI前缀,根据名称判断文件夹类型(系统/普通),
- * 完成GTask TaskList对象到本地文件夹JSON的映射(GTask→本地文件夹转换)。
- *
- * @return 本地文件夹的JSON对象,若序列化失败则返回null
- */
- public JSONObject getLocalJSONFromContent() {
- try {
- JSONObject js = new JSONObject();
- JSONObject folder = new JSONObject();
-
- // 移除列表名称的MIUI前缀,还原本地文件夹名称
- String folderName = getName();
- if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) {
- folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), folderName.length());
- }
- // 设置文件夹名称(SNIPPET字段)
- folder.put(NoteColumns.SNIPPET, folderName);
-
- // 判断文件夹类型:默认/通话笔记文件夹为系统类型,其余为普通文件夹
- if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) {
- folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
- } else {
- folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
- }
-
- // 写入note核心字段
- js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
-
- return js;
- } catch (JSONException e) {
- // JSON序列化失败,输出日志并返回null
- Log.e(TAG, e.toString());
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * 实现父类抽象方法:根据本地数据库Cursor判断当前任务列表的同步动作类型
- * 核心同步逻辑:对比本地文件夹数据与远程GTask列表数据的状态(本地修改标记、同步时间、GID),
- * 特别处理文件夹冲突:直接采用本地修改(返回更新远程),其余逻辑与Task一致。
- *
- * @param c 本地数据库的Cursor对象(包含note表的核心字段)
- * @return 同步动作类型(对应{@link Node}中的SYNC_ACTION_*常量)
- */
- public int getSyncAction(Cursor c) {
- try {
- if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
- // 子场景1:本地无修改
- if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
- // 本地和远程都无修改 → 无操作
- return SYNC_ACTION_NONE;
- } else {
- // 远程有修改 → 更新本地
- return SYNC_ACTION_UPDATE_LOCAL;
- }
- } else {
- // 子场景2:本地有修改
- // 校验GTask ID:本地Cursor中的GID与列表的GID必须匹配,否则为错误
- if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
- Log.e(TAG, "gtask id doesn't match");
- return SYNC_ACTION_ERROR;
- }
- if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
- // 仅本地有修改 → 更新远程
- return SYNC_ACTION_UPDATE_REMOTE;
- } else {
- // 本地和远程都有修改(文件夹冲突)→ 直接采用本地修改,更新远程
- return SYNC_ACTION_UPDATE_REMOTE;
- }
- }
- } catch (Exception e) {
- // 异常捕获:所有异常都标记为同步错误
- Log.e(TAG, e.toString());
- e.printStackTrace();
- }
-
- return SYNC_ACTION_ERROR;
- }
-
- // ====================== 子任务管理:基础查询方法 ======================
- /**
- * 获取子任务的数量
- * @return 子任务列表的大小
- */
- public int getChildTaskCount() {
- return mChildren.size();
- }
-
- /**
- * 根据GID查找子任务
- * @param gid 子任务的GID
- * @return 匹配的{@link Task}实例,未找到则返回null(注:与getChilTaskByGid方法重复,保留原有逻辑)
- */
- public Task findChildTaskByGid(String gid) {
- for (int i = 0; i < mChildren.size(); i++) {
- Task t = mChildren.get(i);
- if (t.getGid().equals(gid)) {
- return t;
- }
- }
- return null;
- }
-
- /**
- * 获取子任务在列表中的索引位置
- * @param task 子任务实例
- * @return 子任务的索引,未找到则返回-1
- */
- public int getChildTaskIndex(Task task) {
- return mChildren.indexOf(task);
- }
-
- /**
- * 根据索引获取子任务
- * @param index 子任务的索引
- * @return 对应索引的{@link Task}实例,索引无效则返回null
- */
- public Task getChildTaskByIndex(int index) {
- if (index < 0 || index >= mChildren.size()) {
- Log.e(TAG, "getTaskByIndex: invalid index");
- return null;
- }
- return mChildren.get(index);
- }
-
- /**
- * 根据GID查找子任务(与findChildTaskByGid方法重复,保留原有逻辑)
- * @param gid 子任务的GID
- * @return 匹配的{@link Task}实例,未找到则返回null
- */
- public Task getChilTaskByGid(String gid) {
- for (Task task : mChildren) {
- if (task.getGid().equals(gid))
- return task;
- }
- return null;
- }
-
- /**
- * 获取子任务列表的完整集合
- * @return 子任务的ArrayList集合
- */
- public ArrayList getChildTaskList() {
- return this.mChildren;
- }
-
- // ====================== 子任务管理:增删改查与排序 ======================
- /**
- * 追加添加子任务到列表末尾,并维护子任务的前序兄弟和父列表关联
- * @param task 要添加的子任务实例
- * @return true表示添加成功,false表示任务为空或已存在
- */
- public boolean addChildTask(Task task) {
- boolean ret = false;
- // 校验任务有效性:非空且未存在于列表中
- if (task != null && !mChildren.contains(task)) {
- ret = mChildren.add(task);
- if (ret) {
- // 设置子任务的前序兄弟(列表最后一个元素的前一个元素)
- task.setPriorSibling(mChildren.isEmpty() ? null : mChildren.get(mChildren.size() - 1));
- // 设置子任务的父列表为当前列表
- task.setParent(this);
- }
- }
- return ret;
- }
-
- /**
- * 在指定索引位置添加子任务,并更新相关子任务的前序兄弟关联(维护排序)
- * @param task 要添加的子任务实例
- * @param index 要添加的索引位置
- * @return true表示添加成功,false表示索引无效或任务已存在
- */
- public boolean addChildTask(Task task, int index) {
- // 校验索引有效性
- if (index < 0 || index > mChildren.size()) {
- Log.e(TAG, "add child task: invalid index");
- return false;
- }
-
- // 检查任务是否已存在
- int pos = mChildren.indexOf(task);
- if (task != null && pos == -1) {
- // 在指定索引添加任务
- mChildren.add(index, task);
-
- // 获取当前任务的前序和后序任务(用于维护排序)
- Task preTask = null; // 前序任务
- Task afterTask = null; // 后序任务
- if (index != 0) {
- preTask = mChildren.get(index - 1);
- }
- if (index != mChildren.size() - 1) {
- afterTask = mChildren.get(index + 1);
- }
-
- // 设置当前任务的前序兄弟
- task.setPriorSibling(preTask);
- // 更新后序任务的前序兄弟为当前任务
- if (afterTask != null) {
- afterTask.setPriorSibling(task);
- }
- }
-
- return true;
- }
-
- /**
- * 从列表中移除子任务,并重置该任务的关联关系,同时更新后续任务的前序兄弟关联
- * @param task 要移除的子任务实例
- * @return true表示移除成功,false表示任务不存在
- */
- public boolean removeChildTask(Task task) {
- boolean ret = false;
- // 获取任务的索引位置
- int index = mChildren.indexOf(task);
- if (index != -1) {
- // 移除任务
- ret = mChildren.remove(task);
-
- if (ret) {
- // 重置该任务的前序兄弟和父列表关联
- task.setPriorSibling(null);
- task.setParent(null);
-
- // 更新后续任务的前序兄弟关联(若存在后续任务)
- if (index != mChildren.size()) {
- mChildren.get(index).setPriorSibling(index == 0 ? null : mChildren.get(index - 1));
- }
- }
- }
- return ret;
- }
-
- /**
- * 将子任务移动到指定索引位置(先移除后添加,维护排序)
- * @param task 要移动的子任务实例
- * @param index 目标索引位置
- * @return true表示移动成功,false表示索引无效、任务不存在或位置未变
- */
- public boolean moveChildTask(Task task, int index) {
- // 校验索引有效性
- if (index < 0 || index >= mChildren.size()) {
- Log.e(TAG, "move child task: invalid index");
- return false;
- }
-
- // 检查任务是否存在于列表中
- int pos = mChildren.indexOf(task);
- if (pos == -1) {
- Log.e(TAG, "move child task: the task should in the list");
- return false;
- }
-
- // 位置未变,直接返回成功
- if (pos == index) {
- return true;
- }
-
- // 先移除任务,再添加到指定索引位置
- return (removeChildTask(task) && addChildTask(task, index));
- }
-
- // ====================== 成员变量的setter/getter方法 ======================
- /**
- * 设置任务列表的排序索引
- * @param index 新的排序索引
- */
- public void setIndex(int index) {
- this.mIndex = index;
- }
-
- /**
- * 获取任务列表的排序索引
- * @return 排序索引值
- */
- public int getIndex() {
- return this.mIndex;
- }
-}
\ No newline at end of file
diff --git a/src/notes/gtask/exception/ActionFailureException.java b/src/notes/gtask/exception/ActionFailureException.java
deleted file mode 100644
index d9466fe..0000000
--- a/src/notes/gtask/exception/ActionFailureException.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.exception;
-
-/**
- * GTask同步动作失败的自定义运行时异常类
- * 该异常继承自{@link RuntimeException}(非受检异常),用于封装GTask同步过程中各类动作失败的场景,
- * 主要包括:
- * 1. 生成GTask创建/更新动作的JSON对象失败(如{@link net.micode.notes.gtask.data.Task#getCreateAction(int)});
- * 2. 从远程GTask的JSON数据解析内容失败(如{@link net.micode.notes.gtask.data.TaskList#setContentByRemoteJSON(org.json.JSONObject)});
- * 3. 其他GTask同步相关的核心动作执行失败。
- * 采用运行时异常的设计,允许在同步流程中快速抛出并处理失败,无需强制捕获,简化代码逻辑。
- *
- * @author MiCode Open Source Community
- * @date 2010-2011
- */
-public class ActionFailureException extends RuntimeException {
- /**
- * 序列化版本号(Serial Version UID)
- * 用于Java对象序列化的版本一致性校验,固定值保证序列化/反序列化时的兼容性。
- */
- private static final long serialVersionUID = 4425249765923293627L;
-
- /**
- * 无参构造方法:创建一个空的GTask动作失败异常
- * 调用父类{@link RuntimeException}的无参构造方法,无异常消息和根因。
- */
- public ActionFailureException() {
- super();
- }
-
- /**
- * 带异常消息的构造方法:创建包含指定错误信息的GTask动作失败异常
- * 调用父类的对应构造方法,传入自定义的异常描述信息,便于定位失败原因。
- *
- * @param paramString 异常的详细描述消息(如"fail to generate task-create jsonobject")
- */
- public ActionFailureException(String paramString) {
- super(paramString);
- }
-
- /**
- * 带异常消息和根因的构造方法:创建包含错误信息和底层异常的GTask动作失败异常
- * 调用父类的对应构造方法,既传入自定义消息,又关联底层异常(如{@link org.json.JSONException}),
- * 便于追溯异常的完整调用链。
- *
- * @param paramString 异常的详细描述消息
- * @param paramThrowable 底层异常(根因异常,如JSON解析异常、IO异常等)
- */
- public ActionFailureException(String paramString, Throwable paramThrowable) {
- super(paramString, paramThrowable);
- }
-}
\ No newline at end of file
diff --git a/src/notes/gtask/exception/NetworkFailureException.java b/src/notes/gtask/exception/NetworkFailureException.java
deleted file mode 100644
index 3f39f6e..0000000
--- a/src/notes/gtask/exception/NetworkFailureException.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.exception;
-
-/**
- * GTask同步过程中网络操作失败的自定义受检异常类
- * 该异常继承自{@link Exception}(受检异常),用于封装GTask同步流程中各类网络相关的失败场景,
- * 主要包括:
- * 1. 与GTask远程服务的网络连接失败(如无网络、连接超时);
- * 2. 向GTask服务发送请求/接收响应时的网络传输失败;
- * 3. 网络IO异常、数据接收不完整等网络相关错误。
- * 作为受检异常,调用者必须显式捕获并处理该异常,强制开发者关注网络操作的容错处理,提升程序健壮性。
- *
- * @author MiCode Open Source Community
- * @date 2010-2011
- */
-public class NetworkFailureException extends Exception {
- /**
- * 序列化版本号(Serial Version UID)
- * 用于Java对象序列化的版本一致性校验,固定值保证异常对象在序列化/反序列化时的兼容性,
- * 是Java序列化机制的标准规范要求。
- */
- private static final long serialVersionUID = 2107610287180234136L;
-
- /**
- * 无参构造方法:创建一个空的网络失败异常
- * 调用父类{@link Exception}的无参构造方法,无异常消息和根因,适用于无需详细描述的网络失败场景。
- */
- public NetworkFailureException() {
- super();
- }
-
- /**
- * 带异常消息的构造方法:创建包含指定错误信息的网络失败异常
- * 调用父类的对应构造方法,传入自定义的异常描述信息(如"network connection timeout"),
- * 便于开发者快速定位网络失败的具体原因。
- *
- * @param paramString 异常的详细描述消息,用于说明网络失败的具体情况
- */
- public NetworkFailureException(String paramString) {
- super(paramString);
- }
-
- /**
- * 带异常消息和根因的构造方法:创建包含错误信息和底层异常的网络失败异常
- * 调用父类的对应构造方法,既传入自定义消息,又关联底层的根因异常(如{@link java.net.SocketTimeoutException}、{@link java.io.IOException}等),
- * 便于追溯网络异常的完整调用链,排查底层问题。
- *
- * @param paramString 异常的详细描述消息
- * @param paramThrowable 底层根因异常(如Socket超时、IO异常等网络相关的原始异常)
- */
- public NetworkFailureException(String paramString, Throwable paramThrowable) {
- super(paramString, paramThrowable);
- }
-}
\ No newline at end of file
diff --git a/src/notes/gtask/remote/GTaskASyncTask.java b/src/notes/gtask/remote/GTaskASyncTask.java
deleted file mode 100644
index a466c1a..0000000
--- a/src/notes/gtask/remote/GTaskASyncTask.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.remote;
-
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.os.AsyncTask;
-import android.os.Build;
-
-import androidx.core.app.NotificationCompat;
-
-import net.micode.notes.R;
-import net.micode.notes.ui.NotesListActivity;
-import net.micode.notes.ui.NotesPreferenceActivity;
-
-/**
- * GTask同步的异步任务类,继承自{@link AsyncTask}
- * 该类负责在后台线程执行GTask的同步逻辑,在主线程更新同步进度、显示系统通知,并处理同步结果,
- * 同时适配Android 8.0+的通知渠道机制和高版本PendingIntent的FLAG_IMMUTABLE要求,
- * 是GTask同步功能与用户交互的核心类。
- *
- * 泛型说明:
- * - 第一个泛型:doInBackground的输入参数类型,无参数
- * - 第二个泛型:进度更新的参数类型,传递同步进度消息
- * - 第三个泛型:后台任务返回的结果类型,传递同步状态码
- *
- * @author MiCode Open Source Community
- * @date 2010-2011
- * @modified 适配Android O+通知渠道、高版本PendingIntent标记
- */
-public class GTaskASyncTask extends AsyncTask {
-
- /**
- * GTask同步通知的唯一标识ID,用于发送和取消通知
- */
- private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
-
- /**
- * 通知渠道ID(Android 8.0+必需),用于标识GTask同步的通知渠道
- */
- private static final String CHANNEL_ID = "gtask_sync_channel";
-
- /**
- * 同步完成的回调接口,用于在同步任务结束后触发后续操作
- */
- public interface OnCompleteListener {
- /**
- * 同步任务完成时的回调方法
- */
- void onComplete();
- }
-
- // ====================== 成员变量 ======================
- /**
- * 上下文对象,用于获取系统服务、资源、启动界面等
- */
- private Context mContext;
-
- /**
- * 通知管理器,用于发送和管理系统通知
- */
- private NotificationManager mNotifiManager;
-
- /**
- * GTask管理器实例,用于执行实际的GTask同步逻辑
- */
- private GTaskManager mTaskManager;
-
- /**
- * 同步完成的回调监听者,接收同步结束的通知
- */
- private OnCompleteListener mOnCompleteListener;
-
- /**
- * 构造方法:初始化GTask同步异步任务
- * @param context 上下文对象,不能为null
- * @param listener 同步完成的回调监听者,可为null(不处理回调)
- */
- public GTaskASyncTask(Context context, OnCompleteListener listener) {
- mContext = context;
- mOnCompleteListener = listener;
- // 获取系统通知管理器服务
- mNotifiManager = (NotificationManager) mContext
- .getSystemService(Context.NOTIFICATION_SERVICE);
- // 获取GTaskManager单例实例
- mTaskManager = GTaskManager.getInstance();
- // 初始化通知渠道(仅Android 8.0+需要,否则通知无法显示)
- createNotificationChannel();
- }
-
- /**
- * (新增适配方法)创建通知渠道(Android 8.0+必需)
- * Android 8.0(API 26)及以上版本要求所有通知必须属于某个通知渠道,否则无法显示
- */
- private void createNotificationChannel() {
- // 判断系统版本是否为Android O及以上
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- // 渠道名称:使用应用名称(从资源文件获取)
- CharSequence name = mContext.getString(R.string.app_name);
- // 渠道描述:说明该渠道的用途(GTask同步通知)
- String description = "GTask同步通知";
- // 通知重要性:默认级别(可弹出、有声音、在状态栏显示)
- int importance = NotificationManager.IMPORTANCE_DEFAULT;
- // 创建通知渠道实例
- NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
- channel.setDescription(description);
- // 向系统注册通知渠道(必须通过NotificationManager注册)
- if (mNotifiManager != null) {
- mNotifiManager.createNotificationChannel(channel);
- }
- }
- }
-
- /**
- * 取消当前的GTask同步任务
- * 调用GTaskManager的取消方法,终止正在执行的同步逻辑
- */
- public void cancelSync() {
- mTaskManager.cancelSync();
- }
-
- /**
- * 发布同步进度(封装AsyncTask的publishProgress方法,简化调用)
- * @param message 同步进度的提示消息,将在通知中显示
- */
- public void publishProgess(String message) {
- publishProgress(new String[] {
- message
- });
- }
-
- /**
- * 显示系统通知,用于展示同步进度、结果、错误信息等
- * 使用NotificationCompat兼容库构建通知,适配不同Android版本
- * @param tickerId 通知滚动提示文字的资源ID(如同步中、成功、失败)
- * @param content 通知的详细内容文字
- */
- private void showNotification(int tickerId, String content) {
- // 使用NotificationCompat.Builder构建通知(兼容低版本),关联指定的通知渠道
- NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, CHANNEL_ID)
- .setSmallIcon(R.drawable.notification) // 通知小图标(必需,从资源文件获取)
- .setContentTitle(mContext.getString(R.string.app_name)) // 通知标题(应用名称)
- .setContentText(content) // 通知详细内容
- .setTicker(mContext.getString(tickerId)) // 状态栏滚动提示文字
- .setWhen(System.currentTimeMillis()) // 通知创建时间(当前时间戳)
- .setDefaults(Notification.DEFAULT_LIGHTS) // 通知灯光效果(使用系统默认)
- .setAutoCancel(true); // 点击通知后自动取消
-
- // 设置通知的跳转意图(PendingIntent):根据提示类型跳转到不同界面
- PendingIntent pendingIntent;
- if (tickerId != R.string.ticker_success) {
- // 同步失败/取消:跳转到笔记设置界面(NotesPreferenceActivity)
- pendingIntent = PendingIntent.getActivity(
- mContext,
- 0,
- new Intent(mContext, NotesPreferenceActivity.class),
- PendingIntent.FLAG_IMMUTABLE // 高版本Android要求使用IMMUTABLE标记,避免安全警告
- );
- } else {
- // 同步成功:跳转到笔记列表界面(NotesListActivity)
- pendingIntent = PendingIntent.getActivity(
- mContext,
- 0,
- new Intent(mContext, NotesListActivity.class),
- PendingIntent.FLAG_IMMUTABLE // 高版本Android要求使用IMMUTABLE标记
- );
- }
- // 为通知设置跳转意图
- builder.setContentIntent(pendingIntent);
-
- // 发送通知:使用固定的通知ID,后续通知会覆盖之前的通知
- mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, builder.build());
- }
-
- /**
- * AsyncTask后台任务方法:在子线程执行GTask同步逻辑
- * 该方法运行在非主线程,不能更新UI,可通过publishProgress更新进度
- * @param unused 输入参数(无参数,泛型为Void)
- * @return 同步状态码(对应GTaskManager的STATE_*常量,如成功、网络错误、内部错误等)
- */
- @Override
- protected Integer doInBackground(Void... unused) {
- // 发布初始进度:显示登录中(同步账户名)
- publishProgess(mContext.getString(
- R.string.sync_progress_login,
- NotesPreferenceActivity.getSyncAccountName(mContext)
- ));
- // 调用GTaskManager执行同步逻辑,传入上下文和当前任务(用于进度回调)
- return mTaskManager.sync(mContext, this);
- }
-
- /**
- * AsyncTask进度更新方法:在主线程处理进度更新(由publishProgress触发)
- * 该方法运行在主线程,可更新UI、显示通知
- * @param progress 进度消息数组(对应泛型String,仅取第一个元素)
- */
- @Override
- protected void onProgressUpdate(String... progress) {
- // 显示同步中的通知,内容为进度消息
- showNotification(R.string.ticker_syncing, progress[0]);
- // 如果上下文是GTaskSyncService,发送广播更新同步进度(服务端的进度通知)
- if (mContext instanceof GTaskSyncService) {
- ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
- }
- }
-
- /**
- * AsyncTask结果处理方法:在主线程处理同步结果(后台任务完成后触发)
- * 该方法运行在主线程,可更新UI、显示结果通知、触发回调
- * @param result 后台任务返回的同步状态码(GTaskManager的STATE_*常量)
- */
- @Override
- protected void onPostExecute(Integer result) {
- // 根据同步状态码显示对应的通知
- if (result == GTaskManager.STATE_SUCCESS) {
- // 同步成功:显示成功通知,记录最后同步时间
- showNotification(
- R.string.ticker_success,
- mContext.getString(R.string.success_sync_account, mTaskManager.getSyncAccount())
- );
- // 更新SharedPreferences中的最后同步时间为当前时间
- NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
- } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
- // 网络错误:显示网络异常通知
- showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
- } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
- // 内部错误:显示内部异常通知
- showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
- } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
- // 同步取消:显示取消通知
- showNotification(R.string.ticker_cancel, mContext.getString(R.string.error_sync_cancelled));
- }
-
- // 触发同步完成的回调(在新线程执行,避免阻塞主线程)
- if (mOnCompleteListener != null) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- mOnCompleteListener.onComplete();
- }
- }).start();
- }
- }
-}
\ No newline at end of file
diff --git a/src/notes/gtask/remote/GTaskSyncService.java b/src/notes/gtask/remote/GTaskSyncService.java
deleted file mode 100644
index 5e376c7..0000000
--- a/src/notes/gtask/remote/GTaskSyncService.java
+++ /dev/null
@@ -1,272 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.gtask.remote;
-
-import android.app.Activity;
-import android.app.Service;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.IBinder;
-
-/**
- * GTask同步服务类,继承自Android {@link Service},是管理GTask异步同步任务的核心服务
- * 主要职责:
- * 1. 接收外部的同步指令(启动同步、取消同步),并分发处理;
- * 2. 管理{@link GTaskASyncTask}异步任务的生命周期(创建、执行、取消);
- * 3. 通过广播向外部组件发送同步状态(是否正在同步)和进度信息;
- * 4. 提供静态方法供外部组件(如Activity)便捷调用同步/取消同步功能,以及获取同步状态;
- * 5. 处理Service的生命周期事件,在低内存时取消同步任务以释放资源。
- *
- * 通信机制:
- * - 外部通过{@link Intent}传递指令(ACTION_START_SYNC/ACTION_CANCEL_SYNC)启动服务;
- * - 服务通过广播({@link #GTASK_SERVICE_BROADCAST_NAME})向外部推送同步状态和进度。
- *
- * @author MiCode Open Source Community
- * @date 2010-2011
- */
-public class GTaskSyncService extends Service {
- // ====================== Intent指令参数常量 ======================
- /**
- * Intent中传递同步动作类型的键名,对应值为{@link #ACTION_START_SYNC}/{@link #ACTION_CANCEL_SYNC}/{@link #ACTION_INVALID}
- */
- public final static String ACTION_STRING_NAME = "sync_action_type";
-
- /**
- * 同步动作类型:启动GTask同步
- */
- public final static int ACTION_START_SYNC = 0;
-
- /**
- * 同步动作类型:取消GTask同步
- */
- public final static int ACTION_CANCEL_SYNC = 1;
-
- /**
- * 同步动作类型:无效动作(默认值,用于容错)
- */
- public final static int ACTION_INVALID = 2;
-
- // ====================== 广播相关常量 ======================
- /**
- * GTask同步服务的广播名称,外部组件可注册该广播接收同步状态和进度更新
- */
- public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
-
- /**
- * 广播中传递“是否正在同步”的键名,对应值为boolean类型(true=同步中,false=未同步)
- */
- public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
-
- /**
- * 广播中传递同步进度信息的键名,对应值为String类型(如“正在初始化列表”“正在同步内容”)
- */
- public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
-
- // ====================== 静态成员变量(全局共享同步状态) ======================
- /**
- * GTask异步同步任务实例,全局唯一,用于控制同步任务的执行和取消
- */
- private static GTaskASyncTask mSyncTask = null;
-
- /**
- * 同步进度信息字符串,全局共享,外部可通过{@link #getProgressString()}获取
- */
- private static String mSyncProgress = "";
-
- /**
- * 启动GTask同步任务的核心方法
- * 逻辑:
- * 1. 检查异步任务是否为null(避免重复执行同步任务);
- * 2. 若为null,创建新的{@link GTaskASyncTask}实例,设置任务完成监听器;
- * 3. 发送初始广播(更新同步状态);
- * 4. 执行异步同步任务;
- * 任务完成监听器逻辑:
- * - 任务完成后,将mSyncTask置为null,发送空进度广播,停止服务自身。
- */
- private void startSync() {
- if (mSyncTask == null) {
- mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
- /**
- * 异步任务完成后的回调方法
- */
- public void onComplete() {
- // 清空异步任务实例,标记同步完成
- mSyncTask = null;
- // 发送空进度广播,通知外部同步完成
- sendBroadcast("");
- // 停止服务自身,释放资源
- stopSelf();
- }
- });
- // 发送初始广播,通知外部同步开始
- sendBroadcast("");
- // 执行异步同步任务
- mSyncTask.execute();
- }
- }
-
- /**
- * 取消当前正在执行的GTask同步任务
- * 逻辑:若异步任务不为null,调用其{@link GTaskASyncTask#cancelSync()}方法取消同步
- */
- private void cancelSync() {
- if (mSyncTask != null) {
- mSyncTask.cancelSync();
- }
- }
-
- /**
- * Service创建时的生命周期方法
- * 初始化:将异步任务实例置为null,确保服务启动时同步任务状态干净
- */
- @Override
- public void onCreate() {
- mSyncTask = null;
- }
-
- /**
- * Service接收启动指令的核心生命周期方法(每次启动服务都会调用)
- * 逻辑:
- * 1. 获取Intent中的参数Bundle;
- * 2. 若Bundle包含动作类型键,根据动作类型执行对应操作(启动/取消同步);
- * 3. 若处理了有效动作,返回{@link #START_STICKY}(服务被系统杀死后会重启);
- * 4. 否则,调用父类默认实现。
- *
- * @param intent 启动服务的Intent,包含同步动作类型参数
- * @param flags 启动标志位
- * @param startId 服务启动的唯一ID
- * @return 服务的启动模式,{@link #START_STICKY}或父类默认值
- */
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- Bundle bundle = intent.getExtras();
- if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
- // 根据Intent中的动作类型执行对应操作
- switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
- case ACTION_START_SYNC:
- // 执行启动同步逻辑
- startSync();
- break;
- case ACTION_CANCEL_SYNC:
- // 执行取消同步逻辑
- cancelSync();
- break;
- default:
- // 无效动作,不处理
- break;
- }
- // 返回START_STICKY,确保服务被系统杀死后能重启(适用于同步任务的持续性需求)
- return START_STICKY;
- }
- // 无有效参数,调用父类默认实现
- return super.onStartCommand(intent, flags, startId);
- }
-
- /**
- * 系统低内存时的回调方法
- * 优化:若同步任务正在执行,取消任务以释放内存,避免影响系统性能
- */
- @Override
- public void onLowMemory() {
- if (mSyncTask != null) {
- mSyncTask.cancelSync();
- }
- }
-
- /**
- * Service绑定的回调方法(该服务为启动型服务,不支持绑定,返回null)
- * @param intent 绑定服务的Intent
- * @return null(不支持绑定)
- */
- public IBinder onBind(Intent intent) {
- return null;
- }
-
- /**
- * 发送同步状态和进度的广播方法,供内部和异步任务调用
- * 逻辑:
- * 1. 更新全局进度信息;
- * 2. 创建广播Intent,设置广播名称;
- * 3. 向Intent中添加“是否正在同步”和“进度信息”参数;
- * 4. 发送广播,通知所有注册的接收器。
- *
- * @param msg 同步进度信息字符串(如“正在初始化GTask列表”)
- */
- public void sendBroadcast(String msg) {
- // 更新全局进度信息
- mSyncProgress = msg;
- // 创建广播Intent,指定广播名称
- Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
- // 添加“是否正在同步”参数:mSyncTask不为null表示同步中
- intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);
- // 添加“进度信息”参数
- intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
- // 发送广播
- sendBroadcast(intent);
- }
-
- /**
- * 供外部组件(如Activity)调用的静态方法:启动GTask同步服务
- * 逻辑:
- * 1. 为GTaskManager设置Activity上下文(用于Google账户授权);
- * 2. 创建启动服务的Intent,设置动作类型为“启动同步”;
- * 3. 启动服务。
- *
- * @param activity 调用方的Activity上下文(用于账户授权)
- */
- public static void startSync(Activity activity) {
- // 为GTaskManager设置Activity上下文,用于后续Google账户登录授权
- GTaskManager.getInstance().setActivityContext(activity);
- // 创建启动GTaskSyncService的Intent
- Intent intent = new Intent(activity, GTaskSyncService.class);
- // 设置Intent参数:动作类型为启动同步
- intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
- // 启动服务
- activity.startService(intent);
- }
-
- /**
- * 供外部组件调用的静态方法:取消GTask同步服务
- * 逻辑:
- * 1. 创建启动服务的Intent,设置动作类型为“取消同步”;
- * 2. 启动服务(服务会处理取消逻辑,即使已启动也会接收指令)。
- *
- * @param context 调用方的上下文(如Activity、Application)
- */
- public static void cancelSync(Context context) {
- Intent intent = new Intent(context, GTaskSyncService.class);
- intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
- context.startService(intent);
- }
-
- /**
- * 供外部组件调用的静态方法:获取当前是否正在同步的状态
- * @return boolean:true表示同步中,false表示未同步
- */
- public static boolean isSyncing() {
- return mSyncTask != null;
- }
-
- /**
- * 供外部组件调用的静态方法:获取当前同步进度信息
- * @return String:同步进度信息字符串
- */
- public static String getProgressString() {
- return mSyncProgress;
- }
-}
\ No newline at end of file
diff --git a/src/notes/model/Note.java b/src/notes/model/Note.java
deleted file mode 100644
index 1b32683..0000000
--- a/src/notes/model/Note.java
+++ /dev/null
@@ -1,461 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.model;
-
-import android.content.ContentProviderOperation;
-import android.content.ContentProviderResult;
-import android.content.ContentUris;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.OperationApplicationException;
-import android.net.Uri;
-import android.os.RemoteException;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.CallNote;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.data.Notes.TextNote;
-
-import java.util.ArrayList;
-
-/**
- * 笔记核心业务模型类
- * 负责管理单条笔记的元数据(创建时间、修改时间、所属文件夹等)和具体数据(文本内容、通话记录内容)
- * 提供笔记ID生成、数据更新、本地修改标记、数据同步到ContentProvider的核心功能
- * 采用内部类NoteData封装文本/通话数据的处理逻辑,符合面向对象的封装原则
- * 遵循Android ContentProvider数据交互规范,实现数据持久化
- *
- * @author MiCode Open Source Community
- * @date 2010-2011
- */
-public class Note {
- /**
- * 存储笔记元数据的变更键值对(如标题、修改时间、本地修改标记)
- * ContentValues是Android中用于封装键值对的容器,专门用于ContentProvider的增删改操作
- */
- private ContentValues mNoteDiffValues;
-
- /**
- * 笔记的具体数据对象(包含文本数据和通话记录数据),由内部类NoteData实现
- */
- private NoteData mNoteData;
-
- /**
- * 日志标签,用于Logcat输出时标识当前类,方便调试定位问题
- */
- private static final String TAG = "Note";
-
- /**
- * 生成新的笔记ID,用于向数据库中添加新笔记
- * 该方法为静态同步方法,保证多线程环境下生成的笔记ID唯一,避免并发冲突
- *
- * @param context 上下文对象,用于获取ContentResolver(访问ContentProvider的入口)
- * @param folderId 笔记所属文件夹的ID,用于关联笔记与文件夹
- * @return 新创建的笔记ID(大于0为有效ID,0表示失败)
- * @throws IllegalStateException 当解析出的笔记ID为-1时抛出,标识数据插入异常
- */
- public static synchronized long getNewNoteId(Context context, long folderId) {
- // 初始化ContentValues,存储新笔记的初始元数据
- ContentValues values = new ContentValues();
- // 获取当前系统时间,作为笔记的创建时间和初始修改时间
- long createdTime = System.currentTimeMillis();
- // 存储笔记创建时间(对应数据库note表的CREATED_DATE列)
- values.put(NoteColumns.CREATED_DATE, createdTime);
- // 存储笔记修改时间(对应数据库note表的MODIFIED_DATE列)
- values.put(NoteColumns.MODIFIED_DATE, createdTime);
- // 存储笔记类型:普通笔记(对应Notes类的TYPE_NOTE常量)
- values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
- // 标记笔记为本地已修改(1表示需要同步,对应LOCAL_MODIFIED列)
- values.put(NoteColumns.LOCAL_MODIFIED, 1);
- // 存储笔记所属文件夹ID(对应PARENT_ID列)
- values.put(NoteColumns.PARENT_ID, folderId);
-
- // 通过ContentResolver插入数据到note表,返回的Uri包含新笔记的ID(格式:content://xxx/note/123)
- Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
-
- // 初始化笔记ID为0(默认失败值)
- long noteId = 0;
- try {
- // 解析Uri的路径段获取笔记ID:Uri的getPathSegments()返回["note", "123"],索引1的元素是ID
- noteId = Long.valueOf(uri.getPathSegments().get(1));
- } catch (NumberFormatException e) {
- // 捕获数字格式异常,输出错误日志,保持noteId为0
- Log.e(TAG, "Get note id error :" + e.toString());
- noteId = 0;
- }
- // 校验笔记ID是否为-1(非法值,通常表示插入操作异常)
- if (noteId == -1) {
- throw new IllegalStateException("Wrong note id:" + noteId);
- }
- // 返回生成的笔记ID
- return noteId;
- }
-
- /**
- * 无参构造方法,初始化笔记的元数据容器和具体数据对象
- */
- public Note() {
- // 初始化笔记元数据的变更容器
- mNoteDiffValues = new ContentValues();
- // 初始化笔记具体数据对象
- mNoteData = new NoteData();
- }
-
- /**
- * 设置笔记元数据的键值对,并自动更新本地修改标记和修改时间
- * 每次修改元数据时,都会标记为本地已修改,并更新修改时间为当前系统时间
- *
- * @param key 元数据的键(对应NoteColumns中的列名,如标题、类型等)
- * @param value 元数据的值(字符串类型)
- */
- public void setNoteValue(String key, String value) {
- // 存储元数据键值对
- mNoteDiffValues.put(key, value);
- // 标记为本地已修改,需要同步
- mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
- // 更新修改时间为当前系统时间
- mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
- }
-
- /**
- * 设置笔记的文本数据键值对(如笔记内容)
- * 委托给内部类NoteData的setTextData方法处理
- *
- * @param key 文本数据的键(对应TextNote中的列名)
- * @param value 文本数据的值(如笔记的文本内容)
- */
- public void setTextData(String key, String value) {
- mNoteData.setTextData(key, value);
- }
-
- /**
- * 设置文本数据的ID(对应数据库data表的主键ID)
- * 用于后续更新文本数据时,指定要更新的记录
- *
- * @param id 文本数据的ID(必须大于0)
- */
- public void setTextDataId(long id) {
- mNoteData.setTextDataId(id);
- }
-
- /**
- * 获取文本数据的ID
- *
- * @return 文本数据的ID(0表示未设置,大于0为有效ID)
- */
- public long getTextDataId() {
- return mNoteData.mTextDataId;
- }
-
- /**
- * 设置通话记录数据的ID(对应数据库data表的主键ID)
- * 用于后续更新通话数据时,指定要更新的记录
- *
- * @param id 通话数据的ID(必须大于0)
- */
- public void setCallDataId(long id) {
- mNoteData.setCallDataId(id);
- }
-
- /**
- * 设置笔记的通话记录数据键值对(如电话号码、通话时间)
- * 委托给内部类NoteData的setCallData方法处理
- *
- * @param key 通话数据的键(对应CallNote中的列名)
- * @param value 通话数据的值(如电话号码)
- */
- public void setCallData(String key, String value) {
- mNoteData.setCallData(key, value);
- }
-
- /**
- * 判断笔记是否有本地修改(需要同步到数据库)
- * 判定条件:元数据容器非空 或 文本/通话数据有修改
- *
- * @return true表示有本地修改,false表示无修改
- */
- public boolean isLocalModified() {
- return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
- }
-
- /**
- * 将笔记的本地修改同步到ContentProvider(数据库)
- * 同步逻辑:先同步元数据,再同步具体数据,即使元数据同步失败,也尝试同步具体数据(保证数据安全)
- *
- * @param context 上下文对象,用于获取ContentResolver
- * @param noteId 要同步的笔记ID(必须大于0)
- * @return true表示同步成功(或无修改),false表示具体数据同步失败
- * @throws IllegalArgumentException 当笔记ID小于等于0时抛出,参数不合法
- */
- public boolean syncNote(Context context, long noteId) {
- // 校验笔记ID的合法性,小于等于0则抛出异常
- if (noteId <= 0) {
- throw new IllegalArgumentException("Wrong note id:" + noteId);
- }
-
- // 若没有本地修改,直接返回成功
- if (!isLocalModified()) {
- return true;
- }
-
- /**
- * 理论上,数据变更后需要更新LOCAL_MODIFIED和MODIFIED_DATE
- * 为了数据安全,即使元数据更新失败,也继续同步具体数据
- */
- // 构建笔记的Uri(content://xxx/note/[noteId]),更新元数据到数据库
- if (context.getContentResolver().update(
- ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
- null) == 0) {
- // 更新返回0表示无记录被更新,输出错误日志,但不中断流程
- Log.e(TAG, "Update note error, should not happen");
- // 继续执行后续的具体数据同步
- }
- // 清空元数据容器,标记为已同步
- mNoteDiffValues.clear();
-
- // 若具体数据有修改且同步失败,返回false;否则返回true
- if (mNoteData.isLocalModified()
- && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
- return false;
- }
-
- return true;
- }
-
- /**
- * 内部嵌套类,封装笔记的具体数据(文本数据和通话记录数据)的处理逻辑
- * 仅被外部类Note访问,符合封装原则,对外隐藏数据处理的细节
- */
- private class NoteData {
- /**
- * 文本数据的ID(对应数据库data表的主键ID)
- * 0表示新数据(需要插入),大于0表示已有数据(需要更新)
- */
- private long mTextDataId;
-
- /**
- * 存储文本数据的键值对(如笔记内容、格式等)
- */
- private ContentValues mTextDataValues;
-
- /**
- * 通话记录数据的ID(对应数据库data表的主键ID)
- * 0表示新数据(需要插入),大于0表示已有数据(需要更新)
- */
- private long mCallDataId;
-
- /**
- * 存储通话记录数据的键值对(如电话号码、通话时间等)
- */
- private ContentValues mCallDataValues;
-
- /**
- * 日志标签,用于标识当前内部类的日志输出
- */
- private static final String TAG = "NoteData";
-
- /**
- * 构造方法,初始化文本和通话数据的容器及ID
- */
- public NoteData() {
- mTextDataValues = new ContentValues();
- mCallDataValues = new ContentValues();
- mTextDataId = 0;
- mCallDataId = 0;
- }
-
- /**
- * 判断文本/通话数据是否有本地修改
- * 判定条件:文本数据容器非空 或 通话数据容器非空
- *
- * @return true表示有修改,false表示无修改
- */
- boolean isLocalModified() {
- return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
- }
-
- /**
- * 设置文本数据的ID,并校验ID的合法性
- *
- * @param id 文本数据的ID(必须大于0)
- * @throws IllegalArgumentException 当ID小于等于0时抛出,参数不合法
- */
- void setTextDataId(long id) {
- if (id <= 0) {
- throw new IllegalArgumentException("Text data id should larger than 0");
- }
- mTextDataId = id;
- }
-
- /**
- * 设置通话数据的ID,并校验ID的合法性
- *
- * @param id 通话数据的ID(必须大于0)
- * @throws IllegalArgumentException 当ID小于等于0时抛出,参数不合法
- */
- void setCallDataId(long id) {
- if (id <= 0) {
- throw new IllegalArgumentException("Call data id should larger than 0");
- }
- mCallDataId = id;
- }
-
- /**
- * 设置通话数据的键值对,并更新笔记的本地修改标记和修改时间
- *
- * @param key 通话数据的键(对应CallNote中的列名)
- * @param value 通话数据的值(字符串类型)
- */
- void setCallData(String key, String value) {
- // 存储通话数据键值对
- mCallDataValues.put(key, value);
- // 标记笔记为本地已修改
- mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
- // 更新笔记的修改时间
- mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
- }
-
- /**
- * 设置文本数据的键值对,并更新笔记的本地修改标记和修改时间
- *
- * @param key 文本数据的键(对应TextNote中的列名)
- * @param value 文本数据的值(字符串类型)
- */
- void setTextData(String key, String value) {
- // 存储文本数据键值对
- mTextDataValues.put(key, value);
- // 标记笔记为本地已修改
- mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
- // 更新笔记的修改时间
- mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
- }
-
- /**
- * 将文本/通话数据同步到ContentProvider(数据库)
- * 处理逻辑:新数据(ID=0)执行插入操作,已有数据(ID>0)执行批量更新操作
- *
- * @param context 上下文对象,用于获取ContentResolver
- * @param noteId 笔记ID,用于关联数据与笔记
- * @return 同步后的笔记Uri(失败则返回null)
- * @throws IllegalArgumentException 当笔记ID小于等于0时抛出,参数不合法
- */
- Uri pushIntoContentResolver(Context context, long noteId) {
- /**
- * 安全校验:笔记ID必须大于0
- */
- if (noteId <= 0) {
- throw new IllegalArgumentException("Wrong note id:" + noteId);
- }
-
- /**
- * 批量操作列表,用于存储ContentProviderOperation
- * 批量操作可减少与ContentProvider的交互次数,提升性能,且支持事务特性
- */
- ArrayList operationList = new ArrayList();
- // 用于构建ContentProviderOperation的构建器
- ContentProviderOperation.Builder builder = null;
-
- // 处理文本数据同步
- if (mTextDataValues.size() > 0) {
- // 添加笔记ID,关联数据与笔记(对应data表的NOTE_ID列)
- mTextDataValues.put(DataColumns.NOTE_ID, noteId);
- // 文本数据ID为0,表示新数据,执行插入操作
- if (mTextDataId == 0) {
- // 添加文本数据的MIME类型(标识数据类型为文本笔记)
- mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
- // 插入文本数据到data表,返回包含数据ID的Uri
- Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
- mTextDataValues);
- try {
- // 解析Uri获取数据ID并设置
- setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
- } catch (NumberFormatException e) {
- // 插入失败,输出错误日志,清空数据容器,返回null
- Log.e(TAG, "Insert new text data fail with noteId" + noteId);
- mTextDataValues.clear();
- return null;
- }
- } else {
- // 文本数据ID大于0,构建更新操作(更新指定ID的文本数据)
- builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
- Notes.CONTENT_DATA_URI, mTextDataId));
- // 设置更新的键值对
- builder.withValues(mTextDataValues);
- // 将更新操作加入批量列表
- operationList.add(builder.build());
- }
- // 清空文本数据容器,标记为已同步
- mTextDataValues.clear();
- }
-
- // 处理通话数据同步(逻辑与文本数据一致)
- if (mCallDataValues.size() > 0) {
- // 添加笔记ID,关联数据与笔记
- mCallDataValues.put(DataColumns.NOTE_ID, noteId);
- // 通话数据ID为0,表示新数据,执行插入操作
- if (mCallDataId == 0) {
- // 添加通话数据的MIME类型(标识数据类型为通话笔记)
- mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
- // 插入通话数据到data表
- Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
- mCallDataValues);
- try {
- // 解析Uri获取数据ID并设置
- setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
- } catch (NumberFormatException e) {
- // 插入失败,输出错误日志,清空数据容器,返回null
- Log.e(TAG, "Insert new call data fail with noteId" + noteId);
- mCallDataValues.clear();
- return null;
- }
- } else {
- // 通话数据ID大于0,构建更新操作
- 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(
- Notes.AUTHORITY, operationList);
- // 校验结果,返回笔记的Uri(结果为空则返回null)
- return (results == null || results.length == 0 || results[0] == null) ? null
- : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
- } catch (RemoteException e) {
- // 捕获远程调用异常(ContentProvider可能在其他进程),输出日志,返回null
- Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
- return null;
- } catch (OperationApplicationException e) {
- // 捕获操作应用异常,输出日志,返回null
- Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
- return null;
- }
- }
- // 无批量操作,返回null
- return null;
- }
- }
-}
\ No newline at end of file
diff --git a/src/notes/model/WorkingNote.java b/src/notes/model/WorkingNote.java
deleted file mode 100644
index ff510b7..0000000
--- a/src/notes/model/WorkingNote.java
+++ /dev/null
@@ -1,653 +0,0 @@
-/*
- * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.micode.notes.model;
-
-import android.appwidget.AppWidgetManager;
-import android.content.ContentUris;
-import android.content.Context;
-import android.database.Cursor;
-import android.text.TextUtils;
-import android.util.Log;
-
-import net.micode.notes.data.Notes;
-import net.micode.notes.data.Notes.CallNote;
-import net.micode.notes.data.Notes.DataColumns;
-import net.micode.notes.data.Notes.DataConstants;
-import net.micode.notes.data.Notes.NoteColumns;
-import net.micode.notes.data.Notes.TextNote;
-import net.micode.notes.tool.ResourceParser.NoteBgResources;
-
-/**
- * 笔记工作状态管理类,是笔记编辑过程中的核心数据模型
- * 主要职责:
- * 1. 管理笔记的各项属性(ID、内容、文件夹ID、提醒时间、背景色、组件信息、修改时间等);
- * 2. 支持新建空白笔记和加载现有笔记两种场景的初始化;
- * 3. 从本地数据库加载笔记的基本信息和数据内容(文本、通话记录);
- * 4. 将编辑后的笔记保存到本地数据库,并处理组件更新逻辑;
- * 5. 提供笔记属性的设置/获取方法,以及设置变化的回调监听器;
- * 6. 处理笔记的删除标记、提醒时间、复选框模式、通话笔记转换等业务逻辑。
- *
- * 数据关联:
- * - 关联{@link Note}类处理数据库的同步操作;
- * - 关联本地ContentProvider(Notes.CONTENT_NOTE_URI/Notes.CONTENT_DATA_URI)获取/保存数据;
- * - 关联{@link NoteBgResources}处理笔记背景色的资源映射。
- *
- * @author MiCode Open Source Community
- * @date 2010-2011
- */
-public class WorkingNote {
- // ====================== 成员变量(笔记核心属性) ======================
- /**
- * 关联的Note实例,用于处理笔记与数据库的同步操作(增删改)
- */
- private Note mNote;
-
- /**
- * 笔记的唯一ID(本地数据库主键),0表示新笔记(未保存到数据库)
- */
- private long mNoteId;
-
- /**
- * 笔记的文本内容(核心数据)
- */
- private String mContent;
-
- /**
- * 笔记的模式(如普通文本模式、复选框列表模式,对应{@link TextNote#MODE})
- */
- private int mMode;
-
- /**
- * 笔记的提醒时间(时间戳,0表示无提醒)
- */
- private long mAlertDate;
-
- /**
- * 笔记的最后修改时间(时间戳)
- */
- private long mModifiedDate;
-
- /**
- * 笔记的背景色ID(对应{@link NoteBgResources}中的颜色标识,非资源ID)
- */
- private int mBgColorId;
-
- /**
- * 关联的桌面组件ID({@link AppWidgetManager#INVALID_APPWIDGET_ID}表示无关联组件)
- */
- private int mWidgetId;
-
- /**
- * 关联的桌面组件类型({@link Notes#TYPE_WIDGET_INVALIDE}表示无效类型)
- */
- private int mWidgetType;
-
- /**
- * 笔记所属的文件夹ID(对应本地数据库中的文件夹主键)
- */
- private long mFolderId;
-
- /**
- * 上下文对象,用于访问ContentResolver、资源等
- */
- private Context mContext;
-
- /**
- * 笔记的删除标记:true表示标记为删除,false表示正常状态
- */
- private boolean mIsDeleted;
-
- /**
- * 笔记设置变化的回调监听器,用于通知外部组件属性变化(背景色、提醒、组件、复选框模式)
- */
- private NoteSettingChangedListener mNoteSettingStatusListener;
-
- // ====================== 常量定义(数据库查询投影、日志标签) ======================
- /**
- * 日志标签,使用类名便于调试时定位日志来源
- */
- private static final String TAG = "WorkingNote";
-
- /**
- * 笔记数据(Data表)的查询投影,指定需要查询的列,减少数据传输
- * 对应列:DataColumns.ID, CONTENT, MIME_TYPE, DATA1(MODE), DATA2, DATA3, DATA4
- */
- public static final String[] DATA_PROJECTION = new String[] {
- DataColumns.ID,
- DataColumns.CONTENT,
- DataColumns.MIME_TYPE,
- DataColumns.DATA1, // 存储笔记模式(MODE)
- DataColumns.DATA2,
- DataColumns.DATA3,
- DataColumns.DATA4,
- };
-
- /**
- * 笔记主表(Note表)的查询投影,指定需要查询的列
- * 对应列:PARENT_ID(FOLDER_ID), ALERTED_DATE, BG_COLOR_ID, WIDGET_ID, WIDGET_TYPE, MODIFIED_DATE
- */
- public static final String[] NOTE_PROJECTION = new String[] {
- NoteColumns.PARENT_ID, // 文件夹ID
- NoteColumns.ALERTED_DATE, // 提醒时间
- NoteColumns.BG_COLOR_ID, // 背景色ID
- NoteColumns.WIDGET_ID, // 组件ID
- NoteColumns.WIDGET_TYPE, // 组件类型
- NoteColumns.MODIFIED_DATE // 修改时间
- };
-
- // ====================== 数据库查询列索引常量(简化代码,避免魔法数字) ======================
- /**
- * Data表查询结果中,ID列的索引(对应DATA_PROJECTION[0])
- */
- private static final int DATA_ID_COLUMN = 0;
-
- /**
- * Data表查询结果中,CONTENT列的索引(对应DATA_PROJECTION[1])
- */
- private static final int DATA_CONTENT_COLUMN = 1;
-
- /**
- * Data表查询结果中,MIME_TYPE列的索引(对应DATA_PROJECTION[2])
- */
- private static final int DATA_MIME_TYPE_COLUMN = 2;
-
- /**
- * Data表查询结果中,DATA1(MODE)列的索引(对应DATA_PROJECTION[3])
- */
- private static final int DATA_MODE_COLUMN = 3;
-
- /**
- * Note表查询结果中,PARENT_ID(文件夹ID)列的索引(对应NOTE_PROJECTION[0])
- */
- private static final int NOTE_PARENT_ID_COLUMN = 0;
-
- /**
- * Note表查询结果中,ALERTED_DATE(提醒时间)列的索引(对应NOTE_PROJECTION[1])
- */
- private static final int NOTE_ALERTED_DATE_COLUMN = 1;
-
- /**
- * Note表查询结果中,BG_COLOR_ID(背景色ID)列的索引(对应NOTE_PROJECTION[2])
- */
- private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
-
- /**
- * Note表查询结果中,WIDGET_ID(组件ID)列的索引(对应NOTE_PROJECTION[3])
- */
- private static final int NOTE_WIDGET_ID_COLUMN = 3;
-
- /**
- * Note表查询结果中,WIDGET_TYPE(组件类型)列的索引(对应NOTE_PROJECTION[4])
- */
- private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
-
- /**
- * Note表查询结果中,MODIFIED_DATE(修改时间)列的索引(对应NOTE_PROJECTION[5])
- */
- private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
-
- // ====================== 私有构造方法(封装初始化逻辑,通过静态方法对外提供实例) ======================
- /**
- * 私有构造方法:初始化新笔记的默认属性(新建空白笔记时使用)
- * @param context 上下文对象
- * @param folderId 笔记所属的文件夹ID
- */
- private WorkingNote(Context context, long folderId) {
- mContext = context;
- mAlertDate = 0; // 初始无提醒
- mModifiedDate = System.currentTimeMillis(); // 初始修改时间为当前时间
- mFolderId = folderId; // 设置所属文件夹ID
- mNote = new Note(); // 初始化Note实例
- mNoteId = 0; // 新笔记ID为0(未保存到数据库)
- mIsDeleted = false; // 初始未删除
- mMode = 0; // 初始模式为普通文本
- mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 初始无关联组件类型
- }
-
- /**
- * 私有构造方法:初始化现有笔记的属性(加载数据库中已存在的笔记时使用)
- * @param context 上下文对象
- * @param noteId 现有笔记的ID(数据库主键)
- * @param folderId 笔记所属的文件夹ID(暂时传0,后续从数据库加载时覆盖)
- */
- private WorkingNote(Context context, long noteId, long folderId) {
- mContext = context;
- mNoteId = noteId; // 设置现有笔记的ID
- mFolderId = folderId; // 临时赋值,后续从数据库加载时更新
- mIsDeleted = false; // 初始未删除
- mNote = new Note(); // 初始化Note实例
- loadNote(); // 从数据库加载笔记的基本信息和数据内容
- }
-
- // ====================== 核心私有方法(加载笔记数据) ======================
- /**
- * 从数据库加载笔记的基本信息(Note表)
- * 逻辑:
- * 1. 根据笔记ID查询Note表的指定列(NOTE_PROJECTION);
- * 2. 若查询结果不为空,赋值文件夹ID、背景色ID、组件信息、提醒时间、修改时间;
- * 3. 若查询结果为空,抛出非法参数异常(笔记ID不存在);
- * 4. 加载完成后,调用{@link #loadNoteData()}加载笔记的具体数据(Data表)。
- */
- private void loadNote() {
- // 根据笔记ID构建Uri,查询Note表
- Cursor cursor = mContext.getContentResolver().query(
- ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
- null, null);
-
- if (cursor != null) {
- if (cursor.moveToFirst()) {
- // 从查询结果中赋值各项属性
- mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); // 文件夹ID
- mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); // 背景色ID
- mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); // 组件ID
- mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN); // 组件类型
- mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN); // 提醒时间
- mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); // 修改时间
- }
- cursor.close(); // 关闭Cursor,释放资源
- } else {
- // 笔记ID不存在,打印日志并抛出异常
- Log.e(TAG, "No note with id:" + mNoteId);
- throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
- }
- // 加载笔记的具体数据(文本、通话记录)
- loadNoteData();
- }
-
- /**
- * 从数据库加载笔记的具体数据(Data表)
- * 逻辑:
- * 1. 根据笔记ID查询Data表的指定列(DATA_PROJECTION);
- * 2. 遍历查询结果,区分数据类型(文本笔记、通话笔记):
- * - 文本笔记(DataConstants.NOTE):赋值内容、模式,设置文本数据ID;
- * - 通话笔记(DataConstants.CALL_NOTE):设置通话数据ID;
- * - 未知类型:打印日志;
- * 3. 若查询结果为空,抛出非法参数异常(笔记数据不存在)。
- */
- private void loadNoteData() {
- // 根据笔记ID查询Data表(NoteId=?)
- Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
- DataColumns.NOTE_ID + "=?", new String[] {
- String.valueOf(mNoteId)
- }, null);
-
- if (cursor != null) {
- if (cursor.moveToFirst()) {
- // 遍历所有数据行
- do {
- String type = cursor.getString(DATA_MIME_TYPE_COLUMN); // 获取数据类型
- if (DataConstants.NOTE.equals(type)) {
- // 文本笔记:赋值内容、模式,设置文本数据ID
- mContent = cursor.getString(DATA_CONTENT_COLUMN);
- mMode = cursor.getInt(DATA_MODE_COLUMN);
- mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
- } else if (DataConstants.CALL_NOTE.equals(type)) {
- // 通话笔记:设置通话数据ID
- mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
- } else {
- // 未知类型,打印日志
- Log.d(TAG, "Wrong note type with type:" + type);
- }
- } while (cursor.moveToNext());
- }
- cursor.close(); // 关闭Cursor,释放资源
- } else {
- // 笔记数据不存在,打印日志并抛出异常
- Log.e(TAG, "No data with id:" + mNoteId);
- throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
- }
- }
-
- // ====================== 公共静态方法(对外提供实例,工厂模式) ======================
- /**
- * 创建空白笔记的静态工厂方法(对外暴露,用于新建笔记)
- * @param context 上下文对象
- * @param folderId 笔记所属的文件夹ID
- * @param widgetId 关联的组件ID(INVALID_APPWIDGET_ID表示无)
- * @param widgetType 关联的组件类型(TYPE_WIDGET_INVALIDE表示无)
- * @param defaultBgColorId 默认背景色ID
- * @return WorkingNote实例(初始化后的空白笔记)
- */
- public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
- int widgetType, int defaultBgColorId) {
- WorkingNote note = new WorkingNote(context, folderId);
- note.setBgColorId(defaultBgColorId); // 设置默认背景色
- note.setWidgetId(widgetId); // 设置组件ID
- note.setWidgetType(widgetType); // 设置组件类型
- return note;
- }
-
- /**
- * 加载现有笔记的静态工厂方法(对外暴露,用于编辑现有笔记)
- * @param context 上下文对象
- * @param id 现有笔记的ID(数据库主键)
- * @return WorkingNote实例(加载后的现有笔记)
- */
- public static WorkingNote load(Context context, long id) {
- return new WorkingNote(context, id, 0);
- }
-
- // ====================== 核心公共方法(保存笔记) ======================
- /**
- * 保存笔记到数据库(线程安全,同步方法)
- * 逻辑:
- * 1. 判断笔记是否值得保存({@link #isWorthSaving()}):
- * - 若不值得保存,返回false;
- * - 若值得保存,继续执行;
- * 2. 若笔记未保存到数据库(ID=0),创建新笔记ID;
- * 3. 调用Note的syncNote方法同步笔记到数据库;
- * 4. 若笔记关联组件,通知监听器更新组件;
- * 5. 返回true表示保存成功。
- * @return boolean:true=保存成功,false=保存失败/无需保存
- */
- public synchronized boolean saveNote() {
- if (isWorthSaving()) {
- // 笔记未保存到数据库,创建新笔记ID
- if (!existInDatabase()) {
- if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
- Log.e(TAG, "Create new note fail with id:" + mNoteId);
- return false;
- }
- }
-
- // 同步笔记到数据库(Note类处理具体的增删改操作)
- mNote.syncNote(mContext, mNoteId);
-
- /**
- * 若笔记关联组件,通知监听器更新组件内容
- */
- if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
- && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
- && mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onWidgetChanged();
- }
- return true;
- } else {
- // 笔记不值得保存,返回false
- return false;
- }
- }
-
- // ====================== 辅助方法(判断笔记状态) ======================
- /**
- * 判断笔记是否已存在于数据库中(ID>0表示已存在)
- * @return boolean:true=已存在,false=未存在(新笔记)
- */
- public boolean existInDatabase() {
- return mNoteId > 0;
- }
-
- /**
- * 判断笔记是否值得保存到数据库(过滤无意义的保存操作)
- * 不保存的场景:
- * 1. 标记为删除的笔记;
- * 2. 新笔记且内容为空;
- * 3. 现有笔记且未发生本地修改;
- * @return boolean:true=值得保存,false=不值得保存
- */
- private boolean isWorthSaving() {
- if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
- || (existInDatabase() && !mNote.isLocalModified())) {
- return false;
- } else {
- return true;
- }
- }
-
- // ====================== 监听器设置方法 ======================
- /**
- * 设置笔记设置变化的回调监听器
- * @param l 监听器实例(实现{@link NoteSettingChangedListener}接口)
- */
- public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
- mNoteSettingStatusListener = l;
- }
-
- // ====================== 公共属性设置方法(包含变化回调) ======================
- /**
- * 设置笔记的提醒时间,并通知监听器
- * @param date 提醒时间戳(0表示取消提醒)
- * @param set 是否设置提醒(true=设置,false=取消)
- */
- public void setAlertDate(long date, boolean set) {
- if (date != mAlertDate) {
- mAlertDate = date; // 更新提醒时间
- mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); // 同步到Note实例
- }
- // 通知监听器提醒时间变化
- if (mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onClockAlertChanged(date, set);
- }
- }
-
- /**
- * 标记笔记为删除/取消删除,并通知监听器更新组件
- * @param mark true=标记为删除,false=取消删除
- */
- public void markDeleted(boolean mark) {
- mIsDeleted = mark; // 更新删除标记
- // 若笔记关联组件,通知监听器更新组件
- if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
- && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onWidgetChanged();
- }
- }
-
- /**
- * 设置笔记的背景色ID,并通知监听器
- * @param id 背景色ID(对应{@link NoteBgResources}中的标识)
- */
- public void setBgColorId(int id) {
- if (id != mBgColorId) {
- mBgColorId = id; // 更新背景色ID
- // 通知监听器背景色变化
- if (mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onBackgroundColorChanged();
- }
- mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); // 同步到Note实例
- }
- }
-
- /**
- * 设置笔记的复选框模式,并通知监听器
- * @param mode 新模式(如普通文本、复选框列表)
- */
- public void setCheckListMode(int mode) {
- if (mMode != mode) {
- // 通知监听器复选框模式变化(传递旧模式和新模式)
- if (mNoteSettingStatusListener != null) {
- mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
- }
- mMode = mode; // 更新模式
- mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); // 同步到Note实例
- }
- }
-
- /**
- * 设置笔记关联的组件类型
- * @param type 组件类型({@link Notes#TYPE_WIDGET_INVALIDE}表示无效)
- */
- public void setWidgetType(int type) {
- if (type != mWidgetType) {
- mWidgetType = type; // 更新组件类型
- mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); // 同步到Note实例
- }
- }
-
- /**
- * 设置笔记关联的组件ID
- * @param id 组件ID({@link AppWidgetManager#INVALID_APPWIDGET_ID}表示无)
- */
- public void setWidgetId(int id) {
- if (id != mWidgetId) {
- mWidgetId = id; // 更新组件ID
- mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); // 同步到Note实例
- }
- }
-
- /**
- * 设置笔记的文本内容,并同步到Note实例
- * @param text 新的文本内容
- */
- public void setWorkingText(String text) {
- if (!TextUtils.equals(mContent, text)) {
- mContent = text; // 更新内容
- mNote.setTextData(DataColumns.CONTENT, mContent); // 同步到Note实例
- }
- }
-
- /**
- * 将笔记转换为通话笔记(设置通话记录相关数据,并移动到通话记录文件夹)
- * @param phoneNumber 电话号码
- * @param callDate 通话时间戳
- */
- public void convertToCallNote(String phoneNumber, long callDate) {
- // 设置通话记录数据(通话时间、电话号码)
- mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
- mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
- // 将笔记移动到通话记录文件夹(ID_CALL_RECORD_FOLDER)
- mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
- }
-
- // ====================== 公共属性获取方法 ======================
- /**
- * 判断笔记是否有提醒(提醒时间>0表示有)
- * @return boolean:true=有提醒,false=无提醒
- */
- public boolean hasClockAlert() {
- return (mAlertDate > 0 ? true : false);
- }
-
- /**
- * 获取笔记的文本内容
- * @return String:笔记内容
- */
- public String getContent() {
- return mContent;
- }
-
- /**
- * 获取笔记的提醒时间戳
- * @return long:提醒时间(0表示无)
- */
- public long getAlertDate() {
- return mAlertDate;
- }
-
- /**
- * 获取笔记的最后修改时间戳
- * @return long:修改时间
- */
- public long getModifiedDate() {
- return mModifiedDate;
- }
-
- /**
- * 获取笔记背景色对应的资源ID(通过{@link NoteBgResources}映射)
- * @return int:背景色资源ID
- */
- public int getBgColorResId() {
- return NoteBgResources.getNoteBgResource(mBgColorId);
- }
-
- /**
- * 获取笔记的背景色ID(对应{@link NoteBgResources}中的标识)
- * @return int:背景色ID
- */
- public int getBgColorId() {
- return mBgColorId;
- }
-
- /**
- * 获取笔记标题栏的背景色资源ID(通过{@link NoteBgResources}映射)
- * @return int:标题栏背景色资源ID
- */
- public int getTitleBgResId() {
- return NoteBgResources.getNoteTitleBgResource(mBgColorId);
- }
-
- /**
- * 获取笔记的复选框模式
- * @return int:模式(普通文本/复选框列表)
- */
- public int getCheckListMode() {
- return mMode;
- }
-
- /**
- * 获取笔记的ID(数据库主键)
- * @return long:笔记ID(0表示新笔记)
- */
- public long getNoteId() {
- return mNoteId;
- }
-
- /**
- * 获取笔记所属的文件夹ID
- * @return long:文件夹ID
- */
- public long getFolderId() {
- return mFolderId;
- }
-
- /**
- * 获取笔记关联的组件ID
- * @return int:组件ID(INVALID_APPWIDGET_ID表示无)
- */
- public int getWidgetId() {
- return mWidgetId;
- }
-
- /**
- * 获取笔记关联的组件类型
- * @return int:组件类型(TYPE_WIDGET_INVALIDE表示无)
- */
- public int getWidgetType() {
- return mWidgetType;
- }
-
- // ====================== 回调接口(笔记设置变化通知) ======================
- /**
- * 笔记设置变化的回调接口,用于通知外部组件(如UI)属性变化
- * 包含背景色、提醒时间、组件、复选框模式的变化回调
- */
- public interface NoteSettingChangedListener {
- /**
- * 笔记背景色变化时的回调
- */
- void onBackgroundColorChanged();
-
- /**
- * 笔记提醒时间设置/取消时的回调
- * @param date 新的提醒时间戳(0表示取消)
- * @param set 是否设置提醒(true=设置,false=取消)
- */
- void onClockAlertChanged(long date, boolean set);
-
- /**
- * 笔记关联的组件变化时的回调(如从组件创建笔记、删除笔记)
- */
- void onWidgetChanged();
-
- /**
- * 笔记复选框模式切换时的回调(普通文本↔复选框列表)
- * @param oldMode 切换前的旧模式
- * @param newMode 切换后的新模式
- */
- void onCheckListModeChanged(int oldMode, int newMode);
- }
-}
\ No newline at end of file
diff --git a/小米便签开源代码的泛读报告.docx b/小米便签开源代码的泛读报告.docx
deleted file mode 100644
index e541aaa..0000000
Binary files a/小米便签开源代码的泛读报告.docx and /dev/null differ
diff --git a/开源软件的质量分析报告文档.docx b/开源软件的质量分析报告文档.docx
deleted file mode 100644
index 81b56aa..0000000
Binary files a/开源软件的质量分析报告文档.docx and /dev/null differ