上传所有注释代码以及注释文档 #55

Merged
pg6wepubk merged 6 commits from develop into master 3 weeks ago

@ -14,6 +14,12 @@
* limitations under the License.
*/
/*
*Contact.java
*
* 2025-12-13
* 21
*/
package net.micode.notes.data;
import android.content.Context;
@ -25,10 +31,22 @@ import android.util.Log;
import java.util.HashMap;
/**
*Contact
*
*<P></P>
*
*
* @author
* @version 1.0
* @since []
*/
public class Contact {
//HashMap表示联系人和电话号码之间的映射关系。只声明不new是延迟初始化的表现
private static HashMap<String, String> sContactCache;
private static final String TAG = "Contact";
//说明电话号码格式可兼容国际区号、前缀0等多种格式
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
@ -36,17 +54,31 @@ public class Contact {
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/**
*
* <P></P>
* @param context 访ContentResolver
* @param phoneNumber 0
* @return code null
* @throws
* @see android.provider.ContactsContract.CommonDataKinds
*/
public static String getContact(Context context, String phoneNumber) {
//不到真正要用的时候不给对象分配内存。第一次被调用时才new。
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
//缓存命中,直接返回电话号码
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
//构造匹配串,提取数字核心部分
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
//cursor是数据库游标初始位置是-1query把SQL拼装好后交给系统联系人Provider
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
@ -54,18 +86,19 @@ public class Contact {
new String[] { phoneNumber },
null);
//指针移到第一行成功返回true
if (cursor != null && cursor.moveToFirst()) {
try {
String name = cursor.getString(0);
sContactCache.put(phoneNumber, name);
sContactCache.put(phoneNumber, name); //将号码-姓名键值对放进内存缓存
return name;
} catch (IndexOutOfBoundsException e) {
} catch (IndexOutOfBoundsException e) { //捕获异常,索引超出列范围的情况,返回错误日志
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
} finally { //无论是否发生异常都必须释放cursor。
cursor.close();
}
} else {
} else { //查询失败,输出日志信息
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}

@ -14,43 +14,73 @@
* limitations under the License.
*/
/*
*Notes.java
*
* 2025-12-06
* 37
*/
package net.micode.notes.data;
import android.net.Uri;
/**
*Notes便
* <P>URI便/Intent</P>
* <b>static final</b>
* @author
* @since []
*/
public class Notes {
public static final String AUTHORITY = "micode_notes";
public static final String TAG = "Notes";
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
//一、ContentProvider权威域名
public static final String AUTHORITY = "micode_notes"; //拼接URI的前缀
public static final String TAG = "Notes"; //日志显示Notes
//二、便签/文件夹/系统文件夹 类型常量
public static final int TYPE_NOTE = 0; //普通文本便签类型常量为0
public static final int TYPE_FOLDER = 1; //文件夹类型常量为1
public static final int TYPE_SYSTEM = 2; //系统文件夹如回收站类型常量为2
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_TEMPORARY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*/
public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
//三、系统保留文件夹 ID
public static final int ID_ROOT_FOLDER = 0; //默认文件夹ID为0
public static final int ID_TEMPORARY_FOLDER = -1; //临时文件夹
public static final int ID_CALL_RECORD_FOLDER = -2; //通话记录文件夹ID保存由通话备忘功能生成的便签
public static final int ID_TRASH_FOLDER = -3;
//四、Intent是什么?
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; //提醒时间戳
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; //便签背景颜色
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; //桌面便签小部件
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; //桌面便签小部件类型
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; //便签父文件夹ID
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; //通话记录时间戳
//五、桌面小部件类型常量
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
/**
*便MIME
* Android ContentResolver // URI MIME
*/
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; //文本便签MIME类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; //通话备忘MIME类型
}
//七、基础URI
/**
* Uri to query all notes and folders
*/
@ -58,12 +88,18 @@ public class Notes {
/**
* Uri to query data
*
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
//八、数据库列名接口 —— Note 表
/**
* NoteColumns便/
* 便ID,PARENT_ID,
*/
public interface NoteColumns {
/**
* The unique ID for a row
* The unique ID for a ro
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
@ -167,12 +203,18 @@ public class Notes {
public static final String VERSION = "version";
}
//九、数据库列名接口 —— Data 表
/**
* DataColumns
*/
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
public static final String ID = "_id"; //主键是_id
/**
* The MIME type of the item represented by this row.
@ -206,63 +248,70 @@ public class Notes {
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* Generic data column, the meaning is {@link #MIME_TYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA1 = "data1";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* Generic data column, the meaning is {@link #MIME_TYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA2 = "data2";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* Generic data column, the meaning is {@link #MIME_TYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA3 = "data3";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* Generic data column, the meaning is {@link #MIME_TYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* Generic data column, the meaning is {@link #MIME_TYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA5 = "data5";
}
//十、文本便签实体常量类
//文本便签TextNote类实现DataColumns接口中声明的方法
public static final class TextNote implements DataColumns {
/**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
*/
public static final String MODE = DATA1;
public static final String MODE = DATA1; //清单模式or普通文本模式
public static final int MODE_CHECK_LIST = 1;
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; //MIME类型为集合多条
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; //MIME类型为单条
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
public static final class CallNote implements DataColumns {
/**
*便
* CallNoteDataColumns
*/
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
*/
public static final String CALL_DATE = DATA1;
public static final String CALL_DATE = DATA1; //DATA1是数据库中的真实列名将通话的时间戳存入DATA1列中
/**
* Phone number for this record

@ -14,6 +14,11 @@
* limitations under the License.
*/
/*
*NotesDatabaseHelper.java
*
* 2025-12-13
*/
package net.micode.notes.data;
import android.content.ContentValues;
@ -26,12 +31,32 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
/**
*便
<P>
*
*<ul>
* <li>/ note data </li>
* <li>便便</li>
* <li></li>
* <li></li>
*</ul>
</P>
*
* @author
* @version {@link #DB_VERSION} 4
* @since 2010-2011
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
*
*/
private static final String DB_NAME = "note.db";
private static final int DB_VERSION = 4;
/**表明常量接口*/
public interface TABLE {
public static final String NOTE = "note";
@ -40,10 +65,19 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "NotesDatabaseHelper";
//类加载时不创建NotesDatabaseHelper实例(mInstance),真正需要使用数据库时才调用getInstance初始化节省应用启动时的内存和资源开销。
private static NotesDatabaseHelper mInstance;
//二、建表SQL初始化note和data表同时添加note_id_index索引列
/**
* NotesNoteColumns
* NotesNoteColumns便IDPARENT_IDNotes
* NOT NULLNULLDEFAULT 0 0NOT NULLDEFAULT
* strftimeSQLite%sUnixnow'
*/
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
"CREATE TABLE " + TABLE.NOTE + "(" + //开始建表表名是TABLE.NOTE(note)
NoteColumns.ID + " INTEGER PRIMARY KEY," +
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
@ -63,6 +97,13 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")";
/**
* Data SQLNotesDataColumns
* <p>
* {@link DataColumns#NOTE_ID} note.id <br>
* data1~data5 {@link DataColumns#MIME_TYPE}
* </p>
*/
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
@ -78,12 +119,22 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";
/**
*data(NOTE_ID)note_id_index
* 便SELECT * FROM data WHERE note_id=?
*/
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
//三、创建Note表触发器在文件夹下便签数量变化时自动增减便签数量(notes_count)的值
/**
* Increase folder's note count when move note to the folder
* increase_folder_count_on_update
* noteparent_id
* Notenotes_count=notes_count+1,id=new.parent_id
* 便
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+
@ -132,8 +183,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END";
//四、Data 表触发器自动同步便签摘要snippet)
/**
* Update note's content when insert data with type {@link DataConstants#NOTE}
* DATAmime_typenote()
* notesnippetcontentnoteid=note_id
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
@ -172,7 +226,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END";
/**
* Delete datas belong to note which has been deleted
* Delete data belong to note which has been deleted
* notedatanote_idnoteid
* data-
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
@ -184,6 +240,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* Delete notes belong to folder which has been deleted
* notenoteparent_idid
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
@ -199,24 +256,37 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " +
" AFTER UPDATE ON " + TABLE.NOTE +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLDER +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLDER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
* Android/
* @param context 访
*/
public NotesDatabaseHelper(Context context) {
/** super(SQLiteOpenHelper)
* @param context context
* @param DB_NAME
* @param null (cursor),null
* @param DB_VERSION
*/
super(context, DB_NAME, null, DB_VERSION);
}
//完成note表的全量初始化
public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db);
createSystemFolder(db);
Log.d(TAG, "note table has been created");
db.execSQL(CREATE_NOTE_TABLE_SQL); //执行SQL语句创建note表
reCreateNoteTableTriggers(db); //重建该表关联的触发器
createSystemFolder(db); //初始化系统默认文件夹数据
Log.d(TAG, "note table has been created"); //打印日志确认note表成功创建
}
//批量重建触发器,先删除旧的,再建立新的
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
@ -235,7 +305,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
//向note表插入四个系统默认文件夹通话记录、根、临时、回收站。保证应用首次启动时有基础的文件夹结构。
private void createSystemFolder(SQLiteDatabase db) {
//ContentValues类用于存储键值对
ContentValues values = new ContentValues();
/**
@ -243,12 +315,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
*/
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
db.insert(TABLE.NOTE, null, values); //向note表插入通话记录文件夹数据
/**
* root folder which is default folder
*/
values.clear();
values.clear(); //清空原有的所有键值对,避免复用容器时残留上一个文件夹的字段值
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
@ -257,7 +329,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
* temporary folder which is used for moving note
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.ID, Notes.ID_TEMPORARY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
@ -265,7 +337,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
* create trash folder
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
@ -287,17 +359,24 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
/**
* synchronized线线if
* getInstance
*/
static synchronized NotesDatabaseHelper getInstance(Context context) {
//首次调用该方法时,才创建实例;若已创建,则直接复用
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
}
return mInstance;
}
//@override是Java中的一种注解用于明确表示子类的方法是对父类方法的重写实现多态性
@Override
public void onCreate(SQLiteDatabase db) {
createNoteTable(db);
createDataTable(db);
createNoteTable(db); //初始化笔记表
createDataTable(db); //初始化数据表
}
@Override
@ -333,13 +412,15 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
}
}
//v1到v2的升级删除旧的note data表清空所有用户数据重建新的
private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); //执行具体的SQL语句删除旧的note表
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); //删除旧的data表
createNoteTable(db);
createDataTable(db);
}
//v2到v3的升级清除无用触发器新增gtask_id列新增回收站文件夹
private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
@ -350,11 +431,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
+ " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
//v3到v4的升级为note表新增version列且约束非空默认为0
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");

