Compare commits

...

78 Commits

Author SHA1 Message Date
pg6wepubk 6d1cbd560e Merge pull request '完善' (#63) from mengcheng_branch into develop
2 months ago
mc19 a560e67b48 完善
2 months ago
pg6wepubk 82d5d7ef3c Merge pull request '规范代码质量分析报告' (#61) from mengcheng_branch into develop
2 months ago
mc19 e0ff6c3791 规范代码质量分析报告
2 months ago
pg6wepubk 99b77eb629 Merge pull request '完成代码质量分析报告,修改泛读报告' (#59) from mengcheng_branch into develop
2 months ago
mc19 59fc87327b 完成质量分析报告,修改泛读报告
2 months ago
pg6wepubk 6deaa7fc13 Merge pull request '完成代码质量分析报告' (#57) from mengcheng_branch into develop
2 months ago
mc19 2fdc35164e 完成代码质量分析报告
2 months ago
pg6wepubk 16692d629a Merge pull request '撰写质量分析报告' (#56) from mengcheng_branch into develop
2 months ago
mc19 6a0a657817 撰写质量分析报告文档
2 months ago
mc19 36a9259bc9 增加分析文件
2 months ago
mc19 6bf950ffe7 补充文档注释部分
2 months ago
pg6wepubk 75559147eb Merge pull request '增加前三个包注释' (#54) from mengcheng_branch into develop
2 months ago
mc19 2e41cabb83 删除原文档
2 months ago
mc19 552d11bbbb Merge branch 'develop' of https://bdgit.educoder.net/pg6wepubk/xiaomi_notes_reading into mengcheng_branch
2 months ago
pkx2w7qjn 51a5d26bca Merge pull request '完善文档标注部分' (#52) from zhaochang_branch into develop
2 months ago
pkx2w7qjn b2251059cf Merge pull request '添加tool包,ui包,widget包注释' (#50) from zhaochang_branch into develop
2 months ago
赵昌 1e13ff446b 重置代码
2 months ago
赵昌 b55b47c8dc 添加tool包,UI包,widget包注释
2 months ago
mc19 bc3beabee4 完善报告代码行数
2 months ago
mc19 cc040dfac9 增加data,gtask,model包注释
2 months ago
mc19 be3561be23 修改格式
3 months ago
mc19 759789a3a3 修改文档名
3 months ago
mc19 b44085160c 删除格式错误文档
3 months ago
mc19 b39b458497 修改一些格式问题
3 months ago
mc19 bea04f9471 修改格式
3 months ago
mc19 e1060a9d80 补充最新模板
3 months ago
赵昌 f0253694e9 Merge branch 'master' of https://bdgit.educoder.net/pkx2w7qjn/xiaomi_notes_reading
3 months ago
pkx2w7qjn c4e56fcb20 Merge pull request '修改部分内容' (#38) from develop into master
3 months ago
赵昌 d99b0e6b4e 修改小米便签泛读、标注和维护报告文档
3 months ago
pkx2w7qjn 93618c9d45 Merge pull request '添加小米便签泛读、标注和维护报告文档' (#36) from develop into master
3 months ago
pkx2w7qjn f27d797a50 Merge pull request '添加小米便签泛读、标注和维护报告文档' (#35) from zhaochang_branch into develop
3 months ago
赵昌 201d9abcfb 修改部分小米便签泛读,标注和维护报告文档内容
3 months ago
赵昌 bc9d3780ad Merge branch 'master' of https://bdgit.educoder.net/pkx2w7qjn/xiaomi_notes_reading
3 months ago
赵昌 fdb3c2ae18 修改ui包类间关系图
3 months ago
mc19 587b774777 报告最终版
3 months ago
mc19 9b1d354da3 第三周修改报告
3 months ago
mc19 0b354512d1 修改格式
3 months ago
mc19 e49cc3e4f1 修改图片
3 months ago
pg6wepubk b5f6698ea0 Merge pull request '完成第三部分,同时修改完善其他部分' (#20) from develop into master
3 months ago
pg6wepubk 8ed90ccbf8 Merge pull request '完成第三部分,同时修改完善其他部分' (#19) from mengcheng_branch into develop
3 months ago
mc19 62599eb986 Merge branch 'master' of https://bdgit.educoder.net/pg6wepubk/xiaomi_notes_reading
3 months ago
mc19 7ec2d9ca86 完善泛读报告
3 months ago
pg6wepubk 79cd82e231 Merge pull request '完善泛读报告' (#18) from mengcheng_branch into master
3 months ago
mc19 d1d1d1b239 完善泛读报告
3 months ago
pkx2w7qjn f8f0baaa2d Merge pull request '完成报告第四部分' (#17) from develop into master
3 months ago
pkx2w7qjn 997154d3ce Merge pull request '完成报告第四部分' (#16) from zhaochang_branch into develop
3 months ago
pkx2w7qjn adcb1950ce Merge pull request '修改部分内容' (#15) from develop into master
3 months ago
pkx2w7qjn 24e0a5b336 Merge pull request '修改部分内容' (#14) from zhaochang_branch into develop
3 months ago
pkx2w7qjn a8502fb77e Merge pull request '完成小米便签阅读报告第二部分' (#13) from develop into master
3 months ago
pkx2w7qjn d290615d0b Merge pull request '完成小米便签阅读报告第二部分' (#12) from zhaochang_branch into develop
3 months ago
赵昌 75ed1223e1 Merge branch 'develop' of https://bdgit.educoder.net/pkx2w7qjn/xiaomi_notes_reading into develop
3 months ago
赵昌 fb984eb6de 完成小米便签阅读报告第二部分
3 months ago
赵昌 8ad11877e6 完成小米便签阅读第二部分
3 months ago
赵昌 cde409e3bd Merge branch 'master' of https://bdgit.educoder.net/pkx2w7qjn/xiaomi_notes_reading
3 months ago
赵昌 a4523b267c 修改第一周报告
3 months ago
pkx2w7qjn f8e6b434c6 Merge pull request '修改分支文件' (#6) from mengcheng_branch into develop
3 months ago
赵昌 186d6c4474 修改第一周报告
3 months ago
mc19 5dffb53534 Merge branch 'develop' of https://bdgit.educoder.net/pg6wepubk/xiaomi_notes_reading into develop
3 months ago
mc19 4cb65cc568 删除多余文件,修改文件名
3 months ago
mc19 e0f404109b 删除文件,修改文件名
3 months ago
mc19 df52bb9e51 删除多余文件
3 months ago
pg6wepubk 8b0a5aca63 Merge pull request '修改分支doc文件夹内容' (#5) from mengcheng_branch into master
3 months ago
mc19 a336c7e0fa Merge branch 'mengcheng_branch' of https://bdgit.educoder.net/pg6wepubk/xiaomi_notes_reading into mengcheng_branch
3 months ago
mc19 8122ebf446 修改报告
3 months ago
pkx2w7qjn 37ae398e69 Merge pull request '提交第一周泛读报告' (#4) from develop into master
3 months ago
pkx2w7qjn e27bfa76b2 Merge pull request '提交第一周泛读报告' (#3) from mengcheng_branch into develop
3 months ago
pkx2w7qjn 1b2175faf7 Merge pull request '提交第一周泛读报告' (#2) from develop into master
3 months ago
pkx2w7qjn 6720f27cce Merge pull request '提交第一周泛读报告' (#1) from zhaochang_branch into develop
3 months ago
mc19 1c464945db 修改报告
3 months ago
mc19 b1f7eb82ac 修改报告
3 months ago
mc19 f2ae1799b2 Merge branch 'mengcheng_branch' of https://bdgit.educoder.net/pg6wepubk/xiaomi_notes_reading into mengcheng_branch
3 months ago
mc19 33c39a526e 新增泛读报告
3 months ago
mc19 939ed40d4f 新增字母
3 months ago
mc19 48a09df8cc Merge branch 'mengcheng_branch' of https://bdgit.educoder.net/pg6wepubk/xiaomi_notes_reading into mengcheng_branch
3 months ago
mc19 e2fc1603e1 新增doc/hello.txt文件
3 months ago
mc19 69b513a2f4 空行删除
3 months ago
mc19 18886ebfde 新增数字
3 months ago

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

@ -14,43 +14,73 @@
* limitations under the License. * limitations under the License.
*/ */
/*
*Notes.java
*
* 2025-12-06
* 37
*/
package net.micode.notes.data; package net.micode.notes.data;
import android.net.Uri; import android.net.Uri;
/**
*Notes便
* <P>URI便/Intent</P>
* <b>static final</b>
* @author
* @since []
*/
public class Notes { public class Notes {
public static final String AUTHORITY = "micode_notes";
public static final String TAG = "Notes"; //一、ContentProvider权威域名
public static final int TYPE_NOTE = 0; public static final String AUTHORITY = "micode_notes"; //拼接URI的前缀
public static final int TYPE_FOLDER = 1; public static final String TAG = "Notes"; //日志显示Notes
public static final int TYPE_SYSTEM = 2;
//二、便签/文件夹/系统文件夹 类型常量
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 * Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder * {@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 * {@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_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0; public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1; public static final int TYPE_WIDGET_4X = 1;
/**
*便MIME
* Android ContentResolver // URI MIME
*/
public static class DataConstants { public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; //文本便签MIME类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; //通话备忘MIME类型
} }
//七、基础URI
/** /**
* Uri to query all notes and folders * Uri to query all notes and folders
*/ */
@ -58,12 +88,18 @@ public class Notes {
/** /**
* Uri to query data * Uri to query data
*
*/ */
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
//八、数据库列名接口 —— Note 表
/**
* NoteColumns便/
* 便ID,PARENT_ID,
*/
public interface NoteColumns { public interface NoteColumns {
/** /**
* The unique ID for a row * The unique ID for a ro
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id";
@ -167,12 +203,18 @@ public class Notes {
public static final String VERSION = "version"; public static final String VERSION = "version";
} }
//九、数据库列名接口 —— Data 表
/**
* DataColumns
*/
public interface DataColumns { public interface DataColumns {
/** /**
* The unique ID for a row * The unique ID for a row
* <P> Type: INTEGER (long) </P> * <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. * 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 * integer data type
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String DATA1 = "data1"; 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 * integer data type
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String DATA2 = "data2"; 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 * TEXT data type
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String DATA3 = "data3"; 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 * TEXT data type
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String DATA4 = "data4"; 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 * TEXT data type
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String DATA5 = "data5"; public static final String DATA5 = "data5";
} }
//十、文本便签实体常量类
//文本便签TextNote类实现DataColumns接口中声明的方法
public static final class TextNote implements DataColumns { public static final class TextNote implements DataColumns {
/** /**
* Mode to indicate the text in check list mode or not * Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P> * <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 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 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 * Call date for this record
* <P> Type: INTEGER (long) </P> * <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 * Phone number for this record

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

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

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

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

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

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

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

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

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

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

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

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

@ -23,6 +23,10 @@ import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
/**
* ServiceAndroid
* GTask/广
*/
public class GTaskSyncService extends Service { public class GTaskSyncService extends Service {
public final static String ACTION_STRING_NAME = "sync_action_type"; 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; 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_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_IS_SYNCING = "isSyncing";
// 广播中用于标识"同步进度消息"的键
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; 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() { private void startSync() {
//当前没有同步任务执行,创建新任务
if (mSyncTask == null) { if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
//任务完成时的回调方法:清理任务实例,发送空进度广播,停止当前服务
public void onComplete() { public void onComplete() {
mSyncTask = null; mSyncTask = null;
sendBroadcast(""); sendBroadcast("");
stopSelf(); stopSelf();
} }
}); });
sendBroadcast(""); sendBroadcast(""); // 发送初始广播(此时任务已创建,通知外界同步开始)
mSyncTask.execute(); mSyncTask.execute(); //执行
} }
} }
@ -67,10 +78,27 @@ public class GTaskSyncService extends Service {
mSyncTask = null; 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 @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
// 获取意图中携带的额外数据(键值对集合)
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
// 检查bundle是否存在且包含动作类型的键
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
//根据动作类型执行对应操作
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
case ACTION_START_SYNC: case ACTION_START_SYNC:
startSync(); startSync();
@ -83,9 +111,10 @@ public class GTaskSyncService extends Service {
} }
return START_STICKY; return START_STICKY;
} }
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId); //没有有效数据,则调用父类方法
} }
//系统内存不足时的回调方法
@Override @Override
public void onLowMemory() { public void onLowMemory() {
if (mSyncTask != null) { if (mSyncTask != null) {
@ -97,6 +126,7 @@ public class GTaskSyncService extends Service {
return null; return null;
} }
//向外界发送包含同步状态(是否正在同步)和进度消息的广播
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
mSyncProgress = msg; mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -105,23 +135,32 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent); sendBroadcast(intent);
} }
//供外部(如界面)调用,触发同步操作
public static void startSync(Activity activity) { public static void startSync(Activity activity) {
// 设置GTaskManager的上下文为当前Activity
GTaskManager.getInstance().setActivityContext(activity); GTaskManager.getInstance().setActivityContext(activity);
// 创建启动GTaskSyncService的意图指定服务类
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class);
// 在意图中添加"启动同步"的动作类型
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
activity.startService(intent); activity.startService(intent);
} }
//供外部(如界面)调用,取消正在进行的同步操作
public static void cancelSync(Context context) { public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class); Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent); context.startService(intent);
} }
//断是否正在同步
public static boolean isSyncing() { public static boolean isSyncing() {
return mSyncTask != null; return mSyncTask != null;
} }
//获取当前同步进度字符串
public static String getProgressString() { public static String getProgressString() {
return mSyncProgress; return mSyncProgress;
} }

@ -33,13 +33,24 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList; import java.util.ArrayList;
/**
*
*
* ContentProvider
* UI,
*/
public class Note { public class Note {
private ContentValues mNoteDiffValues; private ContentValues mNoteDiffValues; //存储Note属性变化修改时间等
private NoteData mNoteData; private NoteData mNoteData; //封装Note具体数据文本内容、通话记录等
private static final String TAG = "Note"; private static final String TAG = "Note";
/** /**
* Create a new note id for adding a new note to databases * 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) { public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database // Create a new note in the database
@ -65,6 +76,7 @@ public class Note {
return noteId; return noteId;
} }
//初始化Note数据容器存储属性变化和具体数据
public Note() { public Note() {
mNoteDiffValues = new ContentValues(); mNoteDiffValues = new ContentValues();
mNoteData = new NoteData(); mNoteData = new NoteData();
@ -76,10 +88,12 @@ public class Note {
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
//设置Note的文本数据如笔记内容
public void setTextData(String key, String value) { public void setTextData(String key, String value) {
mNoteData.setTextData(key, value); mNoteData.setTextData(key, value);
} }
//设置文本数据的ID用于更新已有文本数据时定位记录
public void setTextDataId(long id) { public void setTextDataId(long id) {
mNoteData.setTextDataId(id); mNoteData.setTextDataId(id);
} }
@ -96,10 +110,12 @@ public class Note {
mNoteData.setCallData(key, value); mNoteData.setCallData(key, value);
} }
//是否有本地修改
public boolean isLocalModified() { public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
} }
//同步Note数据到数据库
public boolean syncNote(Context context, long noteId) { public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); 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 * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info * note data info
*/ */
//更新笔记属性(如修改时间、本地修改标记等)
if (context.getContentResolver().update( if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) { null) == 0) {
@ -122,6 +139,7 @@ public class Note {
} }
mNoteDiffValues.clear(); mNoteDiffValues.clear();
//同步具体数据(文本/通话记录若数据有修改且同步失败返回false
if (mNoteData.isLocalModified() if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) { && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false; return false;
@ -130,14 +148,18 @@ public class Note {
return true; return true;
} }
/**
*
* Note
*/
private class NoteData { 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"; private static final String TAG = "NoteData";
@ -178,24 +200,39 @@ public class Note {
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
/**
* /
* ID=0ID>0
* @param context
* @param noteId ID
* @return Urinull
*/
Uri pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) {
/** /**
* Check for safety * Check for safety
*/ */
// 校验笔记ID有效性
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
} }
// 创建批量操作列表(支持同时更新文本和通话数据)
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null; ContentProviderOperation.Builder builder = null;
//处理文本数据同步
if(mTextDataValues.size() > 0) { if(mTextDataValues.size() > 0) {
// 关联文本数据到当前笔记
mTextDataValues.put(DataColumns.NOTE_ID, noteId); mTextDataValues.put(DataColumns.NOTE_ID, noteId);
//文本数据未创建
if (mTextDataId == 0) { if (mTextDataId == 0) {
// 插入数据到ContentProvider获取返回的Uri
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues); mTextDataValues);
try { try {
// 从Uri解析新插入的文本数据ID并存储
setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId); Log.e(TAG, "Insert new text data fail with noteId" + noteId);
@ -203,14 +240,17 @@ public class Note {
return null; return null;
} }
} else { } else {
// 文本数据已存在:更新记录
// 构建更新操作指定数据ID对应的Uri
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId)); Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues); builder.withValues(mTextDataValues); // 设置要更新的内容
operationList.add(builder.build()); operationList.add(builder.build()); // 添加到批量操作列表
} }
mTextDataValues.clear(); mTextDataValues.clear();
} }
//处理通话数据同步(逻辑同处理文本数据同步)
if(mCallDataValues.size() > 0) { if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId); mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) { if (mCallDataId == 0) {
@ -233,21 +273,25 @@ public class Note {
mCallDataValues.clear(); mCallDataValues.clear();
} }
//执行批量更新操作
if (operationList.size() > 0) { if (operationList.size() > 0) {
try { try {
// 应用批量操作到ContentProvider
ContentProviderResult[] results = context.getContentResolver().applyBatch( ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList); Notes.AUTHORITY, operationList);
return (results == null || results.length == 0 || results[0] == null) ? null return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) { } catch (RemoteException e) {
// 远程异常如ContentProvider断开连接
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null; return null;
} catch (OperationApplicationException e) { } catch (OperationApplicationException e) {
// 操作执行异常(如数据约束冲突)
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null; 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.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources; import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
* NoteWorkingNotemNote
*
*/
public class WorkingNote { public class WorkingNote {
// Note for the working note // Note for the working note
private Note mNote; private Note mNote;
// Note Id // Note Id
private long mNoteId; private long mNoteId;
// Note content // Note content
private String mContent; private String mContent; //笔记模式,如普通模式、清单模式
// Note mode // Note mode
private int mMode; private int mMode;
@ -62,6 +65,7 @@ public class WorkingNote {
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener;
//指定查询Data表时需要返回的字段
public static final String[] DATA_PROJECTION = new String[] { public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
@ -72,6 +76,7 @@ public class WorkingNote {
DataColumns.DATA4, DataColumns.DATA4,
}; };
//指定查询Note表时需要返回的字段
public static final String[] NOTE_PROJECTION = new String[] { public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
@ -124,14 +129,19 @@ public class WorkingNote {
loadNote(); loadNote();
} }
//从数据库加载Note的基本信息(从Note表查询)
private void loadNote() { private void loadNote() {
//构建查询URI
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId),
null, null); NOTE_PROJECTION,
null,
null,
null);
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { 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); mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN); mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
@ -143,9 +153,10 @@ public class WorkingNote {
Log.e(TAG, "No note with id:" + mNoteId); Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId); throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
} }
loadNoteData(); loadNoteData(); //继续加载笔记的详细数据从Data表查询
} }
//从数据库加载笔记的详细数据从Data表查询
private void loadNoteData() { private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] { DataColumns.NOTE_ID + "=?", new String[] {
@ -156,11 +167,16 @@ public class WorkingNote {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
do { do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN); String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
//如果是text类型
if (DataConstants.NOTE.equals(type)) { if (DataConstants.NOTE.equals(type)) {
mContent = cursor.getString(DATA_CONTENT_COLUMN); mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN); mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_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)); mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else { } else {
Log.d(TAG, "Wrong note type with type:" + type); 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, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) { int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId);
@ -183,19 +200,24 @@ public class WorkingNote {
return note; return note;
} }
//加载已有Note
public static WorkingNote load(Context context, long id) { public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
//保存Note到数据库同步方法
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
if (isWorthSaving()) { if (isWorthSaving()) {
// 若笔记不存在于数据库(新笔记)
if (!existInDatabase()) { if (!existInDatabase()) {
// 获取新笔记ID若失败则返回0
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId); Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false; return false;
} }
} }
// 通过Note对象同步数据到数据库
mNote.syncNote(mContext, mNoteId); mNote.syncNote(mContext, mNoteId);
/** /**
@ -217,6 +239,7 @@ public class WorkingNote {
} }
private boolean isWorthSaving() { private boolean isWorthSaving() {
//若已删除、(新笔记且内容为空)、(已存在且无本地修改),则无需保存
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
return false; return false;
@ -229,24 +252,32 @@ public class WorkingNote {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} }
//设置提醒时间
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
//有时间变化才更新
if (date != mAlertDate) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
} }
// 若监听器不为空,触发提醒变更回调
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onClockAlertChanged(date, set); mNoteSettingStatusListener.onClockAlertChanged(date, set);
} }
} }
// 标记笔记是否被删除
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
mIsDeleted = mark; mIsDeleted = mark;
// 若存在关联的小部件且监听器不为空,通知小部件变更
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();
} }
} }
// 设置背景色ID
public void setBgColorId(int id) { public void setBgColorId(int id) {
if (id != mBgColorId) { if (id != mBgColorId) {
mBgColorId = id; mBgColorId = id;
@ -257,6 +288,7 @@ public class WorkingNote {
} }
} }
// 设置清单模式(切换普通/清单模式)
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
if (mMode != mode) { if (mMode != mode) {
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
@ -267,6 +299,7 @@ public class WorkingNote {
} }
} }
// 设置小部件类型
public void setWidgetType(int type) { public void setWidgetType(int type) {
if (type != mWidgetType) { if (type != mWidgetType) {
mWidgetType = type; mWidgetType = type;
@ -274,6 +307,7 @@ public class WorkingNote {
} }
} }
//设置小部件ID
public void setWidgetId(int id) { public void setWidgetId(int id) {
if (id != mWidgetId) { if (id != mWidgetId) {
mWidgetId = id; mWidgetId = id;
@ -281,6 +315,7 @@ public class WorkingNote {
} }
} }
//设置笔记内容
public void setWorkingText(String text) { public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) { if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
@ -288,6 +323,7 @@ public class WorkingNote {
} }
} }
// 将笔记转换为通话笔记(设置通话相关数据)
public void convertToCallNote(String phoneNumber, long callDate) { public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
@ -342,6 +378,7 @@ public class WorkingNote {
return mWidgetType; return mWidgetType;
} }
// 笔记设置变更监听器接口(定义属性变化时的回调方法)
public interface NoteSettingChangedListener { public interface NoteSettingChangedListener {
/** /**
* Called when the background color of current note has just changed * Called when the background color of current note has just changed

Loading…
Cancel
Save