@ -14,6 +14,12 @@
* limitations under the License.
*/
/*
* NotesProvider.java
*
* 2025-12-13
* 68
*/
package net.micode.notes.data;
@ -34,24 +40,58 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* 便
*<P>ContentProviderSQLitenote.db</P>
* <ul>
* <li>CRUD()</li>
* <li></li>
* <li>URI</li>
* </ul>
* <p>URI</p>
* <pre>
* content://micode_notes/note 查询所有便签
* content://micode_notes/note/123 查询 ID=123 的便签
* content://micode_notes/data 查询所有数据行(附件、文本块、通话记录)
* content://micode_notes/search_suggest/xxx 系统搜索框建议接口
* </pre>
*
* @author
* @since 2010-2011
*/
public class NotesProvider extends ContentProvider {
//UriMatcher用于匹配uri,在ContentProvider中分辨出查询者想要查询哪个数据表
private static final UriMatcher mMatcher;
//mHelper是一个便签数据库辅助类单例
private NotesDatabaseHelper mHelper;
private static final String TAG = "NotesProvider";
private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4;
private static final int URI_NOTE = 1; //匹配所有note的uri标识
private static final int URI_NOTE_ITEM = 2; //匹配单条note的uri标识
private static final int URI_DATA = 3; //匹配所有data行的uri标识包括文本块、附件、通话记录
private static final int URI_DATA_ITEM = 4; //匹配单条data行的uri标识
private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;
private static final int URI_SEARCH = 5; //执行实际搜索请求
private static final int URI_SEARCH_SUGGEST = 6; //提供搜索建议,实时联想输入关键词的匹配项
/**
* staticAndroid
* UriMatcheruri notedatasearch
* query/insert/delete/update URI
* 使staticqueryuri
*/
static {
//初始化常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
/**
* addURIuri
* uricontent://<AUTHORITY>/<path>(/?)
* "note/#"'#'id
*/
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
@ -65,6 +105,15 @@ public class NotesProvider extends ContentProvider {
* x'0A' represents the '\n' character in sqlite. For title and content in the search result,
* we will trim '\n' and white space in order to show more information.
*/
/**
* 1.noteidsnippetSearchManager NoteColumns.ID SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA
* 2.SNIPPET REPLACEx'0A' '\n'
* TRIM
* SUGGEST_COLUMN_TEXT_1
*3.
* R.drawable.search_resultIntent.ACTION_VIEW
* Notes.TextNote.CONTENT_TYPE
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
@ -73,30 +122,55 @@ public class NotesProvider extends ContentProvider {
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
/**
* NOTES_SEARCH_PROJECTION
* '?'
*
*
*/
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLDER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
//ContentProvider 返回数据库辅助类单例
@Override
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
/**
* ActivitySearchView访
* note/data// URIURIURISQL
* Cursor UI
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs selection
* @param sortOrder
* @return cursor
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
//初始化游标,默认空
Cursor c = null;
//db获取只读数据库连接查询
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
//mMatcher 在静态代码块里预注册了6种 URI 模式,通过match()返回的整数常量决定走哪条分支
switch (mMatcher.match(uri)) {
case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
//解析uri路径中的idgetPathSegments()返回[path,#]
id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
@ -117,6 +191,7 @@ public class NotesProvider extends ContentProvider {
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
//获取关键词
String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
@ -126,36 +201,54 @@ public class NotesProvider extends ContentProvider {
searchString = uri.getQueryParameter("pattern");
}
//空关键词时返回null无需查询
if (TextUtils.isEmpty(searchString)) {
return null;
}
try {
//关键词格式化
searchString = String.format("%%%s%%", searchString);
//执行查询
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
} catch (IllegalStateException ex) {
} catch (IllegalStateException ex) { //捕获try中出现的异常打印日志
Log.e(TAG, "got exception: " + ex.toString());
}
break;
//传了没注册过的uri直接抛异常防止误调用
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
//说明查询到结果,将查询返回的 Cursor 与 ContentResolver、当前 URI 绑定;
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
/**
* ActivityServicenotedata
* content URI note\datauri
* @param uri uri
* @param values note_id=100
* @return uri
*
* @author
* @date 2025-12-13
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();
SQLiteDatabase db = mHelper.getWritableDatabase(); //获取可写数据库连接
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
case URI_DATA:
//插入笔记的具体内容因此先检查values中是否包含DATA_COLUMNS.NOTE_ID
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
@ -167,26 +260,39 @@ public class NotesProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
//通知所有监听该 URI 的 Cursor “数据已变更”
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
//通知该 URI 的数据变更,比如插入笔记内容后,刷新笔记详情页的内容展示。
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
//返回插入的单条记录的标准uri,将插入记录的ID拼接在原始URI末尾
return ContentUris.withAppendedId(uri, insertedId);
}
/**
* ID ID0
* @param uri URI
* @param selection
* @param selectionArgs
* @return count
*
* @author
* @date 2025-12-13
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
String id = null; //存储单条记录的ID从uri中解析
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
boolean deleteData = false; // 标记是否删除的是DATA表数据
switch (mMatcher.match(uri)) {
case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
@ -195,8 +301,8 @@ public class NotesProvider extends ContentProvider {
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
* ID that smaller than 0 is system folder which is not allowed to trash
* ID<0
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
@ -213,12 +319,14 @@ public class NotesProvider extends ContentProvider {
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
deleteData = true; //标记删除的是data表数据
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
//如果删除的是data表内容需要关联note表删除内容后刷新笔记列表
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
@ -227,6 +335,17 @@ public class NotesProvider extends ContentProvider {
return count;
}
/**
* ID
* @param uri URI
* @param values
* @param selection
* @param selectionArgs
* @return
*
* @author
* @date 2025-12-13
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
@ -267,26 +386,44 @@ public class NotesProvider extends ContentProvider {
return count;
}
/**
* SQLANDselection
* @param selection WHERE
* @return "AND(selection)"
*/
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
/**
* idnote.version+1
* @param id 便ID
* @param selection
* @param selectionArgs
*/
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
StringBuilder sql = new StringBuilder(120); //120是初始SQL语句长度
sql.append("UPDATE ");
sql.append(TABLE.NOTE);
sql.append(" SET ");
sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
//有ID或者有selection时才需要加WHERE子句
if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE ");
}
//场景1仅有ID精准更新单条笔记
if (id > 0) {
sql.append(NoteColumns.ID + "=" + String.valueOf(id));
}
//场景2有自定义selection(批量/组合条件更新)
if (!TextUtils.isEmpty(selection)) {
//若已有ID拼接为AND(selection);若没有ID直接用selection
String selectString = id > 0 ? parseSelection(selection) : selection;
//替换selection中的?占位符为实际参数
for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args);
}
@ -296,6 +433,7 @@ public class NotesProvider extends ContentProvider {
mHelper.getWritableDatabase().execSQL(sql.toString());
}
//返回给定URI的MIME类型暂未实现返回null
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub

@ -24,12 +24,31 @@ import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* gtask
* gtask
* MetaData?便便ID便
* gid?google
* JSON?MetaData/
*
* Task
*/
public class MetaData extends Task {
/**
* MetaData.classMetaDataclass
* getSimpleNameMetaData
*/
private final static String TAG = MetaData.class.getSimpleName();
//存储当前元数据关联的gid
private String mRelatedGid = null;
/**
*
* gtask IDJSONTask
* @param gid
* @param metaInfo JSONObjectMetaDataJSON
*/
public void setMeta(String gid, JSONObject metaInfo) {
try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
@ -40,17 +59,27 @@ public class MetaData extends Task {
setName(GTaskStringUtils.META_NOTE_NAME);
}
/**
* gtask ID
* @return gtask ID(null
*/
public String getRelatedGid() {
return mRelatedGid;
}
//笔记内容不为空就保存
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
/**
* gtaskJSON
* @param js gtaskJSON
*/
@Override
public void setContentByRemoteJSON(JSONObject js) {
//调用父类方法初始化task基础属性
super.setContentByRemoteJSON(js);
if (getNotes() != null) {
try {
@ -63,17 +92,23 @@ public class MetaData extends Task {
}
}
/**JSON
* MetaDataSQLite
* 便APP
*/
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
//不支持生成本地JSON
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
//无需计算同步动作
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");

@ -20,24 +20,29 @@ import android.database.Cursor;
import org.json.JSONObject;
/**
* Node
*
*
*/
public abstract class Node {
public static final int SYNC_ACTION_NONE = 0;
public static final int SYNC_ACTION_NONE = 0; //无同步操作
public static final int SYNC_ACTION_ADD_REMOTE = 1;
public static final int SYNC_ACTION_ADD_REMOTE = 1; //远程添加操作
public static final int SYNC_ACTION_ADD_LOCAL = 2;
public static final int SYNC_ACTION_ADD_LOCAL = 2; //本地添加操作
public static final int SYNC_ACTION_DEL_REMOTE = 3;
public static final int SYNC_ACTION_DEL_REMOTE = 3; //远程删除操作
public static final int SYNC_ACTION_DEL_LOCAL = 4;
public static final int SYNC_ACTION_DEL_LOCAL = 4; //本地删除操作
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
public static final int SYNC_ACTION_UPDATE_REMOTE = 5; //远程更新操作
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
public static final int SYNC_ACTION_UPDATE_LOCAL = 6; //本地更新操作
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; //更新冲突
public static final int SYNC_ACTION_ERROR = 8;
public static final int SYNC_ACTION_ERROR = 8; //同步出错
private String mGid;
@ -47,23 +52,30 @@ public abstract class Node {
private boolean mDeleted;
//无参构造法创建Node对象时无需传入任何参数
public Node() {
mGid = null;
mName = "";
mGid = null; //常由云端生成
mName = ""; //不初始化为null避免后续调用mName.length等方法时触发空指针异常
mLastModified = 0;
mDeleted = false;
}
//JSONObject是JSON实例的抽象类生成同步创建操作JSON数据返回操作ID
public abstract JSONObject getCreateAction(int actionId);
//生成同步更新操作的JSON数据返回操作ID
public abstract JSONObject getUpdateAction(int actionId);
//这是一个方法根据远程JSON数据设置内容远程数据同步到本地具体操作
public abstract void setContentByRemoteJSON(JSONObject js);
//这是一个方法根据本地JSON数据设置内容本地数据处理具体操作
public abstract void setContentByLocalJSON(JSONObject js);
//将本地内容转换成JSON数据,同步到远程
public abstract JSONObject getLocalJSONFromContent();
//通过游标获取同步操作类型在前面声明为类型变量0-8
public abstract int getSyncAction(Cursor c);
public void setGid(String gid) {

@ -34,7 +34,11 @@ import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException;
import org.json.JSONObject;
/**
*便
* JSONJSON /
* 便
*/
public class SqlData {
private static final String TAG = SqlData.class.getSimpleName();
@ -47,16 +51,21 @@ public class SqlData {
public static final int DATA_ID_COLUMN = 0;
//区分数据项,比如文本、图片、附件等,由此决定数据解析方式
public static final int DATA_MIME_TYPE_COLUMN = 1;
//存储数据项的核心内容
public static final int DATA_CONTENT_COLUMN = 2;
//存储content辅助信息比如图片的宽度大小等
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
//更多扩展信息
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver;
//false表示新创建的未入库数据项true表示数据库中已经创建的数据项
private boolean mIsCreate;
private long mDataId;
@ -71,6 +80,10 @@ public class SqlData {
private ContentValues mDiffDataValues;
/**
* mContentResolver
* @param context
*/
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
@ -97,13 +110,23 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
/**
* JSONSqlData
* mDifferentValues
* JSON js->
* @param js
* @throws JSONException
*/
public void setContent(JSONObject js) throws JSONException {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
//新创建的未入库数据项或者是当前实例的已有ID和JSON中解析的ID不一样说明该字段发生了变更
if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId);
}
mDataId = dataId;
//判断JSON中是否包含MIME_TYPE键否则默认为纯文本
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE;
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
@ -111,18 +134,21 @@ public class SqlData {
}
mDataMimeType = dataMimeType;
//判断JSON中是否包含CONTENT键如便签文本等否则赋值为空串
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
if (mIsCreate || !mDataContent.equals(dataContent)) {
mDiffDataValues.put(DataColumns.CONTENT, dataContent);
}
mDataContent = dataContent;
//判断DATA1键如图片宽度等
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
if (mIsCreate || mDataContentData1 != dataContentData1) {
mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
}
mDataContentData1 = dataContentData1;
//判断DATA3键
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
@ -144,28 +170,39 @@ public class SqlData {
return js;
}
/**
*
*
* @param noteId 便ID
* @param validateVersion
* @param version
*/
public void commit(long noteId, boolean validateVersion, long version) {
//新创建的项,“插入”
if (mIsCreate) {
//未入库数据库未生成主键所以当前数据项ID为无效值
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID);
}
mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try {
try { //从数据库返回的地址里抠出数据项的ID
mDataId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
}
} else {
} else { //数据库里本来就有这个项,只是更改内容
if (mDiffDataValues.size() > 0) {
int result = 0;
//不需要防止多设备更改冲突
if (!validateVersion) {
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else {
} else { //需要防止多设备更改冲突
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE

@ -37,12 +37,18 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* sqlNote
*
*
* AndroidContentProvider
*/
public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName();
private static final int INVALID_ID = -99999;
//记录需要从小米便签数据库中查询的字段
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,
@ -52,6 +58,7 @@ public class SqlNote {
NoteColumns.VERSION
};
//将PROJECTION_NOTE中的每个字段按顺序赋索引值0-16便于从cursor中快速获取
public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1;
@ -86,11 +93,11 @@ public class SqlNote {
public static final int VERSION_COLUMN = 16;
private Context mContext;
private Context mContext; //上下文对象用于获取系统服务如ContentResolver
private ContentResolver mContentResolver;
private ContentResolver mContentResolver; //操作ContentProvider数据库交互
private boolean mIsCreate;
private boolean mIsCreate; //标记当前笔记是否为新创建(未存入数据库)
private long mId;
@ -100,15 +107,15 @@ public class SqlNote {
private long mCreatedDate;
private int mHasAttachment;
private int mHasAttachment; //是否有附件01
private long mModifiedDate;
private long mParentId;
private String mSnippet;
private String mSnippet; // 笔记摘要(简短内容,用于列表展示)
private int mType;
private int mType; // 笔记类型Notes.TYPE_NOTE-普通笔记TYPE_FOLDER-文件夹)
private int mWidgetId;
@ -118,10 +125,11 @@ public class SqlNote {
private long mVersion;
private ContentValues mDiffNoteValues;
private ContentValues mDiffNoteValues; //存储需要更新的字段
private ArrayList<SqlData> mDataList;
private ArrayList<SqlData> mDataList; // 笔记关联的数据列表如文本内容、图片等由SqlData管理
//初始化新笔记
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -143,9 +151,12 @@ public class SqlNote {
mDataList = new ArrayList<SqlData>();
}
//从cursor加载已有笔记
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
//从数据库加载,标记为已存在
mIsCreate = false;
loadFromCursor(c);
mDataList = new ArrayList<SqlData>();
@ -154,10 +165,13 @@ public class SqlNote {
mDiffNoteValues = new ContentValues();
}
//通过id加载已有笔记
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
//根据id查询数据库并加载数据
loadFromCursor(id);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
@ -169,13 +183,14 @@ public class SqlNote {
private void loadFromCursor(long id) {
Cursor c = null;
try {
//查询指定id的笔记
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(id)
}, null);
if (c != null) {
c.moveToNext();
loadFromCursor(c);
c.moveToNext(); //移动到第一条记录
loadFromCursor(c); //从cursor加载数据
} else {
Log.w(TAG, "loadFromCursor: cursor = null");
}
@ -200,10 +215,12 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN);
}
//加载笔记的关联数据(如文本内容)
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
mDataList.clear(); //清空现有数据
try {
//根据note_id=mId查询当前笔记关联的所有数据
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] {
String.valueOf(mId)
@ -226,15 +243,26 @@ public class SqlNote {
}
}
/**-JSON便
* JSON---
* setContentJSONSqlNote---
*/
public boolean setContent(JSONObject js) {
try {
//解析JSON中的笔记元数据note
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) {
}
//文件夹类型,仅更新摘要和类型
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) : "";
//如果是新创建或者内容(snippet)有变化时记录差异
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
@ -246,14 +274,21 @@ public class SqlNote {
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
}
//普通笔记类型,更新所有元数据和关联数据
else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
//关联数据数组
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
//逐个解析元数据字段仅仅记录变化的部分到差异容器这里是id字段
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;
if (mIsCreate || mAlertDate != alertDate) {
@ -261,6 +296,7 @@ public class SqlNote {
}
mAlertDate = alertDate;
//背景颜色字段
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
if (mIsCreate || mBgColorId != bgColorId) {
@ -268,6 +304,7 @@ public class SqlNote {
}
mBgColorId = bgColorId;
//创建日期字段
long createDate = note.has(NoteColumns.CREATED_DATE) ? note
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
if (mIsCreate || mCreatedDate != createDate) {
@ -275,6 +312,7 @@ public class SqlNote {
}
mCreatedDate = createDate;
//有无附件字段
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
.getInt(NoteColumns.HAS_ATTACHMENT) : 0;
if (mIsCreate || mHasAttachment != hasAttachment) {
@ -282,6 +320,7 @@ public class SqlNote {
}
mHasAttachment = hasAttachment;
//修改日期字段
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
if (mIsCreate || mModifiedDate != modifiedDate) {
@ -289,6 +328,7 @@ public class SqlNote {
}
mModifiedDate = modifiedDate;
//父文件夹字段
long parentId = note.has(NoteColumns.PARENT_ID) ? note
.getLong(NoteColumns.PARENT_ID) : 0;
if (mIsCreate || mParentId != parentId) {
@ -296,6 +336,7 @@ public class SqlNote {
}
mParentId = parentId;
//内容字段
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
@ -303,6 +344,7 @@ public class SqlNote {
}
mSnippet = snippet;
//笔记类型字段
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
@ -310,6 +352,7 @@ public class SqlNote {
}
mType = type;
//桌面组件id字段
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
: AppWidgetManager.INVALID_APPWIDGET_ID;
if (mIsCreate || mWidgetId != widgetId) {
@ -317,6 +360,7 @@ public class SqlNote {
}
mWidgetId = widgetId;
//桌面组件类型字段
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
if (mIsCreate || mWidgetType != widgetType) {
@ -324,6 +368,7 @@ public class SqlNote {
}
mWidgetType = widgetType;
//原始父文件夹字段
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
if (mIsCreate || mOriginParent != originParent) {
@ -334,6 +379,8 @@ public class SqlNote {
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null;
//查找已存在的sqlData(通过ID匹配)
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
for (SqlData temp : mDataList) {
@ -343,12 +390,13 @@ public class SqlNote {
}
}
//不存在则创建新的sqlData
if (sqlData == null) {
sqlData = new SqlData(mContext);
mDataList.add(sqlData);
}
sqlData.setContent(data);
sqlData.setContent(data); //更新数据内容
}
}
} catch (JSONException e) {
@ -359,6 +407,7 @@ public class SqlNote {
return true;
}
//将笔记内容转换成JSON对象用于同步发送数据
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
@ -369,6 +418,7 @@ public class SqlNote {
}
JSONObject note = new JSONObject();
//普通笔记:所有元数据+关联数据
if (mType == Notes.TYPE_NOTE) {
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate);
@ -384,6 +434,7 @@ public class SqlNote {
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
//关联数据转换成JSON数组
JSONArray dataArray = new JSONArray();
for (SqlData sqlData : mDataList) {
JSONObject data = sqlData.getContent();
@ -392,7 +443,9 @@ public class SqlNote {
}
}
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
}
//文件夹/系统文件夹仅包含ID、类型、摘要
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);
@ -407,11 +460,16 @@ public class SqlNote {
return null;
}
/**
*setContent(JSONObject js)
*/
//设置父文件夹ID并记录差异
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
}
//设置GTask ID 用于同步
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
@ -420,10 +478,14 @@ public class SqlNote {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
//重置本地修改标记(用于修改后)
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}
/**
*
*/
public long getId() {
return mId;
}
@ -440,14 +502,20 @@ public class SqlNote {
return mType == Notes.TYPE_NOTE;
}
//数据库提交方法:保存/更新笔记
public void commit(boolean validateVersion) {
//如果是新笔记,就插入到数据库
if (mIsCreate) {
//移除无效ID,因为数据库会自动生成ID
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID);
}
//插入笔记元数据到ContentProvider
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
try {
//从返回的uri里获取新生成的ID
mId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
@ -457,25 +525,34 @@ public class SqlNote {
throw new IllegalStateException("Create thread id failed");
}
//提交关联数据,如文本内容
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1);
}
}
} else {
}
//不是新笔记,已经存在,就执行“更新”操作
else {
//验证ID有效性
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) {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId)
});
} else {
}
// 验证版本:当数据库版本<=当前版本时更新
else {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] {
@ -487,6 +564,7 @@ public class SqlNote {
}
}
//提交关联数据
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion);
@ -494,12 +572,12 @@ public class SqlNote {
}
}
// refresh local info
// refresh local info
loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues.clear();
mIsCreate = false;
mDiffNoteValues.clear(); //清空差异字段
mIsCreate = false; //标记为已创建
}
}

@ -31,19 +31,22 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Node Node
*/
public class Task extends Node {
private static final String TAG = Task.class.getSimpleName();
private boolean mCompleted;
private boolean mCompleted; //Google 任务是否已完成(勾选状态)
private String mNotes;
private String mNotes; //任务备注正文
private JSONObject mMetaInfo;
private JSONObject mMetaInfo;//定义Task的MetaData的JSON数据格式
//指向当前任务点的前兄弟任务的指针/引用,用于在内存中关联当前任务的前一个任务
private Task mPriorSibling;
private TaskList mParent;
private TaskList mParent; //定义所属的Google TaskList
public Task() {
super();
@ -54,6 +57,11 @@ public class Task extends Node {
mMetaInfo = null;
}
/**JSONz
*
* @param actionId
* @return JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -68,6 +76,10 @@ public class Task extends Node {
// index
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
/**JSONObject
* +
* entitygid
*/
// entity_delta
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
@ -77,6 +89,7 @@ public class Task extends Node {
if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
}
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
// parent_id
@ -95,7 +108,10 @@ public class Task extends Node {
}
} catch (JSONException e) {
//toString输出异常本身的类型和描述
Log.e(TAG, e.toString());
//还原异常的发生现场,通过栈进行追踪
e.printStackTrace();
throw new ActionFailureException("fail to generate task-create jsonobject");
}
@ -103,6 +119,11 @@ public class Task extends Node {
return js;
}
/**JSON
*
* @param actionId
* @return JSON +
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -121,7 +142,7 @@ public class Task extends Node {
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_NOTES, getNotes());//更新备注
}
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
@ -135,7 +156,12 @@ public class Task extends Node {
return js;
}
/**
* JSON
* @param js JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
// id
@ -175,13 +201,23 @@ public class Task extends Node {
}
}
/**
* 便JSONTask
* 便
* @param js
*/
public void setContentByLocalJSON(JSONObject js) {
//若是本地JSON不含便签元信息+内容数据,输出错误日志
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
}
try {
/**
* note便便便
* dataArray:便
*/
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
@ -204,6 +240,7 @@ public class Task extends Node {
}
}
//返回完整 JSON供本地数据库保存或上传云端
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
@ -247,6 +284,7 @@ public class Task extends Node {
}
}
//将小米便签的MetaData元数据对象中的JSON格式解析为mMetaInfo
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
@ -258,6 +296,11 @@ public class Task extends Node {
}
}
/**
* 便cursortaskmMetaInfo
* GID
*
*/
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
@ -281,6 +324,7 @@ public class Task extends Node {
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()) {
@ -290,12 +334,18 @@ public class Task extends Node {
// apply remote to local
return SYNC_ACTION_UPDATE_LOCAL;
}
} else {
} 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;
}
/**SqlNote.SYNC_ID_COLUMNSqlNote
*
* ID / ID
* getLastModified()
*/
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
return SYNC_ACTION_UPDATE_REMOTE;
@ -311,6 +361,7 @@ public class Task extends Node {
return SYNC_ACTION_ERROR;
}
//空任务、空备注、无元数据 → 不值得存/上传,直接跳过
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);

@ -33,9 +33,9 @@ import java.util.ArrayList;
public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();
private int mIndex;
private int mIndex; //列表索引找到特定的task
private ArrayList<Task> mChildren;
private ArrayList<Task> mChildren; //task列表
public TaskList() {
super();
@ -43,6 +43,7 @@ public class TaskList extends Node {
mIndex = 1;
}
//生成TaskList“创建任务”的JSON
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -74,18 +75,20 @@ public class TaskList extends Node {
return js;
}
//“更新操作”的JSON
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
// action_id 操作ID追踪操作结果
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id
// id(要更新的任务/任务列表GID
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta
@ -106,7 +109,7 @@ public class TaskList extends Node {
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
// id
// id本地和远端ID一致
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
}
@ -130,6 +133,7 @@ public class TaskList extends Node {
}
public void setContentByLocalJSON(JSONObject js) {
//本地JSON为空或者是否包含核心字段META_HEAD_NOTE
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
}
@ -137,6 +141,7 @@ public class TaskList extends Node {
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);
@ -157,6 +162,10 @@ public class TaskList extends Node {
}
}
/**
* MIUI_FOLDER_PREFFIX 便
* @return JSON
*/
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();
@ -164,6 +173,7 @@ public class TaskList extends Node {
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);
@ -183,10 +193,11 @@ public class TaskList extends Node {
}
}
//使用游标判断 本地和远端状态,返回同步操作类型号
public int getSyncAction(Cursor c) {
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update
// there is no local update 本地无更新
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side
return SYNC_ACTION_NONE;
@ -194,12 +205,14 @@ public class TaskList extends Node {
// apply remote to local
return SYNC_ACTION_UPDATE_LOCAL;
}
} else {
} else { //本地有更新检验本地和远端ID是否一致再决定最终的同步策略
// validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}
//在本地和远端ID一致前提下进一步判断云端数据是否有更新
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
return SYNC_ACTION_UPDATE_REMOTE;
@ -220,6 +233,7 @@ public class TaskList extends Node {
return mChildren.size();
}
//添加子任务
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
@ -234,6 +248,7 @@ public class TaskList extends Node {
return ret;
}
//指定位置插入子任务
public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index");
@ -241,14 +256,20 @@ public class TaskList extends Node {
}
int pos = mChildren.indexOf(task);
//pos==-1说明task不在mChildren里
if (task != null && pos == -1) {
mChildren.add(index, task);
// update the task list
// update the task list更新任务列表索引
Task preTask = null;
Task afterTask = null;
//如果插入位置不在第一个前任务为index-1的位置
if (index != 0)
preTask = mChildren.get(index - 1);
//如果插入位置不在最后一个后继任务为index+1的位置
if (index != mChildren.size() - 1)
afterTask = mChildren.get(index + 1);
@ -260,9 +281,12 @@ public class TaskList extends Node {
return true;
}
//移除子任务
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
//index!=-1说明task在mChildren里移除操作有效
if (index != -1) {
ret = mChildren.remove(task);
@ -276,11 +300,13 @@ public class TaskList extends Node {
mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1));
}
//当移除最后一个任务时index==mChildren.size(),没有后续任务,无需更新
}
}
return ret;
}
//将指定task从当前位置移到mChildren列表指定的index位置
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
@ -294,11 +320,20 @@ public class TaskList extends Node {
return false;
}
//当前已经在指定位置,不用移动
if (pos == index)
return true;
return (removeChildTask(task) && addChildTask(task, index));
//这里先判断当前不在指定位置,是不是更好?至少更容易一下子看懂
/**
* if (pos!=index)
* return (removeChildTask(task) && addChildTask(task,index));
* else return true;
*/
}
//给定云端gid快速查找子任务
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@ -309,10 +344,12 @@ public class TaskList extends Node {
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");
@ -321,12 +358,24 @@ public class TaskList extends Node {
return mChildren.get(index);
}
public Task getChilTaskByGid(String gid) {
/**gid
*findChildTaskByGid(String gid)
*/
public Task getChildTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
return task;
}
return null;
/*
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
if (t.getGid().equals(gid)) {
return t;
}
}
return null;
*/
}
public ArrayList<Task> getChildTaskList() {

@ -16,6 +16,11 @@
package net.micode.notes.gtask.exception;
/**
* RuntimeException
*
* GTask
*/
public class ActionFailureException extends RuntimeException {
private static final long serialVersionUID = 4425249765923293627L;
@ -23,10 +28,15 @@ public class ActionFailureException extends RuntimeException {
super();
}
/**
* RuntimeException(String) - super
* @param paramString
*/
public ActionFailureException(String paramString) {
super(paramString);
}
//错误信息+异常原因
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}

@ -16,6 +16,11 @@
package net.micode.notes.gtask.exception;
/**
* Exception
*
* GTask
*/
public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L;
@ -27,6 +32,7 @@ public class NetworkFailureException extends Exception {
super(paramString);
}
//自定义错误信息+底层的根异常
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}

@ -28,77 +28,137 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
*AsyncTask
* doInBackground onProgressUpdate onPostExecute
* GTaskGTaskManager
*
* / /
* 广
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
//通知Activity等外层同步已结束是接口
public interface OnCompleteListener {
void onComplete();
}
private Context mContext;
private Context mContext; //上下文用于获取系统服务、资源字符串、启动Activity等
private NotificationManager mNotifiManager;
private NotificationManager mNotifiManager; //用于发送和管理状态栏通知
private GTaskManager mTaskManager;
private GTaskManager mTaskManager; //真正执行同步核心逻辑(登录、拉取、对比、提交等)
private OnCompleteListener mOnCompleteListener;
private OnCompleteListener mOnCompleteListener; //通知外层 Activity/Service 同步结束
//构造方法初始化上下文和回调监听器获取通知管理器和GTaskManager实例
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
//获取GTaskManager单例实例 (负责实际同步逻辑)
mTaskManager = GTaskManager.getInstance();
}
//终止同步的方法
public void cancelSync() {
mTaskManager.cancelSync();
}
//反馈给用户当前进度(这里或许应该是Progress?)
public void publishProgess(String message) {
publishProgress(new String[] {
message
});
}
// private void showNotification(int tickerId, String content) {
// Notification notification = new Notification(R.drawable.notification, mContext
// .getString(tickerId), System.currentTimeMillis());
// notification.defaults = Notification.DEFAULT_LIGHTS;
// notification.flags = Notification.FLAG_AUTO_CANCEL;
// PendingIntent pendingIntent;
// if (tickerId != R.string.ticker_success) {
// pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
// NotesPreferenceActivity.class), 0);
//
// } else {
// pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
// NotesListActivity.class), 0);
// }
// notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
// pendingIntent);
// mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
// }
/**
*
* @param tickerId
* @param content
*/
private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_LIGHTS;
notification.flags = Notification.FLAG_AUTO_CANCEL;
//延迟意图:点击通知时触发的页面跳转
PendingIntent pendingIntent;
//同步不成功,跳转到偏好设置页面
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);
} else {
NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE);
} else { //同步成功,跳转到笔记列表页
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE);
}
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);
//设置通知属性
Notification.Builder builder = new Notification.Builder(mContext)
.setAutoCancel(true)
.setContentTitle(mContext.getString(R.string.app_name)) //通知标题设置
.setContentText(content) //通知内容设置
.setContentIntent(pendingIntent) //点击通知时的跳转意图
.setWhen(System.currentTimeMillis()) //通知时间
.setOngoing(true); //持续通知,不会被滑动清除,同步过程中保持显示
Notification notification=builder.getNotification();
//通过通知管理器显示通知使用固定ID确保后续通知能覆盖之前的
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
/**
* 线
* GTaskManagersync
* @param unused
* @return
*/
@Override
protected Integer doInBackground(Void... unused) {
//发布登录进度:显示"正在登录[账号]"的提示(账号从偏好设置中获取)
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
return mTaskManager.sync(mContext, this);
}
/**
* UI线
* @param progress
*/
@Override
protected void onProgressUpdate(String... progress) {
// 显示"同步中"的通知,内容为后台传来的进度信息
showNotification(R.string.ticker_syncing, progress[0]);
// 若当前上下文是GTaskSyncService同步服务则发送广播告知进度
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()));

@ -60,35 +60,40 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
* Google
* GoogleHTTP/
*/
public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName();
// 获取任务列表的GET请求URL
private static final String GTASK_URL = "https://mail.google.com/tasks/";
// 提交操作的POST请求URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
private static GTaskClient mInstance = null;
private DefaultHttpClient mHttpClient;
private DefaultHttpClient mHttpClient; // HTTP客户端用于发送HTTP请求
private String mGetUrl;
private String mGetUrl; // 实际使用的GET请求URL可能因域名变化
private String mPostUrl;
private String mPostUrl; // 实际使用的POST请求URL可能因域名变化
private long mClientVersion;
private long mClientVersion; // 客户端版本从Google服务获取用于请求验证
private boolean mLoggedin;
private boolean mLoggedin; // 登录状态标识
private long mLastLoginTime;
private int mActionId;
private Account mAccount;
private Account mAccount; // 当前登录的Google账户
private JSONArray mUpdateArray;
private JSONArray mUpdateArray; // 更新队列:批量存储待提交的更新操作(减少网络请求次数)
private GTaskClient() {
mHttpClient = null;
@ -102,6 +107,7 @@ public class GTaskClient {
mUpdateArray = null;
}
//保证全局一个客户端实例
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -109,27 +115,33 @@ public class GTaskClient {
return mInstance;
}
// 登录Google任务处理账户认证和会话建立
public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
// 登录过期检查假设Cookie 5分钟过期过期则需要重新登录
final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
// need to re-login after account switch
// 账户切换检查:若当前账户与设置中的账户不一致,需要重新登录
if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
mLoggedin = false;
}
// 已登录且有效,直接返回成功
if (mLoggedin) {
Log.d(TAG, "already logged in");
return true;
}
// 执行登录流程
mLastLoginTime = System.currentTimeMillis();
// 获取Google账户的认证token
String authToken = loginGoogleAccount(activity, false);
if (authToken == null) {
Log.e(TAG, "login google account failed");
@ -137,21 +149,24 @@ public class GTaskClient {
}
// login with custom domain if necessary
// 处理自定义域名账户非gmail/googlemail
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;
String suffix = mAccount.name.substring(index);
String suffix = mAccount.name.substring(index); // 提取域名后缀
url.append(suffix + "/");
mGetUrl = url.toString() + "ig";
mPostUrl = url.toString() + "r/ig";
// 尝试用自定义URL登录
if (tryToLoginGtask(activity, authToken)) {
mLoggedin = true;
}
}
// try to login with google official url
// 若自定义域名登录失败使用官方URL重试
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
@ -164,16 +179,19 @@ public class GTaskClient {
return true;
}
// 登录Google账户获取认证token用于后续Google任务登录
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
Account[] accounts = accountManager.getAccountsByType("com.google");
AccountManager accountManager = AccountManager.get(activity); // 获取账户管理器
Account[] accounts = accountManager.getAccountsByType("com.google"); // 获取所有Google账户
// 无可用Google账户
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) {
@ -190,12 +208,13 @@ public class GTaskClient {
}
// get the token now
// 获取账户的auth token
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
Bundle authTokenBundle = accountManagerFuture.getResult();
Bundle authTokenBundle = accountManagerFuture.getResult(); // 获取token结果
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
if (invalidateToken) {
if (invalidateToken) { // 若需要失效旧token重新获取
accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false);
}
@ -207,16 +226,19 @@ public class GTaskClient {
return authToken;
}
// 尝试登录Google任务使用获取的auth token建立会话
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the
// token and try again
// 可能是token过期失效旧token并重新获取
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;
@ -225,25 +247,29 @@ public class GTaskClient {
return true;
}
// 登录Google任务核心逻辑使用auth token获取会话Cookie和客户端版本
private boolean loginGtask(String authToken) {
// 设置HTTP连接超时10秒和读取超时15秒
int timeoutConnection = 10000;
int timeoutSocket = 15000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
mHttpClient = new DefaultHttpClient(httpParameters);
mHttpClient = new DefaultHttpClient(httpParameters); // 初始化HTTP客户端
BasicCookieStore localBasicCookieStore = new BasicCookieStore();
mHttpClient.setCookieStore(localBasicCookieStore);
mHttpClient.setCookieStore(localBasicCookieStore); // 设置Cookie存储
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
// 执行登录请求
try {
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
String loginUrl = mGetUrl + "?auth=" + authToken; // 构建带token的登录URL
HttpGet httpGet = new HttpGet(loginUrl);// 创建GET请求
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
response = mHttpClient.execute(httpGet); // 发送请求
// get the cookie now
// 检查是否获取到认证Cookie含"GTL"标识)
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
@ -256,17 +282,18 @@ public class GTaskClient {
}
// get the client version
// 解析响应获取客户端版本(用于后续请求)
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
String jsBegin = "_setup("; // 响应中包含客户端版本的JS前缀
String jsEnd = ")}</script>"; // 后缀
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
String jsString = null;
if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end);
jsString = resString.substring(begin + jsBegin.length(), end);// 提取JS内容
}
JSONObject js = new JSONObject(jsString);
mClientVersion = js.getLong("v");
mClientVersion = js.getLong("v"); // 获取客户端版本
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
@ -280,25 +307,29 @@ public class GTaskClient {
return true;
}
// 获取操作ID每次调用递增用于标识请求的唯一性
private int getActionId() {
return mActionId++;
}
// 创建POST请求设置请求头Content-Type等
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setHeader("AT", "1");
httpPost.setHeader("AT", "1"); // 自定义头,可能用于标识客户端类型
return httpPost;
}
// 读取响应内容处理压缩gzip/deflate并转换为字符串
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue();
contentEncoding = entity.getContentEncoding().getValue(); // 获取编码方式
Log.d(TAG, "encoding: " + contentEncoding);
}
InputStream input = entity.getContent();
// 根据编码方式解压
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
@ -307,6 +338,7 @@ public class GTaskClient {
}
try {
// 读取输入流并转换为字符串
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
@ -323,33 +355,37 @@ public class GTaskClient {
}
}
// 发送POST请求封装JSON请求并处理响应
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
HttpPost httpPost = createHttpPost();
HttpPost httpPost = createHttpPost(); // 创建POST请求
try {
// 构建请求参数将JSON作为"r"参数的值)
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
list.add(new BasicNameValuePair("r", js.toString()));
// 编码为表单格式
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
// execute the post
// 执行请求并获取响应
HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
} catch (ClientProtocolException e) {
} catch (ClientProtocolException e) { // HTTP协议异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (IOException e) {
} catch (IOException e) { // IO异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (JSONException e) {
} catch (JSONException e) { // JSON解析异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("unable to convert response content to jsonobject");
@ -360,21 +396,27 @@ public class GTaskClient {
}
}
// 创建远程任务向Google任务服务发送创建任务请求
public void createTask(Task task) throws NetworkFailureException {
// 先提交之前的更新队列(避免冲突)
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// 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
// 发送请求并获取响应
JSONObject jsResponse = postRequest(jsPost);
// 从响应中获取新创建任务的GID并设置到任务对象
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
@ -386,21 +428,27 @@ public class GTaskClient {
}
}
// 创建远程任务列表向Google任务服务发送创建列表请求
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
// 发送请求并获取响应
JSONObject jsResponse = postRequest(jsPost);
// 从响应中获取新创建列表的GID并设置
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
@ -412,19 +460,22 @@ public class GTaskClient {
}
}
// 提交更新队列:将缓存的更新操作批量发送到服务端
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);
postRequest(jsPost);
mUpdateArray = null;
mUpdateArray = null; // 清空队列
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
@ -433,10 +484,12 @@ public class GTaskClient {
}
}
// 添加更新节点到队列:将节点的更新操作加入缓存队列(批量提交)
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// too many update items may result in an error
// set max to 10 items
// 限制队列最大长度为10避免单次请求过大
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
@ -447,6 +500,7 @@ public class GTaskClient {
}
}
// 移动任务:将任务从原列表移动到新列表(或列表内调整位置)
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
commitUpdate();
@ -456,17 +510,23 @@ public class GTaskClient {
JSONObject action = new JSONObject();
// 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调整位置
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());
}
// 设置源列表和目标父节点
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
// 跨列表移动:设置目标列表
if (preParent != curParent) {
// put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
@ -486,6 +546,7 @@ public class GTaskClient {
}
}
// 删除远程节点:向服务端发送删除请求
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
try {
@ -493,6 +554,7 @@ public class GTaskClient {
JSONArray actionList = new JSONArray();
// action_list
// 标记节点为已删除,并添加删除操作
node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
@ -509,6 +571,7 @@ public class GTaskClient {
}
}
// 获取远程任务列表:从服务端获取所有任务列表
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -522,13 +585,13 @@ public class GTaskClient {
// get the task list
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
String jsBegin = "_setup("; // 响应中任务列表的JS前缀
String jsEnd = ")}</script>"; // 后缀
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
String jsString = null;
if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end);
jsString = resString.substring(begin + jsBegin.length(), end); // 提取JS内容
}
JSONObject js = new JSONObject(jsString);
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
@ -547,6 +610,7 @@ public class GTaskClient {
}
}
// 获取指定任务列表下的任务:从服务端获取某个列表的所有任务
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
try {
@ -559,13 +623,16 @@ public class GTaskClient {
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
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) {
@ -575,10 +642,12 @@ public class GTaskClient {
}
}
// 获取当前同步账户返回登录的Google账户
public Account getSyncAccount() {
return mAccount;
}
// 重置更新队列:清空待提交的更新操作
public void resetUpdateArray() {
mUpdateArray = null;
}

@ -47,21 +47,24 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
/**
* Google
* NoteGoogle
*/
public class GTaskManager {
private static final String TAG = GTaskManager.class.getSimpleName();
public static final int STATE_SUCCESS = 0;
public static final int STATE_SUCCESS = 0; //同步成功状态
public static final int STATE_NETWORK_ERROR = 1;
public static final int STATE_NETWORK_ERROR = 1; //网络错误
public static final int STATE_INTERNAL_ERROR = 2;
public static final int STATE_INTERNAL_ERROR = 2; //内部错误
public static final int STATE_SYNC_IN_PROGRESS = 3;
public static final int STATE_SYNC_IN_PROGRESS = 3; //同步中
public static final int STATE_SYNC_CANCELLED = 4;
public static final int STATE_SYNC_CANCELLED = 4; //取消同步
private static GTaskManager mInstance = null;
private static GTaskManager mInstance = null; //单例实例
private Activity mActivity;
@ -69,24 +72,25 @@ public class GTaskManager {
private ContentResolver mContentResolver;
private boolean mSyncing;
private boolean mSyncing; //同步状态标识:是否正在同步
private boolean mCancelled;
private boolean mCancelled; //是否已取消
private HashMap<String, TaskList> mGTaskListHashMap;
private HashMap<String, TaskList> mGTaskListHashMap; //远程任务列表key任务列表GID
private HashMap<String, Node> mGTaskHashMap;
private HashMap<String, Node> mGTaskHashMap; //所有远程节点(任务/列表key节点GID
private HashMap<String, MetaData> mMetaHashMap;
private HashMap<String, MetaData> mMetaHashMap; //元数据key关联的任务GID
private TaskList mMetaList;
private TaskList mMetaList; //元数据列表
private HashSet<Long> mLocalDeleteIdMap;
private HashSet<Long> mLocalDeleteIdMap; //记录需要从远程删除的本地笔记ID
private HashMap<String, Long> mGidToNid;
private HashMap<String, Long> mGidToNid; //远程GID到本地笔记ID的映射关系
private HashMap<Long, String> mNidToGid;
private HashMap<Long, String> mNidToGid; //本地笔记ID到远程GID的映射关系
//初始化所有集合和状态变量(单例模式防止外部实例化)
private GTaskManager() {
mSyncing = false;
mCancelled = false;
@ -99,6 +103,7 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>();
}
// 单例获取方法:保证全局唯一实例
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@ -106,20 +111,26 @@ public class GTaskManager {
return mInstance;
}
// 设置Activity上下文用于后续登录时获取认证token
public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
mActivity = activity;
}
//协调本地与远程数据同步,返回同步状态
public int sync(Context context, GTaskASyncTask asyncTask) {
// 检查是否正在同步,若正在同步则返回对应状态
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS;
}
// 初始化同步环境
mContext = context;
mContentResolver = mContext.getContentResolver();
mSyncing = true;
mCancelled = false;
//清空所有存储集合(避免上次同步残留数据)
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
@ -128,8 +139,9 @@ public class GTaskManager {
mNidToGid.clear();
try {
// 获取GTaskClient实例
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
client.resetUpdateArray(); //重置客户端的更新队列
// login google task
if (!mCancelled) {
@ -139,55 +151,61 @@ public class GTaskManager {
}
// get the task list from google
// 从远程获取任务列表并初始化(更新同步进度)
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList();
// do content sync work
// do content sync work(更新同步进度)
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent();
} catch (NetworkFailureException e) {
} catch (NetworkFailureException e) { // 捕获网络异常
Log.e(TAG, e.toString());
return STATE_NETWORK_ERROR;
} catch (ActionFailureException e) {
} catch (ActionFailureException e) { // 捕获操作失败异常
Log.e(TAG, e.toString());
return STATE_INTERNAL_ERROR;
} catch (Exception e) {
} catch (Exception e) { // 返回内部错误状态
Log.e(TAG, e.toString());
e.printStackTrace();
return STATE_INTERNAL_ERROR;
} finally {
} finally { // 无论成功失败,清理资源
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
mLocalDeleteIdMap.clear();
mGidToNid.clear();
mNidToGid.clear();
mSyncing = false;
mSyncing = false; // 标记为同步结束
}
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
// 初始化远程任务列表从Google服务器获取任务列表和元数据
private void initGTaskList() throws NetworkFailureException {
// 若同步已取消,直接返回
if (mCancelled)
return;
GTaskClient client = GTaskClient.getInstance();
GTaskClient client = GTaskClient.getInstance(); // 获取网络客户端
try {
// 1. 获取所有远程任务列表JSON数组
JSONArray jsTaskLists = client.getTaskLists();
// init meta list first
// 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);
if (name
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
// 检查是否为元数据列表(名称符合特定前缀+后缀)
if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList();
//用远程JSON初始化元数据列表
mMetaList.setContentByRemoteJSON(object);
// load meta data
// load meta data(元数据本身以任务形式存储)
JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j);
@ -196,6 +214,7 @@ public class GTaskManager {
if (metaData.isWorthSaving()) {
mMetaList.addChildTask(metaData);
if (metaData.getGid() != null) {
// 存储元数据key关联的任务GID
mMetaHashMap.put(metaData.getRelatedGid(), metaData);
}
}
@ -204,26 +223,29 @@ public class GTaskManager {
}
// create meta list if not existed
// 3. 若元数据列表不存在,则创建一个
if (mMetaList == null) {
mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META);
GTaskClient.getInstance().createTaskList(mMetaList);
+ GTaskStringUtils.FOLDER_META); // 设置名称
GTaskClient.getInstance().createTaskList(mMetaList); // 调用客户端创建列表
}
// init task list
// 4. 初始化普通任务列表(排除元数据列表)
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);
// 筛选符合条件的列表:以特定前缀开头,且不是元数据列表
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist);
tasklist.setContentByRemoteJSON(object); // 用远程JSON初始化列表
mGTaskListHashMap.put(gid, tasklist); // 存入任务列表集合
mGTaskHashMap.put(gid, tasklist); // 同时存入全局节点集合
// load tasks
JSONArray jsTasks = client.getTaskList(gid);
@ -231,27 +253,28 @@ public class GTaskManager {
object = (JSONObject) jsTasks.getJSONObject(j);
gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
Task task = new Task();
task.setContentByRemoteJSON(object);
task.setContentByRemoteJSON(object); // 用远程JSON初始化任务
if (task.isWorthSaving()) {
task.setMetaInfo(mMetaHashMap.get(gid));
task.setMetaInfo(mMetaHashMap.get(gid)); // 关联元数据
tasklist.addChildTask(task);
mGTaskHashMap.put(gid, task);
mGTaskHashMap.put(gid, task); // 存入全局节点集合
}
}
}
}
} catch (JSONException e) {
} catch (JSONException e) { // 处理JSON解析异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("initGTaskList: handing JSONObject failed");
}
}
// 同步内容:协调本地与远程的任务/列表数据(核心同步逻辑)
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;
String gid;
Node node;
int syncType; // 同步类型(新增/删除/更新等)
Cursor c = null; // 数据库查询游标
String gid; // 远程GID
Node node; // 远程节点
mLocalDeleteIdMap.clear();
@ -260,20 +283,23 @@ public class GTaskManager {
}
// for local deleted note
// 1. 处理本地已删除的笔记(在回收站中的非系统类型笔记)
try {
// 查询条件:不是系统类型+父ID是回收站
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)
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLDER)
}, null);
if (c != null) {
while (c.moveToNext()) {
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);
gid = c.getString(SqlNote.GTASK_ID_COLUMN); // 获取笔记关联的远程GID
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 {
@ -287,32 +313,43 @@ public class GTaskManager {
}
// sync folder first
// 2. 优先同步文件夹(任务列表)
syncFolder();
// for note existing in database
// 3. 处理本地已存在的普通笔记(非回收站中的笔记类型)
try {
// 查询条件Note类型 + 父ID不是回收站
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)
String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLDER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
gid = c.getString(SqlNote.GTASK_ID_COLUMN); // 获取关联的远程GID
node = mGTaskHashMap.get(gid);
// 远程存在对应节点
if (node != null) {
mGTaskHashMap.remove(gid);
mGTaskHashMap.remove(gid); // 从本地缓存移除
// 记录GID与本地ID的映射关系
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
syncType = node.getSyncAction(c);
} else {
syncType = node.getSyncAction(c); // 计算同步类型(根据本地与远程的修改时间等)
}
// 远程不存在对应节点
else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
// local add 本地GID为空本地新增需要同步到远程
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
// remote delete 本地有GID但远程无远程已删除需要删除本地
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
// 执行同步操作
doContentSync(syncType, node, c);
}
} else {
@ -327,16 +364,20 @@ public class GTaskManager {
}
// go through remaining items
// 4. 处理远程存在但本地不存在的节点(需要同步到本地)
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
node = entry.getValue();
// 执行本地新增
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
// mCancelled can be set by another thread, so we neet to check one by
// one
// clear local delete table
// 5. 清理本地已删除的笔记(若未取消同步)
if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes");
@ -344,6 +385,7 @@ public class GTaskManager {
}
// refresh local sync id
// 6. 提交更新并刷新本地同步ID若未取消
if (!mCancelled) {
GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId();
@ -351,6 +393,7 @@ public class GTaskManager {
}
// 同步文件夹(任务列表):处理本地与远程的文件夹数据
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
@ -362,22 +405,30 @@ public class GTaskManager {
}
// for root folder
// 1. 同步根文件夹
try {
// 查询根文件夹ID固定为Notes.ID_ROOT_FOLDER
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) {
mGTaskHashMap.remove(gid);
// 记录映射关系
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
// 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 {
}
// 远程不存在,需要新增到远程
else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
}
} else {
@ -391,7 +442,9 @@ public class GTaskManager {
}
// for call-note folder
// 2. 同步通话记录文件夹
try {
// 查询通话记录文件夹ID固定为Notes.ID_CALL_RECORD_FOLDER
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
@ -400,12 +453,14 @@ public class GTaskManager {
if (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if
// necessary
// 系统文件夹只在名称不匹配时更新远程
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE))
@ -425,10 +480,12 @@ public class GTaskManager {
}
// for local existing folders
// 3. 同步本地已存在的普通文件夹(非系统类型,非回收站)
try {
// 查询条件:文件夹 + 父ID不是回收站
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)
String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLDER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
@ -442,9 +499,11 @@ public class GTaskManager {
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
// 本地GID为空本地新增同步到远程
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
// 本地有GID但远程无远程已删除删除本地
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
@ -461,21 +520,24 @@ public class GTaskManager {
}
// for remote add folders
// 4. 处理远程存在但本地不存在的文件夹(同步到本地)
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
gid = entry.getKey();
node = entry.getValue();
if (mGTaskHashMap.containsKey(gid)) {
if (mGTaskHashMap.containsKey(gid)) { // 若缓存中存在(未被处理)
mGTaskHashMap.remove(gid);
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); // 本地新增
}
}
// 若未取消,提交所有文件夹相关的远程更新
if (!mCancelled)
GTaskClient.getInstance().commitUpdate();
}
// 执行具体同步操作:根据同步类型处理本地/远程数据
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -483,52 +545,57 @@ public class GTaskManager {
MetaData meta;
switch (syncType) {
case Node.SYNC_ACTION_ADD_LOCAL:
case Node.SYNC_ACTION_ADD_LOCAL: // 远程新增,同步到本地
addLocalNode(node);
break;
case Node.SYNC_ACTION_ADD_REMOTE:
case Node.SYNC_ACTION_ADD_REMOTE: // 本地新增,同步到远程
addRemoteNode(node, c);
break;
case Node.SYNC_ACTION_DEL_LOCAL:
meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN));
case Node.SYNC_ACTION_DEL_LOCAL: // 远程已删除,删除本地
meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN)); // 获取关联元数据
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta);
GTaskClient.getInstance().deleteNode(meta); // 删除远程元数据
}
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); // 记录本地ID待删除
break;
case Node.SYNC_ACTION_DEL_REMOTE:
case Node.SYNC_ACTION_DEL_REMOTE: // 本地已删除,删除远程
meta = mMetaHashMap.get(node.getGid());
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta);
}
GTaskClient.getInstance().deleteNode(node);
break;
case Node.SYNC_ACTION_UPDATE_LOCAL:
case Node.SYNC_ACTION_UPDATE_LOCAL: // 远程更新,同步到本地
updateLocalNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_REMOTE:
case Node.SYNC_ACTION_UPDATE_REMOTE: // 本地更新,同步到远程
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_CONFLICT:
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:
case Node.SYNC_ACTION_NONE: // 无同步操作
break;
case Node.SYNC_ACTION_ERROR:
case Node.SYNC_ACTION_ERROR: // 同步错误
default:
throw new ActionFailureException("unkown sync action type");
}
}
// 本地新增节点:将远程节点同步到本地数据库
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote;
// 节点是任务列表(文件夹)
if (node instanceof TaskList) {
// 特殊文件夹处理:根目录或通话记录文件夹
if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
@ -537,13 +604,14 @@ public class GTaskManager {
sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
} else {
sqlNote = new SqlNote(mContext);
sqlNote.setContent(node.getLocalJSONFromContent());
sqlNote.setContent(node.getLocalJSONFromContent()); // 用远程数据构建本地JSON
sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
}
} else {
} else { // 节点是任务(笔记)
sqlNote = new SqlNote(mContext);
JSONObject js = node.getLocalJSONFromContent();
JSONObject js = node.getLocalJSONFromContent(); // 用远程数据构建本地JSON
try {
// 处理笔记ID冲突若远程数据中的ID已在本地存在移除ID让本地自动生成
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.has(NoteColumns.ID)) {
@ -555,6 +623,7 @@ public class GTaskManager {
}
}
// 处理数据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++) {
@ -576,26 +645,31 @@ public class GTaskManager {
}
sqlNote.setContent(js);
// 获取父文件夹的本地ID通过GID映射
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");
}
sqlNote.setParentId(parentId.longValue());
sqlNote.setParentId(parentId.longValue()); // 设置父目录ID
}
// create the local node
// 提交本地新增
sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false);
// update gid-nid mapping
// 更新映射关系
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta
// 更新远程元数据
updateRemoteMeta(node.getGid(), sqlNote);
}
// 更新本地节点:将远程更新同步到本地
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -604,8 +678,10 @@ public class GTaskManager {
SqlNote sqlNote;
// update the note locally
sqlNote = new SqlNote(mContext, c);
// 用远程数据更新本地内容
sqlNote.setContent(node.getLocalJSONFromContent());
// 确定父目录ID任务的父是列表列表的父是根目录
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
: new Long(Notes.ID_ROOT_FOLDER);
if (parentId == null) {
@ -613,12 +689,14 @@ public class GTaskManager {
throw new ActionFailureException("cannot update local node");
}
sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true);
sqlNote.commit(true); // 提交更新(覆盖本地数据)
// update meta info
// 更新远程元数据
updateRemoteMeta(node.getGid(), sqlNote);
}
// 远程新增节点:将本地节点同步到远程
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -628,26 +706,36 @@ public class GTaskManager {
Node n;
// update remotely
/**
*
*
*/
if (sqlNote.isNoteType()) {
Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent());
task.setContentByLocalJSON(sqlNote.getContent()); // 用本地JSON初始化远程任务
// 获取父文件夹的远程GID通过本地ID映射
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");
}
// 将任务添加到父列表
mGTaskListHashMap.get(parentGid).addChildTask(task);
// 调用客户端创建远程任务
GTaskClient.getInstance().createTask(task);
n = (Node) task;
// add meta
updateRemoteMeta(task.getGid(), sqlNote);
} else {
}
// 本地节点是文件夹(对应远程任务列表)
else {
TaskList tasklist = null;
// we need to skip folder if it has already existed
// 生成文件夹名称(特定前缀+文件夹标识)
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT;
@ -656,12 +744,14 @@ public class GTaskManager {
else
folderName += sqlNote.getSnippet();
// 检查远程是否已存在同名文件夹(避免重复创建)
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
String gid = entry.getKey();
TaskList list = entry.getValue();
// 已存在同名文件夹
if (list.getName().equals(folderName)) {
tasklist = list;
if (mGTaskHashMap.containsKey(gid)) {
@ -672,6 +762,7 @@ public class GTaskManager {
}
// no match we can add now
// 若远程不存在,则创建新文件夹
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
@ -682,35 +773,40 @@ public class GTaskManager {
}
// update local note
// 更新本地节点的远程GID
sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false);
sqlNote.resetLocalModified();
sqlNote.commit(true);
sqlNote.commit(false); // 保存GID
sqlNote.resetLocalModified(); // 重置本地修改标记(避免重复同步)
sqlNote.commit(true); // 提交修改
// gid-id mapping
// 更新映射关系
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
// 更新远程节点:将本地更新同步到远程
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote = new SqlNote(mContext, c);
SqlNote sqlNote = new SqlNote(mContext, c); // 获取本地节点数据
// update remotely
node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node);
GTaskClient.getInstance().addUpdateNode(node); // 将更新加入客户端的更新队列
// update meta
// 更新远程元数据
updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary
if (sqlNote.isNoteType()) {
Task task = (Task) node;
TaskList preParentList = task.getParent();
TaskList preParentList = task.getParent(); // 原父列表
// 获取当前父文件夹的远程GID通过本地ID映射
String curParentGid = mNidToGid.get(sqlNote.getParentId());
if (curParentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
@ -718,6 +814,7 @@ public class GTaskManager {
}
TaskList curParentList = mGTaskListHashMap.get(curParentGid);
// 若父列表变化,执行移动操作
if (preParentList != curParentList) {
preParentList.removeChildTask(task);
curParentList.addChildTask(task);
@ -730,13 +827,15 @@ public class GTaskManager {
sqlNote.commit(true);
}
// 更新远程元数据:同步本地笔记的元数据到远程
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
// 仅处理笔记类型(文件夹无元数据)
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
if (metaData != null) {
if (metaData != null) { // 元数据已存在,更新内容
metaData.setMeta(gid, sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(metaData);
} else {
GTaskClient.getInstance().addUpdateNode(metaData); // 加入更新队列
} else { // 元数据不存在,创建新的
metaData = new MetaData();
metaData.setMeta(gid, sqlNote.getContent());
mMetaList.addChildTask(metaData);
@ -746,12 +845,14 @@ public class GTaskManager {
}
}
// 刷新本地同步ID将远程的最后修改时间同步到本地用于后续同步对比
private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) {
return;
}
// get the latest gtask list
// 重新获取最新的远程节点数据
mGTaskHashMap.clear();
mGTaskListHashMap.clear();
mMetaHashMap.clear();
@ -759,16 +860,18 @@ public class GTaskManager {
Cursor c = null;
try {
// 查询所有非系统类型且不在回收站的节点
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)
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLDER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
while (c.moveToNext()) { // 遍历本地节点
String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
Node node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
// 更新本地节点的同步ID远程最后修改时间
ContentValues values = new ContentValues();
values.put(NoteColumns.SYNC_ID, node.getLastModified());
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
@ -790,6 +893,7 @@ public class GTaskManager {
}
}
// 获取同步账户返回当前登录的Google账户名
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}

@ -23,6 +23,10 @@ import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
/**
* ServiceAndroid
* GTask/广
*/
public class GTaskSyncService extends Service {
public final static String ACTION_STRING_NAME = "sync_action_type";
@ -32,27 +36,34 @@ public class GTaskSyncService extends Service {
public final static int ACTION_INVALID = 2;
//同步服务发送广播的action名称用于标识该广播的唯一标识
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 GTaskASyncTask mSyncTask = null; //当前的同步任务实例
private static String mSyncProgress = "";
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();
sendBroadcast(""); // 发送初始广播(此时任务已创建,通知外界同步开始)
mSyncTask.execute(); //执行
}
}
@ -67,10 +78,27 @@ public class GTaskSyncService extends Service {
mSyncTask = null;
}
/**
*
* /
* @param intent The Intent supplied to {@link android.content.Context#startService},
* as given. This may be null if the service is being restarted after
* its process has gone away, and it had previously returned anything
* except {@link #START_STICKY_COMPATIBILITY}.
* @param flags
* @param startId A unique integer representing this specific request to
* start. Use with {@link #stopSelfResult(int)}.
*
* @return
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 获取意图中携带的额外数据(键值对集合)
Bundle bundle = intent.getExtras();
// 检查bundle是否存在且包含动作类型的键
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
//根据动作类型执行对应操作
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
case ACTION_START_SYNC:
startSync();
@ -83,9 +111,10 @@ public class GTaskSyncService extends Service {
}
return START_STICKY;
}
return super.onStartCommand(intent, flags, startId);
return super.onStartCommand(intent, flags, startId); //没有有效数据,则调用父类方法
}
//系统内存不足时的回调方法
@Override
public void onLowMemory() {
if (mSyncTask != null) {
@ -97,6 +126,7 @@ public class GTaskSyncService extends Service {
return null;
}
//向外界发送包含同步状态(是否正在同步)和进度消息的广播
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -105,23 +135,32 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent);
}
//供外部(如界面)调用,触发同步操作
public static void startSync(Activity activity) {
// 设置GTaskManager的上下文为当前Activity
GTaskManager.getInstance().setActivityContext(activity);
// 创建启动GTaskSyncService的意图指定服务类
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;
}

@ -33,13 +33,24 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
/**
*
*
* ContentProvider
* UI,
*/
public class Note {
private ContentValues mNoteDiffValues;
private NoteData mNoteData;
private ContentValues mNoteDiffValues; //存储Note属性变化修改时间等
private NoteData mNoteData; //封装Note具体数据文本内容、通话记录等
private static final String TAG = "Note";
/**
* Create a new note id for adding a new note to databases
* ID
* /
* @param context
* @param folderId ID
* @return ID
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database
@ -65,6 +76,7 @@ public class Note {
return noteId;
}
//初始化Note数据容器存储属性变化和具体数据
public Note() {
mNoteDiffValues = new ContentValues();
mNoteData = new NoteData();
@ -76,10 +88,12 @@ public class Note {
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
//设置Note的文本数据如笔记内容
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
//设置文本数据的ID用于更新已有文本数据时定位记录
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
@ -96,10 +110,12 @@ public class Note {
mNoteData.setCallData(key, value);
}
//是否有本地修改
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
//同步Note数据到数据库
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -114,6 +130,7 @@ public class Note {
* {@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) {
@ -122,6 +139,7 @@ public class Note {
}
mNoteDiffValues.clear();
//同步具体数据(文本/通话记录若数据有修改且同步失败返回false
if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false;
@ -130,14 +148,18 @@ public class Note {
return true;
}
/**
*
* Note
*/
private class NoteData {
private long mTextDataId;
private long mTextDataId;// 文本数据在数据库中的ID0表示未创建
private ContentValues mTextDataValues;
private ContentValues mTextDataValues; // 存储文本数据的变化
private long mCallDataId;
private long mCallDataId; // 通话记录数据在数据库中的ID0表示未创建
private ContentValues mCallDataValues;
private ContentValues mCallDataValues; // 存储通话数据的变化(如号码更新)
private static final String TAG = "NoteData";
@ -178,24 +200,39 @@ public class Note {
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
* /
* ID=0ID>0
* @param context
* @param noteId ID
* @return Urinull
*/
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety
*/
// 校验笔记ID有效性
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
// 创建批量操作列表(支持同时更新文本和通话数据)
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
//处理文本数据同步
if(mTextDataValues.size() > 0) {
// 关联文本数据到当前笔记
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
//文本数据未创建
if (mTextDataId == 0) {
// 插入数据到ContentProvider获取返回的Uri
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
try {
// 从Uri解析新插入的文本数据ID并存储
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
@ -203,14 +240,17 @@ public class Note {
return null;
}
} else {
// 文本数据已存在:更新记录
// 构建更新操作指定数据ID对应的Uri
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
operationList.add(builder.build());
builder.withValues(mTextDataValues); // 设置要更新的内容
operationList.add(builder.build()); // 添加到批量操作列表
}
mTextDataValues.clear();
}
//处理通话数据同步(逻辑同处理文本数据同步)
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
@ -233,21 +273,25 @@ public class Note {
mCallDataValues.clear();
}
//执行批量更新操作
if (operationList.size() > 0) {
try {
// 应用批量操作到ContentProvider
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) {
// 远程异常如ContentProvider断开连接
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;
return null; // 无批量操作需执行(如仅插入了新数据,未更新)
}
}
}

@ -31,14 +31,17 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
* NoteWorkingNotemNote
*
*/
public class WorkingNote {
// Note for the working note
private Note mNote;
// Note Id
private long mNoteId;
// Note content
private String mContent;
private String mContent; //笔记模式,如普通模式、清单模式
// Note mode
private int mMode;
@ -62,6 +65,7 @@ public class WorkingNote {
private NoteSettingChangedListener mNoteSettingStatusListener;
//指定查询Data表时需要返回的字段
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
@ -72,6 +76,7 @@ public class WorkingNote {
DataColumns.DATA4,
};
//指定查询Note表时需要返回的字段
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
@ -124,14 +129,19 @@ public class WorkingNote {
loadNote();
}
//从数据库加载Note的基本信息(从Note表查询)
private void loadNote() {
//构建查询URI
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null);
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);
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); //文件夹ID
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
@ -143,9 +153,10 @@ public class WorkingNote {
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}
loadNoteData();
loadNoteData(); //继续加载笔记的详细数据从Data表查询
}
//从数据库加载笔记的详细数据从Data表查询
private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
@ -156,11 +167,16 @@ public class WorkingNote {
if (cursor.moveToFirst()) {
do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
//如果是text类型
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)) {
}
//如果是通话记录类型
else if (DataConstants.CALL_NOTE.equals(type)) {
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else {
Log.d(TAG, "Wrong note type with type:" + type);
@ -174,6 +190,7 @@ public class WorkingNote {
}
}
//创建空Note
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
@ -183,19 +200,24 @@ public class WorkingNote {
return note;
}
//加载已有Note
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
//保存Note到数据库同步方法
public synchronized boolean saveNote() {
if (isWorthSaving()) {
// 若笔记不存在于数据库(新笔记)
if (!existInDatabase()) {
// 获取新笔记ID若失败则返回0
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false;
}
}
// 通过Note对象同步数据到数据库
mNote.syncNote(mContext, mNoteId);
/**
@ -217,6 +239,7 @@ public class WorkingNote {
}
private boolean isWorthSaving() {
//若已删除、(新笔记且内容为空)、(已存在且无本地修改),则无需保存
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
return false;
@ -229,24 +252,32 @@ public class WorkingNote {
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();
}
}
// 设置背景色ID
public void setBgColorId(int id) {
if (id != mBgColorId) {
mBgColorId = id;
@ -257,6 +288,7 @@ public class WorkingNote {
}
}
// 设置清单模式(切换普通/清单模式)
public void setCheckListMode(int mode) {
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
@ -267,6 +299,7 @@ public class WorkingNote {
}
}
// 设置小部件类型
public void setWidgetType(int type) {
if (type != mWidgetType) {
mWidgetType = type;
@ -274,6 +307,7 @@ public class WorkingNote {
}
}
//设置小部件ID
public void setWidgetId(int id) {
if (id != mWidgetId) {
mWidgetId = id;
@ -281,6 +315,7 @@ public class WorkingNote {
}
}
//设置笔记内容
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
@ -288,6 +323,7 @@ public class WorkingNote {
}
}
// 将笔记转换为通话笔记(设置通话相关数据)
public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
@ -342,6 +378,7 @@ public class WorkingNote {
return mWidgetType;
}
// 笔记设置变更监听器接口(定义属性变化时的回调方法)
public interface NoteSettingChangedListener {
/**
* Called when the background color of current note has just changed

Loading…
Cancel
Save