Compare commits

..

24 Commits

Author SHA1 Message Date
p6vxzahlf 17c2d96f83 Merge pull request '修改 质量分析报告' (#19) from develop into master
5 days ago
white-yj8109 dc3ca0cff5 修改 质量分析报告
5 days ago
p6vxzahlf a250c531dc Merge pull request '新增质量分析报告' (#18) from develop into master
1 week ago
white-yj8109 4fb0bd0109 新增质量分析报告
1 week ago
p6vxzahlf cda683eed4 Merge pull request '完成代码标注工作' (#17) from develop into master
3 weeks ago
white-yj8109 dbb6348ac2 恢复 初始代码
3 weeks ago
white-yj8109 e71651d844 新增 代码标注报告
3 weeks ago
white-yj8109 30382e6e71 Merge branch 'master' of https://bdgit.educoder.net/p6vxzahlf/Notes
3 weeks ago
white-yj8109 b0924ee626 删除版本1
3 weeks ago
p6vxzahlf 7bf3c8be05 Merge pull request '新增 data gtask model包的代码标注' (#15) from wangyijia_branch into develop
3 weeks ago
white-yj8109 2a37004d61 新增 data gtask model代码标注
3 weeks ago
white-yj8109 f00ba94078 Merge branch 'develop' of https://bdgit.educoder.net/p6vxzahlf/Notes into develop
3 weeks ago
white-yj8109 55c1c81e2e 新增代码标注文档
3 weeks ago
white-yj8109 7c613852bd 新增 代码标注报告
3 weeks ago
ple74bfj6 bd7ecfd782 ool,ui,widget类里的代码
3 weeks ago
white-yj8109 01fab0004b 删除报告
3 weeks ago
p6vxzahlf fcda44d97d Delete 'doc/小米便签的泛读报告.docx'
3 weeks ago
p6vxzahlf 385ca96eda Merge pull request '泛读报告-最终版' (#11) from develop into master
1 month ago
white-yj8109 03df6e9c81 修改为新模板
1 month ago
p6vxzahlf 855c5dd69a Merge pull request '调整格式' (#10) from develop into master
1 month ago
white-yj8109 d95946757c 调整格式
1 month ago
p6vxzahlf 8afd22ab37 Merge pull request '修改格式' (#9) from develop into master
2 months ago
white-yj8109 fe418550e8 修改格式
2 months ago
p6vxzahlf d81fb13b32 Merge pull request '新增 小米便签的泛读报告完整版' (#8) from develop into master
2 months ago

@ -25,47 +25,74 @@ import android.util.Log;
import java.util.HashMap;
/**
*
* @Package: net.micode.notes.data
* @ClassName: Contact
* @Description:
*/
public class Contact {
//哈希图型变量sContactCache用于存储联系人姓名和电话号码的映射关系
private static HashMap<String, String> sContactCache;
private static final String TAG = "Contact";
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/**
* sql:
* phone_lookupraw_contact_iddataraw_contact_id
*/
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER + ",?) AND " + Data.MIMETYPE
+ "='" + Phone.CONTENT_ITEM_TYPE + "'" + " AND " + Data.RAW_CONTACT_ID + " IN " + "(SELECT raw_contact_id "
+ " FROM phone_lookup" + " WHERE min_match = '+')";
/**
* @method getContact
* @description
* @param context
* @param phoneNumber
* @return string
*/
public static String getContact(Context context, String phoneNumber) {
if(sContactCache == null) {
//初始化 sContactCache
if (sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
if(sContactCache.containsKey(phoneNumber)) {
//通过电话号码查找sContactCache如果命中直接返回对应的姓名
if (sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
null);
//selection:将CALLER_ID_SELECTION中的“+”替换成实际电话号码的最小匹配字符串
String selection = CALLER_ID_SELECTION.replace("+", PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
/**
* Data.CONTENT_URI
* Phone.DISPLAY_NAME
* sqlselection
* phoneNumber
*
*/
Cursor cursor = context.getContentResolver().query(Data.CONTENT_URI, new String[]{Phone.DISPLAY_NAME},
selection, new String[]{phoneNumber}, null);
//如果光标不为空且移到第一行,即已在数据库中查询到
if (cursor != null && cursor.moveToFirst()) {
//获取联系人姓名 并将电话号码和联系人姓名的映射关系存到sContactCache中 返回姓名
try {
String name = cursor.getString(0);
sContactCache.put(phoneNumber, name);
return name;
} catch (IndexOutOfBoundsException e) {
}
//异常处理
catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
cursor.close();
}
} else {
}
//如果未在数据库中查询到,则记录错误日志
else {
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}

@ -17,24 +17,40 @@
package net.micode.notes.data;
import android.net.Uri;
/**
*
* @Package: net.micode.notes.data
* @ClassName: Notes
* @Description:
*/
public class Notes {
public static final String AUTHORITY = "micode_notes";
//定义此应用ContentProvider的唯一标识
public static final String AUTHORITY = "net.micode.notes.provider";
public static final String TAG = "Notes";
/**
*{@link Notes#TYPE_NOTE } 便
*{@link Notes#TYPE_FOLDER }
*{@link Notes#TYPE_SYSTEM }
*/
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder 便
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
* {@link Notes#ID_TRASH_FOLER}
*/
public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
//定义Intent Extra 的常量,用于在不同组件之间安全地传递数据
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";
@ -46,6 +62,7 @@ public class Notes {
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
// 将不同数据类型对应到其MIMEitem类型字符串
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
@ -61,6 +78,7 @@ public class Notes {
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
//Note表数据库列名常量接口
public interface NoteColumns {
/**
* The unique ID for a row
@ -95,6 +113,8 @@ public class Notes {
/**
* Folder's name or text content of note
*
* 便便
* <P> Type: TEXT </P>
*/
public static final String SNIPPET = "snippet";
@ -167,6 +187,7 @@ public class Notes {
public static final String VERSION = "version";
}
//Data表数据库列名常量接口
public interface DataColumns {
/**
* The unique ID for a row
@ -241,10 +262,12 @@ public class Notes {
public static final String DATA5 = "data5";
}
//DataColumns接口的实现方式1文本便签的数据模型
public static final class TextNote implements DataColumns {
/**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
* data1
*/
public static final String MODE = DATA1;
@ -257,16 +280,19 @@ public class Notes {
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
//DataColumns接口的实现方式2通话便签的数据模型
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
* data1
*/
public static final String CALL_DATE = DATA1;
/**
* Phone number for this record
* <P> Type: TEXT </P>
* data3
*/
public static final String PHONE_NUMBER = DATA3;

@ -26,7 +26,12 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
/**
*
* @Package: net.micode.notes.data
* @ClassName: NotesDatabaseHelper
* @Description:
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "note.db";
@ -42,6 +47,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static NotesDatabaseHelper mInstance;
/**notesql
* note便
*/
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
@ -63,6 +71,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")";
/**datasql
* data
*/
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
@ -78,12 +89,17 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";
//为data表的note_id列创建索引的sql语句
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/**
* Increase folder's note count when move note to the folder
* increase_folder_count_on_update
*
* notePARENT_ID
* note
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+
@ -96,6 +112,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* Decrease folder's note count when move note from folder
* decrease_folder_count_on_update
*
* notePARENT_ID
* note
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " +
@ -109,6 +129,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* Increase folder's note count when insert new note to the folder
* increase_folder_count_on_insert
*
* note
* note
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " +
@ -121,6 +145,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* Decrease folder's note count when delete note from the folder
* decrease_folder_count_on_delete
*
* note
* note
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +
@ -134,6 +162,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* Update note's content when insert data with type {@link DataConstants#NOTE}
* update_note_content_on_insert
*
* data便
* note便
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
@ -147,6 +179,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* Update note's content when data with {@link DataConstants#NOTE} type has changed
* update_note_content_on_update
*
* data便
* note便
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
@ -160,6 +196,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted
* update_note_content_on_delete
*
* data
* note便
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
@ -173,6 +213,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* Delete datas belong to note which has been deleted
* delete_data_on_delete
*
* note
* data便
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
@ -184,6 +228,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* Delete notes belong to folder which has been deleted
* folder_delete_notes_on_delete
*
* note
* note便
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
@ -195,6 +243,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* Move notes belong to folder which has been moved to trash folder
* folder_move_notes_on_trash
*
* notePARENT_IDid
* note便idid
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " +
@ -206,10 +258,22 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
* @method NotesDatabaseHelper
* @description
* @param context
* context
* DB_NAME
*
* DB_VERSION
*/
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
//创建note表
public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db);
@ -217,7 +281,9 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "note table has been created");
}
//创建note表触发器
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
//将已有的触发器删掉
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -235,11 +301,13 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
//创建系统文件夹
private void createSystemFolder(SQLiteDatabase db) {
//ContentValues是一个键值对集合用于存储一行数据。名是string值为基本类型。
ContentValues values = new ContentValues();
/**
* call record foler for call notes
*
*/
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
@ -247,6 +315,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* root folder which is default folder
*
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
@ -255,6 +324,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* temporary folder which is used for moving note
* 便
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
@ -263,6 +333,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* create trash folder
*
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
@ -270,6 +341,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
}
//创建data表
public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db);
@ -277,6 +349,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "data table has been created");
}
//创建data表触发器
private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
@ -287,6 +360,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
//创建NotesDatabaseHelper的单例
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
@ -294,12 +368,20 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance;
}
//重写onCreate方法创建数据库
@Override
public void onCreate(SQLiteDatabase db) {
createNoteTable(db);
createDataTable(db);
}
/**
* @method onUpgrade
* @description
* @param db
* @param oldVersion
* @param newVersion
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
@ -307,7 +389,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
if (oldVersion == 1) {
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
skipV2 = true; // this upgrade including the upgrade from v2 to v3 v1->v2升级已包含v2->v3升级
oldVersion++;
}
@ -333,6 +415,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
}
}
//更新到版本2重建note表和data表
private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
@ -340,6 +423,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
createDataTable(db);
}
//更新到版本3引入Gtask功能添加垃圾站功能
private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
@ -355,6 +439,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
}
//更新到版本4增加版本字段
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");

@ -34,74 +34,105 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
*
* @Package: net.micode.notes.data
* @ClassName: NotesProvider
* @Description: 便
*/
public class NotesProvider extends ContentProvider {
//uri匹配器
private static final UriMatcher mMatcher;
private NotesDatabaseHelper mHelper;
private static final String TAG = "NotesProvider";
//定义便签、数据相关的uri常量
private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4;
//定义搜索相关的uri常量
private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;
//初始化并配置 UriMatcher 实例。将 URI 模式映射到整数值。
static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);//# 表示数字占位符,匹配特定 ID
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);//# 表示数字占位符,匹配特定 ID
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
//两个搜索建议的URI模式一个是基本的搜索建议请求另一个是带有查询字符串的搜索建议请求
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);//*表示任意字符
}
/**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result,
* we will trim '\n' and white space in order to show more information.
*
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
//将摘要中的换行符替换为空字符串后,去除两端空字符,作为搜索结果的主文本
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
//与主文本内容一致
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
//资源里的图片作为指定搜索结果的图标
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
//显示用户的数据 作为 点击搜索结果时要执行的动作
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
//文本数据类型 作为 指定内容的 MIME 类型
//定义了一个用于根据内容摘要进行搜索的SQL查询语句。
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
//"?"是占位符,在查找时,将传入搜索的内容
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
//不搜索垃圾文件夹中便签
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
//只搜索普通便签
//创建NotesDatabaseHelper实例
@Override
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
/**
* @method query
* @description URI.
* @param [uri, projection, selection, selectionArgs, sortOrder]
* @return android.database.Cursor
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
switch (mMatcher.match(uri)) {
switch (mMatcher.match(uri)) { //根据返回的匹配码执行相应操作
case URI_NOTE:
//查Note表中的内容
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
id = uri.getPathSegments().get(1);//获取便签id
//构建查询条件确保只查询指定ID
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
//查询数据表中的数据
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
@ -113,11 +144,13 @@ public class NotesProvider extends ContentProvider {
case URI_SEARCH:
case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) {
//搜索查询不允许指定排序顺序或投影
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
String searchString = null;
//从URI中提取搜索字符串
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1);
@ -131,7 +164,8 @@ public class NotesProvider extends ContentProvider {
}
try {
searchString = String.format("%%%s%%", searchString);
searchString = String.format("%%%s%%", searchString);//用于模糊匹配的SQL通配符
//执行预定义的 SQL 查询语句,传入搜索字符串作为参数
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
} catch (IllegalStateException ex) {
@ -141,46 +175,60 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
//设置通知URI以便在数据更改时通知观察者不懂
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
/**
* @method insert
* @description URIContentValues
* @param [uri, values]
* @return android.net.Uri URI
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
insertedId = noteId = db.insert(TABLE.NOTE, null, values);//插入新的记录
break;
case URI_DATA:
//确保数据关联的ID有效
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
Log.d(TAG, "Wrong data format without note id:" + values.toString());
}
insertedId = dataId = db.insert(TABLE.DATA, null, values);
insertedId = dataId = db.insert(TABLE.DATA, null, values);//插入新的数据记录
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
// Notify the note uri 通知相关的URI表示数据已更改
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
// Notify the data uri 通知相关的数据URI表示数据已更改
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
return ContentUris.withAppendedId(uri, insertedId);
return ContentUris.withAppendedId(uri, insertedId); //返回新插入的URI
}
/**
* @method delete
* @description
* @param [uri, selection, selectionArgs]
* @return int
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
@ -189,10 +237,11 @@ public class NotesProvider extends ContentProvider {
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";//确保不删除系统文件夹
count = db.delete(TABLE.NOTE, selection, selectionArgs);//删除相关便签,返回删除的记录数
break;
case URI_NOTE_ITEM:
//获取要删除的id
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
@ -219,14 +268,22 @@ public class NotesProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
//如果删除了data记录通知相关的note URI
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
//通知传入的URI表示数据已更改
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
/**
* @method update
* @description
* @param [uri, values, selection, selectionArgs]
* @return int
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
@ -235,7 +292,7 @@ public class NotesProvider extends ContentProvider {
boolean updateData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs);
increaseNoteVersion(-1, selection, selectionArgs);//更新便签版本号
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
@ -260,42 +317,60 @@ public class NotesProvider extends ContentProvider {
if (count > 0) {
if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);//通知便签URI数据已更改
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
/**
* @method parseSelection
* @description //辅助方法,用于解析查询条件字符串,确保在已有条件的基础上正确添加新的条件。
* @param selection
* @return String
*/
private String parseSelection(String selection) {
//如果selection不为空则在前面加上" AND (",并在后面加上")",否则返回空字符串
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
/**
* @method increaseNoteVersion
* @description 便便
* @param
* @return
*/
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
StringBuilder sql = new StringBuilder(120);//初始化一个容量为120的StringBuilder对象用于构建SQL语句
//构建更新便签版本号的SQL语句
sql.append("UPDATE ");
sql.append(TABLE.NOTE);
sql.append(" SET ");
sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
//如果指定了id或selection则添加WHERE子句
if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE ");
}
//如果指定了id则添加ID条件
if (id > 0) {
sql.append(NoteColumns.ID + "=" + String.valueOf(id));
}
if (!TextUtils.isEmpty(selection)) {
String selectString = id > 0 ? parseSelection(selection) : selection;
for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args);
selectString = selectString.replaceFirst("\\?", args);//将每个占位符 '?' 替换为实际的参数值
}
sql.append(selectString);
}
mHelper.getWritableDatabase().execSQL(sql.toString());
mHelper.getWritableDatabase().execSQL(sql.toString());//执行构建好的SQL语句
}
//未实现获取URI对应的MIME类型
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub

@ -25,6 +25,11 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
* @Package: net.micode.notes.gtask.data
* @ClassName: MetaData
* @Description: Google Task便Google Task
*/
public class MetaData extends Task {
private final static String TAG = MetaData.class.getSimpleName();
@ -47,7 +52,7 @@ public class MetaData extends Task {
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
}//只要便签非空,就认为值得保存
@Override
public void setContentByRemoteJSON(JSONObject js) {
@ -66,16 +71,19 @@ public class MetaData extends Task {
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
//功能是被禁止调用的,因为元数据不从本地 JSON 设置内容
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
@Override
public JSONObject getLocalJSONFromContent() {
//功能是被禁止调用的,因为元数据不生成本地 JSON 内容
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
@Override
public int getSyncAction(Cursor c) {
//功能是被禁止调用的,因为元数据不参与同步操作
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
}

@ -18,9 +18,17 @@ package net.micode.notes.gtask.data;
import android.database.Cursor;
import org.json.JSONObject;
/**
*
* @Package: net.micode.notes.gtask.data
* @ClassName: Node
* @Description:
*/
public abstract class Node {
//同步操作类型常量定义
public static final int SYNC_ACTION_NONE = 0;
public static final int SYNC_ACTION_ADD_REMOTE = 1;
@ -39,6 +47,7 @@ public abstract class Node {
public static final int SYNC_ACTION_ERROR = 8;
// 节点的全局唯一标识符
private String mGid;
private String mName;
@ -47,6 +56,7 @@ public abstract class Node {
private boolean mDeleted;
// 构造函数,初始化节点的基本属性
public Node() {
mGid = null;
mName = "";
@ -54,7 +64,15 @@ public abstract class Node {
mDeleted = false;
}
public abstract JSONObject getCreateAction(int actionId);
/**
* : JSON
* JSON
*
* get set
*/
public abstract JSONObject getCreateAction(int actionId);//
public abstract JSONObject getUpdateAction(int actionId);

@ -34,17 +34,24 @@ import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @Package: net.micode.notes.gtask.data
* @ClassName: SqlData
* @Description: Google Task便
*/
public class SqlData {
private static final String TAG = SqlData.class.getSimpleName();
private static final int INVALID_ID = -99999;
//包含便签数据表的核心字段,用于查询和加载数据
public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
};
// 查询结果列索引常量,提高代码可读性和维护性
public static final int DATA_ID_COLUMN = 0;
public static final int DATA_MIME_TYPE_COLUMN = 1;
@ -57,7 +64,7 @@ public class SqlData {
private ContentResolver mContentResolver;
private boolean mIsCreate;
private boolean mIsCreate;// 标记是否为新建数据
private long mDataId;
@ -69,19 +76,21 @@ public class SqlData {
private String mDataContentData3;
private ContentValues mDiffDataValues;
private ContentValues mDiffDataValues;// 存储数据变化的ContentValues
//构造函数:新建便签
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
mDataId = INVALID_ID;
mDataMimeType = DataConstants.NOTE;
mDataContent = "";
mDataContent = "";// 初始内容为空
mDataContentData1 = 0;
mDataContentData3 = "";
mDiffDataValues = new ContentValues();
}
//构造函数:从数据库游标加载现有数据
public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver();
mIsCreate = false;
@ -89,6 +98,7 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
//从数据库游标加载数据到对象字段
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -97,13 +107,16 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
//将JSON格式的数据解析并设置到对象字段
public void setContent(JSONObject js) throws JSONException {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
// 处理数据ID
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;//如果有ID字段则取值否则设为无效ID
if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId);
}
}//如果是新建数据或ID发生变化记录变化
mDataId = dataId;
//处理MIME类型
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE;
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
@ -111,18 +124,21 @@ public class SqlData {
}
mDataMimeType = dataMimeType;
//处理数据内容
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
if (mIsCreate || !mDataContent.equals(dataContent)) {
mDiffDataValues.put(DataColumns.CONTENT, dataContent);
}
mDataContent = dataContent;
//处理扩展数据1
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
if (mIsCreate || mDataContentData1 != dataContentData1) {
mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
}
mDataContentData1 = dataContentData1;
// 处理扩展数据3
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
@ -130,6 +146,7 @@ public class SqlData {
mDataContentData3 = dataContentData3;
}
//将对象字段序列化为JSON格式用于网络传输或数据交换
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
@ -144,25 +161,44 @@ public class SqlData {
return js;
}
/**
* @method commit
* @description
*
* 1. INSERTURIID
* 2. UPDATE
* 3.
* @param noteId 便ID
* @param validateVersion
* @param version
*/
public void commit(long noteId, boolean validateVersion, long version) {
// 新数据执行INSERT操作
if (mIsCreate) {
// 如果ID是无效值从变更记录中移除ID字段
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID);
}
// 设置关联的便签ID
mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
// 执行插入操作
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try {
mDataId = Long.valueOf(uri.getPathSegments().get(1));
mDataId = Long.valueOf(uri.getPathSegments().get(1));//从返回的URI中提取新数据的ID
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
}
} else {
}
//现有数据执行UPDATE操作
else {
if (mDiffDataValues.size() > 0) {
int result = 0;
if (!validateVersion) {
// 不验证版本:直接更新
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else {
@ -179,6 +215,7 @@ public class SqlData {
}
}
// 清除变更记录,更新对象状态
mDiffDataValues.clear();
mIsCreate = false;
}

@ -38,103 +38,91 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
*
* @Package: net.micode.notes.gtask.data
* @ClassName: SqlNote
* @Description: 便
*/
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; // 无效ID常量表示便签尚未保存到数据库
//便签表的所有字段,用于查询和加载便签
public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID,
NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID,
NoteColumns.VERSION
NoteColumns.ID, // 便签ID
NoteColumns.ALERTED_DATE, // 提醒日期
NoteColumns.BG_COLOR_ID, // 背景颜色ID
NoteColumns.CREATED_DATE, // 创建日期
NoteColumns.HAS_ATTACHMENT, // 是否有附件
NoteColumns.MODIFIED_DATE, // 修改日期
NoteColumns.NOTES_COUNT, // 子便签数量
NoteColumns.PARENT_ID, // 父文件夹ID
NoteColumns.SNIPPET, // 片段内容
NoteColumns.TYPE, // 便签类型
NoteColumns.WIDGET_ID, // 小部件ID
NoteColumns.WIDGET_TYPE, // 小部件类型
NoteColumns.SYNC_ID, // 同步ID
NoteColumns.LOCAL_MODIFIED, // 本地修改标记
NoteColumns.ORIGIN_PARENT_ID, // 原始父文件夹ID
NoteColumns.GTASK_ID, // Google Task ID
NoteColumns.VERSION // 版本号
};
// 查询结果列索引常量
public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1;
public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3;
public static final int HAS_ATTACHMENT_COLUMN = 4;
public static final int MODIFIED_DATE_COLUMN = 5;
public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8;
public static final int TYPE_COLUMN = 9;
public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12;
public static final int LOCAL_MODIFIED_COLUMN = 13;
public static final int ORIGIN_PARENT_ID_COLUMN = 14;
public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16;
private Context mContext;
private ContentResolver mContentResolver;
private boolean mIsCreate;
private Context mContext; // Android上下文
private ContentResolver mContentResolver; // ContentResolver用于数据库操作
private boolean mIsCreate; // 标记是否为新建便签
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private int mHasAttachment;
private int mHasAttachment; // 是否有附件0无1有
private long mModifiedDate;
private long mParentId;
private String mSnippet;
private int mType;
private long mParentId; // 父文件夹ID
private String mSnippet; // 摘要
private int mType; // 便签类型NOTE/FOLDER/SYSTEM
private int mWidgetId;
private int mWidgetType;
private long mOriginParent; // 原始父文件夹ID用于恢复操作
private long mVersion; // 版本号
private long mOriginParent;
private long mVersion;
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
private ContentValues mDiffNoteValues; // 存储便签变化的ContentValues
private ArrayList<SqlData> mDataList; // 关联的数据列表仅TYPE_NOTE类型
//构造函数:创建新便签
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = true;
mId = INVALID_ID;
mAlertDate = 0;
mId = INVALID_ID; // 新便签ID无效
mAlertDate = 0; // 默认无提醒
mBgColorId = ResourceParser.getDefaultBgId(context);
mCreatedDate = System.currentTimeMillis();
mHasAttachment = 0;
mModifiedDate = System.currentTimeMillis();
mParentId = 0;
mSnippet = "";
mType = Notes.TYPE_NOTE;
mParentId = 0; // 默认父文件夹为根目录
mSnippet = ""; // 默认摘要内容为空
mType = Notes.TYPE_NOTE; // 默认为普通便签
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
mOriginParent = 0;
@ -143,35 +131,38 @@ public class SqlNote {
mDataList = new ArrayList<SqlData>();
}
//构造函数:从数据库游标加载现有便签
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
mDataList = new ArrayList<SqlData>(); // 初始化数据列表
if (mType == Notes.TYPE_NOTE) // 如果是普通便签,加载数据内容
loadDataContent();
mDiffNoteValues = new ContentValues();
mDiffNoteValues = new ContentValues(); // 初始化变化值容器
}
//构造函数根据便签ID加载现有便签
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(id);
loadFromCursor(id); // 根据ID加载便签
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
//根据便签ID从数据库加载便签
private void loadFromCursor(long id) {
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(id)
String.valueOf(id)
}, null);
if (c != null) {
c.moveToNext();
@ -181,10 +172,11 @@ public class SqlNote {
}
} finally {
if (c != null)
c.close();
c.close(); // 关闭游标
}
}
//从数据库游标加载便签属性
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
@ -200,13 +192,20 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN);
}
/**
* 便
*
* 1. 便ID
* 2. SqlData
* 3. SqlData
*/
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
mDataList.clear(); // 清空现有数据列表
try {
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] {
String.valueOf(mId)
String.valueOf(mId)
}, null);
if (c != null) {
if (c.getCount() == 0) {
@ -226,13 +225,27 @@ public class SqlNote {
}
}
/**
* @method setContent
* @description JSON便
*
* 1. 便
* 2. 便
* 3.
* @param js 便JSON
* @return
*/
public boolean setContent(JSONObject js) {
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
// 系统文件夹:不能设置
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
Log.w(TAG, "cannot set system folder");
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// for folder we can only update the snnipet and type
}
// 文件夹:只能更新片段和类型
else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// 处理片段内容
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
@ -240,20 +253,26 @@ public class SqlNote {
}
mSnippet = snippet;
// 处理类型
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
}
// 普通便签:处理所有字段
else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 处理便签ID
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id);
}
mId = id;
// 处理提醒日期
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
.getLong(NoteColumns.ALERTED_DATE) : 0;
if (mIsCreate || mAlertDate != alertDate) {
@ -261,6 +280,7 @@ public class SqlNote {
}
mAlertDate = alertDate;
// 处理背景颜色ID
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
if (mIsCreate || mBgColorId != bgColorId) {
@ -268,6 +288,7 @@ public class SqlNote {
}
mBgColorId = bgColorId;
// 处理创建日期
long createDate = note.has(NoteColumns.CREATED_DATE) ? note
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
if (mIsCreate || mCreatedDate != createDate) {
@ -275,6 +296,7 @@ public class SqlNote {
}
mCreatedDate = createDate;
// 处理附件标记
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
.getInt(NoteColumns.HAS_ATTACHMENT) : 0;
if (mIsCreate || mHasAttachment != hasAttachment) {
@ -282,6 +304,7 @@ public class SqlNote {
}
mHasAttachment = hasAttachment;
// 处理修改日期
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
if (mIsCreate || mModifiedDate != modifiedDate) {
@ -289,6 +312,7 @@ public class SqlNote {
}
mModifiedDate = modifiedDate;
// 处理父文件夹ID
long parentId = note.has(NoteColumns.PARENT_ID) ? note
.getLong(NoteColumns.PARENT_ID) : 0;
if (mIsCreate || mParentId != parentId) {
@ -296,6 +320,7 @@ public class SqlNote {
}
mParentId = parentId;
// 处理片段内容
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
@ -303,6 +328,7 @@ public class SqlNote {
}
mSnippet = snippet;
// 处理类型
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
@ -310,6 +336,7 @@ public class SqlNote {
}
mType = type;
// 处理小部件ID
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
: AppWidgetManager.INVALID_APPWIDGET_ID;
if (mIsCreate || mWidgetId != widgetId) {
@ -317,6 +344,7 @@ public class SqlNote {
}
mWidgetId = widgetId;
// 处理小部件类型
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
if (mIsCreate || mWidgetType != widgetType) {
@ -324,6 +352,7 @@ public class SqlNote {
}
mWidgetType = widgetType;
// 处理原始父文件夹ID
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
if (mIsCreate || mOriginParent != originParent) {
@ -331,23 +360,29 @@ public class SqlNote {
}
mOriginParent = originParent;
// 处理数据内容
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null;
// 查找现有的数据对象
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
for (SqlData temp : mDataList) {
if (dataId == temp.getId()) {
sqlData = temp;
break;
}
}
}
// 如果没找到,创建新的数据对象
if (sqlData == null) {
sqlData = new SqlData(mContext);
mDataList.add(sqlData);
}
// 设置数据内容
sqlData.setContent(data);
}
}
@ -359,6 +394,13 @@ public class SqlNote {
return true;
}
/**
* @method getContent
* @description 便JSON
* @param
* @return JSONObject 便JSON
*/
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
@ -369,6 +411,8 @@ public class SqlNote {
}
JSONObject note = new JSONObject();
// 普通便签:包含完整字段和数据
if (mType == Notes.TYPE_NOTE) {
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate);
@ -384,6 +428,7 @@ public class SqlNote {
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
// 添加数据内容
JSONArray dataArray = new JSONArray();
for (SqlData sqlData : mDataList) {
JSONObject data = sqlData.getContent();
@ -392,7 +437,9 @@ public class SqlNote {
}
}
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
}
// 文件夹和系统文件夹仅包含ID、类型和片段
else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.SNIPPET, mSnippet);
@ -407,86 +454,118 @@ public class SqlNote {
return null;
}
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
}
//设置Google Task ID
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
//设置同步ID
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
//重置本地修改标记。在同步完成后调用,表示便签已经与远程同步
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}
public long getId() {
return mId;
}
public long getParentId() {
return mParentId;
}
public String getSnippet() {
return mSnippet;
}
//判断是否为普通便签类型
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}
/**
* @method commit
* @description 便
* @param validateVersion
* @return
*/
public void commit(boolean validateVersion) {
// 新便签执行INSERT操作
if (mIsCreate) {
// 如果ID是无效值从变更记录中移除ID字段让数据库自动生成
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID);
}
// 执行插入操作
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
try {
// 从返回的URI中提取新便签的ID
// URI格式content://authority/note/{note_id}
mId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
}
if (mId == 0) {
throw new IllegalStateException("Create thread id failed");
}
// 如果是普通便签,提交关联的所有数据
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1);
}
}
} else {
}
// 现有便签执行UPDATE操作
else {
// 检查便签ID有效性
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id");
}
// 如果有变更,执行更新操作
if (mDiffNoteValues.size() > 0) {
mVersion ++;
mVersion ++; // 版本号自增
int result = 0;
if (!validateVersion) {
// 不验证版本:直接更新
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId)
String.valueOf(mId)
});
} else {
// 验证版本:使用乐观锁机制
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] {
String.valueOf(mId), String.valueOf(mVersion)
});
}
if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing");
}
}
// 如果是普通便签,提交关联的所有数据
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion);
@ -494,12 +573,13 @@ public class SqlNote {
}
}
// refresh local info
// 刷新本地信息:重新从数据库加载,确保数据一致性
loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE)
loadDataContent();
// 清除变更记录,更新对象状态
mDiffNoteValues.clear();
mIsCreate = false;
}
}
}

@ -31,19 +31,24 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @Package: net.micode.notes.gtask.data
* @ClassName: Task
* @Description:
*/
public class Task extends Node {
private static final String TAG = Task.class.getSimpleName();
private boolean mCompleted;
private boolean mCompleted;//任务是否完成
private String mNotes;
private String mNotes;//任务
private JSONObject mMetaInfo;
private JSONObject mMetaInfo; //任务的元数据信息
private Task mPriorSibling;
private Task mPriorSibling;//任务的前一个兄弟任务
private TaskList mParent;
private TaskList mParent; //任务所属的任务列表
public Task() {
super();
@ -54,21 +59,31 @@ public class Task extends Node {
mMetaInfo = null;
}
/**
* @method getCreateAction
* @description JSON
* @param actionId
* @return JSONObject
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
try {
// action_type
//添加任务创建操作的类型标识
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id
//添加操作的唯一标识符
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// index
//添加任务在其父任务列表中的索引位置
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
// entity_delta
//初始化entity,表示任务的具体属性,添加名称、创建者标识、类型和便签
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
@ -77,19 +92,25 @@ public class Task extends Node {
if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
}
//添加任务的完成状态
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
// parent_id
//添加任务所属的父任务列表的标识符
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
// dest_parent_type
//添加任务所属的父任务列表的类型标识
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
// list_id
//添加任务所属的任务列表的标识符
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
// prior_sibling_id
//添加任务的前一个兄弟任务的标识符(如果有的话)
if (mPriorSibling != null) {
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
}
@ -103,6 +124,12 @@ public class Task extends Node {
return js;
}
/**
* @method getUpdateAction
* @description JSON
* @param actionId
* @return JSONObject
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -135,6 +162,12 @@ public class Task extends Node {
return js;
}
/**
* @method setContentByRemoteJSON
* @description JSON
* @param js JSON
* @return
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -175,7 +208,14 @@ public class Task extends Node {
}
}
/**
* @method setContentByLocalJSON
* @description JSON
* @param js JSON
* @return
*/
public void setContentByLocalJSON(JSONObject js) {
//如果传入的 JSON 对象为空或缺少必要的字段,则记录警告日志
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
@ -185,6 +225,7 @@ public class Task extends Node {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
//如果类型不匹配,则记录错误日志并返回
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type");
return;
@ -192,6 +233,7 @@ public class Task extends Node {
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
//找到文本便签的数据,并设置任务的名称
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT));
break;
@ -204,9 +246,15 @@ public class Task extends Node {
}
}
/**
* @method getLocalJSONFromContent
* @description JSON
* @return JSONObject JSON
*/
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
//如果元数据信息为空,表示是从远程创建的新任务
if (mMetaInfo == null) {
// new task created from web
if (name == null) {
@ -218,6 +266,7 @@ public class Task extends Node {
JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject();
//构建表示任务内容的本地 JSON 对象
data.put(DataColumns.CONTENT, name);
dataArray.put(data);
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
@ -247,10 +296,16 @@ public class Task extends Node {
}
}
/**
* @method setMetaInfo
* @description
* @param metaData MetaData
* @return
*/
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
mMetaInfo = new JSONObject(metaData.getNotes());
mMetaInfo = new JSONObject(metaData.getNotes());//将 MetaData 对象的便签信息解析为 JSON 对象并存储
} catch (JSONException e) {
Log.w(TAG, e.toString());
mMetaInfo = null;
@ -258,6 +313,12 @@ public class Task extends Node {
}
}
/**
* @method getSyncAction
* @description
* @param c
* @return int
*/
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
@ -276,18 +337,21 @@ public class Task extends Node {
}
// validate the note id now
//如果本地数据的 ID 与远程数据的 ID 不匹配
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
Log.w(TAG, "note id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL;
}
//如果本地数据的修改标志为 0即没有本地更新
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update
//如果本地数据的同步 ID 与任务的最后修改时间戳匹配
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side
return SYNC_ACTION_NONE;
} else {
// apply remote to local
// apply remote to local 远程更新
return SYNC_ACTION_UPDATE_LOCAL;
}
} else {
@ -297,9 +361,10 @@ public class Task extends Node {
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
// local modification only 仅本地更新
return SYNC_ACTION_UPDATE_REMOTE;
} else {
//本地-远程更新 更新冲突
return SYNC_ACTION_UPDATE_CONFLICT;
}
}
@ -311,6 +376,7 @@ public class Task extends Node {
return SYNC_ACTION_ERROR;
}
//任务有元数据信息,或名称非空,或便签非空,则认为值得保存
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);

@ -29,7 +29,16 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
*
* @Package: net.micode.notes.gtask.data
* @ClassName: TaskList
* @Description: Node
* 1. Task
* 2. Google Task APIJSON
* 3.
* 4.
*/
public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();
@ -137,15 +146,19 @@ public class TaskList extends Node {
try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
//如果是文件夹类型,则设置名称为“文件夹:名称”
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
}
//否则如果是系统文件夹类型则根据ID设置名称
else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)//如果是根文件夹
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);//设置名称为“文件夹:默认文件夹”
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)//如果是通话记录文件夹
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE);
+ GTaskStringUtils.FOLDER_CALL_NOTE);//设置名称为“文件夹:通话记录”
else
Log.e(TAG, "invalid system folder");
} else {
@ -222,36 +235,38 @@ public class TaskList extends Node {
public boolean addChildTask(Task task) {
boolean ret = false;
//如果任务不为空且不在子任务列表中,添加子任务
if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task);
if (ret) {
// need to set prior sibling and parent
// need to set prior sibling and parent 设置兄弟节点和父节点
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1));
.get(mChildren.size() - 1));//如果前一个任务为空则设置前一个任务为null否则设置为子任务列表中的最后一个任务
task.setParent(this);
}
}
return ret;
}
// 在指定位置添加子任务
public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index");
return false;
}
int pos = mChildren.indexOf(task);
int pos = mChildren.indexOf(task);//获取任务在子任务列表中的位置
if (task != null && pos == -1) {
mChildren.add(index, task);
// update the task list
//更新任务列表
Task preTask = null;
Task afterTask = null;
if (index != 0)
preTask = mChildren.get(index - 1);
if (index != mChildren.size() - 1)
afterTask = mChildren.get(index + 1);
task.setPriorSibling(preTask);
if (afterTask != null)
afterTask.setPriorSibling(task);
@ -273,6 +288,7 @@ public class TaskList extends Node {
// update the task list
if (index != mChildren.size()) {
//如果被移除任务不是最后一个任务,则将其后一个任务的前一个任务设置为被移除任务的前一个任务
mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1));
}
@ -281,6 +297,7 @@ public class TaskList extends Node {
return ret;
}
// 移动子任务到指定位置
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
@ -296,9 +313,10 @@ public class TaskList extends Node {
if (pos == index)
return true;
return (removeChildTask(task) && addChildTask(task, index));
return (removeChildTask(task) && addChildTask(task, index));//先移除任务,再添加到指定位置
}
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@ -309,10 +327,12 @@ public class TaskList extends Node {
return null;
}
// 根据任务获取子任务索引
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
// 根据索引获取子任务
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
@ -321,6 +341,7 @@ public class TaskList extends Node {
return mChildren.get(index);
}
// 根据 GID 获取子任务
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))

@ -16,17 +16,21 @@
package net.micode.notes.gtask.exception;
// 自定义异常类:表示操作失败的异常
public class ActionFailureException extends RuntimeException {
private static final long serialVersionUID = 4425249765923293627L;
private static final long serialVersionUID = 4425249765923293627L;//序列化版本号
// 构造方法
public ActionFailureException() {
super();
}
// 构造方法,带有错误信息
public ActionFailureException(String paramString) {
super(paramString);
}
// 构造方法,带有错误信息和原因
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}

@ -16,17 +16,21 @@
package net.micode.notes.gtask.exception;
// 自定义异常类:表示网络故障的异常
public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L;
private static final long serialVersionUID = 2107610287180234136L;//序列化版本号
// 构造方法
public NetworkFailureException() {
super();
}
// 构造方法,带有错误信息
public NetworkFailureException(String paramString) {
super(paramString);
}
// 构造方法,带有错误信息和原因
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}

@ -1,4 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
@ -29,21 +28,29 @@ import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
*
* @Package: net.micode.notes.gtask.remote
* @ClassName: GTaskASyncTask
* @Description: 1. 线Google Task
* 2.
* 3.
* 4.
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; // 同步通知ID
//同步完成监听器接口 用于通知同步服务的完成事件
public interface OnCompleteListener {
void onComplete();
}
private Context mContext;
private NotificationManager mNotifiManager;
private Context mContext; // Android上下文
private NotificationManager mNotifiManager; // 通知管理器
private GTaskManager mTaskManager; // 同步管理器
private OnCompleteListener mOnCompleteListener; // 完成监听器
private GTaskManager mTaskManager;
private OnCompleteListener mOnCompleteListener;
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
@ -53,42 +60,67 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager = GTaskManager.getInstance();
}
public void cancelSync() {
mTaskManager.cancelSync();
}
//发布同步进度
public void publishProgess(String message) {
publishProgress(new String[] {
message
message
});
}
/**
* @method showNotification
* @description
* @param tickerId ID
* @param content
*/
private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_LIGHTS;
notification.flags = Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) {
// 同步中或失败:跳转到设置页面
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);
NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE);
} else {
// 同步成功:跳转到便签列表页面
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE);
}
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);
// 构建通知
Notification.Builder builder = new Notification.Builder(mContext)
.setAutoCancel(true)
.setContentTitle(mContext.getString(R.string.app_name))
.setContentText(content)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setOngoing(true);
Notification notification=builder.getNotification();
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
/**
* @method doInBackground
* @description
* @param unused 使Void
* @return
*/
@Override
protected Integer doInBackground(Void... unused) {
// 发布登录进度
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
// 执行同步
return mTaskManager.sync(mContext, this);
}
//更新同步进度
@Override
protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]);
@ -97,8 +129,11 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
}
}
//同步完成后处理。根据同步结果显示相应的通知,并调用完成监听器
@Override
protected void onPostExecute(Integer result) {
// 根据同步结果显示相应的通知
if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount()));
@ -111,13 +146,14 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled));
}
// 调用完成监听器在新线程中执行避免阻塞UI
if (mOnCompleteListener != null) {
new Thread(new Runnable() {
public void run() {
mOnCompleteListener.onComplete();
}
}).start();
}
}
}
}

@ -61,34 +61,38 @@ import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
*
* @Package: net.micode.notes.gtask.remote
* @ClassName: GTaskClient
* @Description: 1. Google TaskHTTP
* 2.
* 3. API
* 4. ID
*/
public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName();
private static final String GTASK_URL = "https://mail.google.com/tasks/";
private static final String GTASK_URL = "https://mail.google.com/tasks/"; // Google Task基础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"; // GET请求URL
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"; // POST请求URL
private static GTaskClient mInstance = null;
private DefaultHttpClient mHttpClient;
private String mGetUrl;
private String mPostUrl;
private long mClientVersion;
private boolean mLoggedin;
private long mLastLoginTime;
private DefaultHttpClient mHttpClient; // HTTP客户端用于执行网络请求
private String mGetUrl; // 当前使用的GET请求URL
private String mPostUrl; // 当前使用的POST请求URL
private long mClientVersion; // 客户端版本号
private boolean mLoggedin; // 登录状态标记
private long mLastLoginTime; // 上次登录时间,用于会话超时控制
private int mActionId; // 动作ID计数器确保每个请求有唯一ID
private Account mAccount; // 当前同步的Google账户
private JSONArray mUpdateArray; // 批量更新数组,用于缓存更新操作
private int mActionId;
private Account mAccount;
private JSONArray mUpdateArray;
// 构造函数:实现单例模式
private GTaskClient() {
mHttpClient = null;
@ -102,6 +106,7 @@ public class GTaskClient {
mUpdateArray = null;
}
//获取单例实例
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -109,34 +114,42 @@ public class GTaskClient {
return mInstance;
}
/**
* Google Task
* @param activity
* @return
*/
public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
final long interval = 1000 * 60 * 5;
// 检查会话超时假设Cookie在5分钟后过期
final long interval = 1000 * 60 * 5; // 5分钟
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
// need to re-login after account switch
// 检查账户切换:如果当前账户与设置中的账户不同,需要重新登录
if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
.getSyncAccountName(activity))) {
mLoggedin = false;
}
// 如果已经登录,直接返回成功
if (mLoggedin) {
Log.d(TAG, "already logged in");
return true;
}
// 记录本次登录时间
mLastLoginTime = System.currentTimeMillis();
// 获取Google账户授权令牌
String authToken = loginGoogleAccount(activity, false);
if (authToken == null) {
Log.e(TAG, "login google account failed");
return false;
}
// login with custom domain if necessary
// 尝试使用自定义域名登录针对非Gmail用户
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
@ -151,7 +164,7 @@ public class GTaskClient {
}
}
// try to login with google official url
// 如果自定义域名登录失败尝试使用官方Google域名登录
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
@ -164,16 +177,32 @@ public class GTaskClient {
return true;
}
/**
* @method loginGoogleAccount
* @description Google
*
*
* 1. Google
* 2.
* 3. 使AccountManager
* 4. 使
*
* @param activity
* @param invalidateToken 使
* @return String null
*/
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
Account[] accounts = accountManager.getAccountsByType("com.google");
AccountManager accountManager = AccountManager.get(activity);// 获取账户管理器
Account[] accounts = accountManager.getAccountsByType("com.google");// 获取所有Google账户
if (accounts.length == 0) {
Log.e(TAG, "there is no available google account");
return null;
}
// 根据设置中的账户名称查找对应账户
String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null;
for (Account a : accounts) {
@ -189,12 +218,14 @@ public class GTaskClient {
return null;
}
// get the token now
// 获取授权令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
// 如果令牌失效,重新获取
if (invalidateToken) {
accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false);
@ -207,10 +238,21 @@ public class GTaskClient {
return authToken;
}
/**
* @method tryToLoginGtask
* @description Google Task
*
* 1. 使Google Task
* 2. 使
*
* @param activity
* @param authToken
* @return
*/
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the
// token and try again
// 令牌可能过期,使令牌失效并重新获取
authToken = loginGoogleAccount(activity, true);
if (authToken == null) {
Log.e(TAG, "login google account failed");
@ -225,25 +267,42 @@ public class GTaskClient {
return true;
}
/**
* @method loginGtask
* @description 使Google Task
*
* 1. HTTPSocket
* 2. Cookie
* 3. URLGET
* 4. CookieCookieGTL
* 5.
*
* @param authToken
* @return truefalse
*/
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000;
// 配置HTTP客户端参数
int timeoutConnection = 10000; // 连接超时10秒
int timeoutSocket = 15000; // Socket超时15秒
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
mHttpClient = new DefaultHttpClient(httpParameters);
// 设置Cookie存储
BasicCookieStore localBasicCookieStore = new BasicCookieStore();
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
// 登录Google Task
try {
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the cookie now
// 检查认证Cookie是否获取成功
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
@ -255,7 +314,7 @@ public class GTaskClient {
Log.w(TAG, "it seems that there is no auth cookie");
}
// get the client version
// 解析响应内容,获取客户端版本号
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -272,7 +331,7 @@ public class GTaskClient {
e.printStackTrace();
return false;
} catch (Exception e) {
// simply catch all exceptions
// 捕获所有异常,确保稳定性
Log.e(TAG, "httpget gtask_url failed");
return false;
}
@ -280,17 +339,26 @@ public class GTaskClient {
return true;
}
//获取下一个动作ID
private int getActionId() {
return mActionId++;
}
//创建HTTP POST请求对象
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setHeader("AT", "1");
httpPost.setHeader("AT", "1"); // AT=1表示使用Cookie认证
return httpPost;
}
/**
* @method getResponseContent
* @description HttpEntity
* @param entity HTTP
* @return
* @throws IOException IO
*/
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
@ -299,6 +367,7 @@ public class GTaskClient {
}
InputStream input = entity.getContent();
// 根据压缩编码选择对应的解压流
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
@ -319,10 +388,27 @@ public class GTaskClient {
sb = sb.append(buff);
}
} finally {
input.close();
input.close(); // 确保流被关闭
}
}
/**
*
/**
* @method postRequest
* @description POSTGoogle Task
*
* 1.
* 2. HttpPost
* 3. JSON
* 4.
* 5. JSON
*
* @param js JSON
* @return JSON
* @throws NetworkFailureException
* @throws ActionFailureException JSON
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -331,12 +417,13 @@ public class GTaskClient {
HttpPost httpPost = createHttpPost();
try {
// 将JSON对象编码为表单参数
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
list.add(new BasicNameValuePair("r", js.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
// execute the post
// 执行POST请求
HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
@ -360,20 +447,32 @@ public class GTaskClient {
}
}
/**
* @method createTask
* @description
*
* 1.
* 2. JSON
* 3.
* 4. ID
*
* @param task
* @throws NetworkFailureException
*/
public void createTask(Task task) throws NetworkFailureException {
commitUpdate();
commitUpdate(); // 先提交已有的批量更新
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
// 构建动作列表:包含创建任务的动作
actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 添加客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
// 发送请求并处理响应
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -386,20 +485,33 @@ public class GTaskClient {
}
}
/**
* @method createTaskList
* @description
*
* 1.
* 2. JSON
* 3.
* 4. ID
*
* @param tasklist
* @throws NetworkFailureException
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate();
commitUpdate(); // 先提交已有的批量更新
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
// 构建动作列表:包含创建任务列表的动作
actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client version
// 添加客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
// 发送请求并处理响应
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -412,19 +524,22 @@ public class GTaskClient {
}
}
//提交批量更新
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
JSONObject jsPost = new JSONObject();
// action_list
// 添加缓存的更新动作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version
// 添加客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送请求
postRequest(jsPost);
mUpdateArray = null;
mUpdateArray = null; // 清空更新数组
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
@ -433,48 +548,61 @@ public class GTaskClient {
}
}
//将节点的更新操作添加到批量更新数组中
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// too many update items may result in an error
// set max to 10 items
// 优化更新项太多可能导致错误设置最大为10项
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
// 初始化更新数组并添加更新动作
if (mUpdateArray == null)
mUpdateArray = new JSONArray();
mUpdateArray.put(node.getUpdateAction(getActionId()));
}
}
/**
* @method moveTask
* @description
* @param task
* @param preParent
* @param curParent
* @throws NetworkFailureException
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
commitUpdate();
commitUpdate(); // 先提交已有的批量更新
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
// 构建移动动作
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
// 在同一任务列表内移动且不是第一个时设置前一个兄弟节点ID
if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and
// it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
}
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
// 在不同任务列表之间移动时设置目标列表ID
if (preParent != curParent) {
// put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 添加客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
@ -486,22 +614,24 @@ public class GTaskClient {
}
}
//Google Task中删除节点
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
commitUpdate(); // 先提交已有的批量更新
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
// 构建删除动作
node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 添加客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
mUpdateArray = null;
mUpdateArray = null; // 清空更新数组
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
@ -509,6 +639,8 @@ public class GTaskClient {
}
}
//获取当前账户下的所有任务列表
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -520,7 +652,7 @@ public class GTaskClient {
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the task list
// 解析响应内容,提取任务列表信息
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -547,25 +679,27 @@ public class GTaskClient {
}
}
//获取特定任务列表下的所有任务
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
commitUpdate(); // 先提交已有的批量更新
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
// 构建获取所有任务的动作
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); // 不获取已删除的任务
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 添加客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送请求并获取响应
JSONObject jsResponse = postRequest(jsPost);
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
} catch (JSONException e) {
@ -575,11 +709,13 @@ public class GTaskClient {
}
}
//获取当前同步账户
public Account getSyncAccount() {
return mAccount;
}
//重置更新数组
public void resetUpdateArray() {
mUpdateArray = null;
}
}
}

@ -48,45 +48,47 @@ import java.util.Iterator;
import java.util.Map;
/**
*
* @Package: net.micode.notes.gtask.remote
* @ClassName: GTaskManager
* @Description:
* 1. SQLiteGoogle Task
* 2.
* 3. IDGoogle Task ID
* 4. 便
*/
public class GTaskManager {
private static final String TAG = GTaskManager.class.getSimpleName();
public static final int STATE_SUCCESS = 0;
public static final int STATE_NETWORK_ERROR = 1;
public static final int STATE_INTERNAL_ERROR = 2;
private static final String TAG = GTaskManager.class.getSimpleName(); // 日志标签
public static final int STATE_SYNC_IN_PROGRESS = 3;
public static final int STATE_SYNC_CANCELLED = 4;
// 同步状态常量
public static final int STATE_SUCCESS = 0; // 同步成功
public static final int STATE_NETWORK_ERROR = 1; // 网络错误
public static final int STATE_INTERNAL_ERROR = 2; // 内部错误
public static final int STATE_SYNC_IN_PROGRESS = 3; // 同步进行中
public static final int STATE_SYNC_CANCELLED = 4; // 同步已取消
private static GTaskManager mInstance = null;
private Activity mActivity;
private Context mContext;
private ContentResolver mContentResolver;
private boolean mSyncing;
private Activity mActivity; // Activity上下文用于获取授权令牌
private Context mContext; // 应用上下文
private ContentResolver mContentResolver; // ContentResolver用于数据库操作
private boolean mSyncing; // 同步状态标记
private boolean mCancelled; // 取消同步标记
private boolean mCancelled;
// Google Task相关数据结构
private HashMap<String, TaskList> mGTaskListHashMap; // Google Task列表映射GID -> TaskList
private HashMap<String, Node> mGTaskHashMap; // Google Task节点映射GID -> Node
private HashMap<String, MetaData> mMetaHashMap; // 元数据映射相关GID -> MetaData
private TaskList mMetaList; // 元数据任务列表
private HashMap<String, TaskList> mGTaskListHashMap;
// 本地数据相关
private HashSet<Long> mLocalDeleteIdMap; // 本地待删除的便签ID集合
private HashMap<String, Long> mGidToNid; // GID到本地ID的映射
private HashMap<Long, String> mNidToGid; // 本地ID到GID的映射
private HashMap<String, Node> mGTaskHashMap;
private HashMap<String, MetaData> mMetaHashMap;
private TaskList mMetaList;
private HashSet<Long> mLocalDeleteIdMap;
private HashMap<String, Long> mGidToNid;
private HashMap<Long, String> mNidToGid;
//初始化所有数据结构和状态变量
private GTaskManager() {
mSyncing = false;
mCancelled = false;
@ -99,6 +101,7 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>();
}
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@ -106,20 +109,41 @@ public class GTaskManager {
return mInstance;
}
//设置Activity上下文
public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
mActivity = activity;
}
/**
* @method sync
* @description
* 1.
* 2.
* 3. Google Task
* 4.
* 5. 便
* 6.
* 7.
*
* @param context Android
* @param asyncTask
* @return
*/
public int sync(Context context, GTaskASyncTask asyncTask) {
// 检查是否已经在同步中
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS;
}
// 初始化同步环境
mContext = context;
mContentResolver = mContext.getContentResolver();
mSyncing = true;
mCancelled = false;
// 清空数据结构,准备新的同步
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
@ -129,20 +153,20 @@ public class GTaskManager {
try {
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
client.resetUpdateArray(); // 重置客户端更新数组
// login google task
// 登录Google Task
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed");
}
}
// get the task list from google
// 初始化任务列表
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList();
// do content sync work
// 执行内容同步
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent();
} catch (NetworkFailureException e) {
@ -156,6 +180,7 @@ public class GTaskManager {
e.printStackTrace();
return STATE_INTERNAL_ERROR;
} finally {
// 无论成功失败,都清理资源
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
@ -168,26 +193,36 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
/**
* @method initGTaskList
* @description Google Task
*
* 1. Google Task
* 2.
* 3.
* 4.
* 5.
*/
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
if (mCancelled) return;
GTaskClient client = GTaskClient.getInstance();
try {
JSONArray jsTaskLists = client.getTaskLists();
// init meta list first
// 首先初始化元数据列表
mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
// 查找元数据列表(名称以特定前缀开头)
if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object);
// load meta data
// 加载元数据列表中的所有元数据任务
JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j);
@ -203,29 +238,28 @@ public class GTaskManager {
}
}
// create meta list if not existed
// 如果元数据列表不存在,创建新的
if (mMetaList == null) {
mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META);
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META);
GTaskClient.getInstance().createTaskList(mMetaList);
}
// init task list
// 初始化普通任务列表
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
// 只处理以MIUI前缀开头的任务列表排除元数据列表
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) {
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist);
// load tasks
// 加载任务列表中的所有任务
JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j);
@ -247,6 +281,17 @@ public class GTaskManager {
}
}
/**
* @method syncContent
* @description 便
*
* 1. 便
* 2. 便
* 3. 便
* 4.
* 5. 便
* 6. ID
*/
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;
@ -255,11 +300,9 @@ public class GTaskManager {
mLocalDeleteIdMap.clear();
if (mCancelled) {
return;
}
if (mCancelled) return;
// for local deleted note
// 第一步:处理本地已删除的便签(在回收站中的便签)
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] {
@ -286,10 +329,10 @@ public class GTaskManager {
}
}
// sync folder first
// 第二步:同步文件夹(必须先同步文件夹,因为便签需要知道父文件夹的映射关系)
syncFolder();
// for note existing in database
// 第三步:同步现有的便签
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
@ -306,10 +349,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
// 本地新增本地有GID但远程没有对应节点
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
// 远程删除本地有GID但远程节点不存在
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
@ -318,7 +361,6 @@ public class GTaskManager {
} else {
Log.w(TAG, "failed to query existing note in database");
}
} finally {
if (c != null) {
c.close();
@ -326,7 +368,7 @@ public class GTaskManager {
}
}
// go through remaining items
// 第四步处理远程新增的项目遍历剩余的Google Task节点
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
@ -334,34 +376,38 @@ public class GTaskManager {
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
// mCancelled can be set by another thread, so we neet to check one by
// one
// clear local delete table
// 第五步:批量删除本地已删除的便签
if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes");
}
}
// refresh local sync id
// 第六步刷新本地同步ID
if (!mCancelled) {
GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId();
}
}
/**
* @method syncFolder
* @description
*
* 1.
* 2.
* 3.
* 4.
*/
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
Node node;
int syncType;
if (mCancelled) {
return;
}
if (mCancelled) return;
// for root folder
// 同步根文件夹
try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
@ -373,7 +419,7 @@ public class GTaskManager {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
// for system folder, only update remote name if necessary
// 系统文件夹:只有在名称不同时才更新远程
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
@ -390,11 +436,11 @@ public class GTaskManager {
}
}
// for call-note folder
// 同步通话记录文件夹
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
}, null);
if (c != null) {
if (c.moveToNext()) {
@ -404,11 +450,9 @@ public class GTaskManager {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if
// necessary
// 系统文件夹:只有在名称不同时才更新远程
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE))
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
@ -424,7 +468,7 @@ public class GTaskManager {
}
}
// for local existing folders
// 同步现有的普通文件夹
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
@ -441,10 +485,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
// 本地新增
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
// 远程删除
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
@ -460,7 +504,7 @@ public class GTaskManager {
}
}
// for remote add folders
// 处理远程新增的文件夹
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
@ -476,10 +520,15 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate();
}
/**
* @method doContentSync
* @description
* @param syncType
* @param node Google Task
* @param c
*/
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
if (mCancelled) return;
MetaData meta;
switch (syncType) {
@ -510,25 +559,36 @@ public class GTaskManager {
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea
// right now just use local update simply
// 冲突处理:简单策略,使用本地更新远程
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_NONE:
break;
case Node.SYNC_ACTION_ERROR:
default:
throw new ActionFailureException("unkown sync action type");
throw new ActionFailureException("unknown sync action type");
}
}
/**
* @method addLocalNode
* @description
*
* 1. SqlNote
* 2. ID
* 3. ID
* 4.
* 5. ID
* 6.
*
* @param node
*/
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
}
if (mCancelled) return;
SqlNote sqlNote;
if (node instanceof TaskList) {
// 处理任务列表(文件夹)
if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
@ -541,20 +601,23 @@ public class GTaskManager {
sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
}
} else {
// 处理任务(便签)
sqlNote = new SqlNote(mContext);
JSONObject js = node.getLocalJSONFromContent();
try {
// 检查便签ID是否可用
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// the id is not available, have to create a new one
// ID已被占用移除ID让数据库自动生成新ID
note.remove(NoteColumns.ID);
}
}
}
// 检查数据ID是否可用
if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
for (int i = 0; i < dataArray.length(); i++) {
@ -562,13 +625,11 @@ public class GTaskManager {
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// the data id is not available, have to create
// a new one
// 数据ID已被占用移除ID
data.remove(DataColumns.ID);
}
}
}
}
} catch (JSONException e) {
Log.w(TAG, e.toString());
@ -576,6 +637,7 @@ public class GTaskManager {
}
sqlNote.setContent(js);
// 设置父文件夹ID
Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
@ -584,28 +646,40 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue());
}
// create the local node
// 创建本地节点
sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false);
// update gid-nid mapping
// 更新ID映射
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta
// 更新元数据
updateRemoteMeta(node.getGid(), sqlNote);
}
/**
* @method updateLocalNode
* @description
*
* 1. SqlNote
* 2.
* 3. ID
* 4.
* 5.
*
* @param node
* @param c
*/
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
if (mCancelled) return;
SqlNote sqlNote;
// update the note locally
// 更新本地便签
sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent());
// 更新父文件夹ID
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
: new Long(Notes.ID_ROOT_FOLDER);
if (parentId == null) {
@ -613,25 +687,42 @@ public class GTaskManager {
throw new ActionFailureException("cannot update local node");
}
sqlNote.setParentId(parentId.longValue());
// 提交更新(带版本验证)
sqlNote.commit(true);
// update meta info
// 更新元数据
updateRemoteMeta(node.getGid(), sqlNote);
}
/**
* @method addRemoteNode
* @description
*
*
* 1. Google Task
* 2.
* 3.
* 4. GID
* 5. ID
* 6.
*
* @param node
* @param c
*/
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
if (mCancelled) return;
SqlNote sqlNote = new SqlNote(mContext, c);
Node n;
// update remotely
// 在远程创建节点
if (sqlNote.isNoteType()) {
// 创建任务(便签)
Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent());
// 查找父任务列表
String parentGid = mNidToGid.get(sqlNote.getParentId());
if (parentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
@ -642,12 +733,13 @@ public class GTaskManager {
GTaskClient.getInstance().createTask(task);
n = (Node) task;
// add meta
// 添加元数据
updateRemoteMeta(task.getGid(), sqlNote);
} else {
// 创建任务列表(文件夹)
TaskList tasklist = null;
// we need to skip folder if it has already existed
// 检查是否已存在同名文件夹
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT;
@ -656,6 +748,7 @@ public class GTaskManager {
else
folderName += sqlNote.getSnippet();
// 查找已存在的同名文件夹
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
@ -671,7 +764,7 @@ public class GTaskManager {
}
}
// no match we can add now
// 如果没有匹配的文件夹,创建新的
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
@ -681,32 +774,43 @@ public class GTaskManager {
n = (Node) tasklist;
}
// update local note
// 更新本地节点
sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false);
sqlNote.resetLocalModified();
sqlNote.resetLocalModified(); // 重置本地修改标记
sqlNote.commit(true);
// gid-id mapping
// 更新ID映射
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
/**
* @method updateRemoteNode
* @description
*
*
* 1.
* 2.
* 3.
* 4.
*
* @param node
* @param c
*/
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
if (mCancelled) return;
SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely
// 更新远程节点
node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node);
// update meta
// 更新元数据
updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary
// 如果便签被移动到其他文件夹,处理移动操作
if (sqlNote.isNoteType()) {
Task task = (Task) node;
TaskList preParentList = task.getParent();
@ -725,18 +829,30 @@ public class GTaskManager {
}
}
// clear local modified flag
// 重置本地修改标记
sqlNote.resetLocalModified();
sqlNote.commit(true);
}
/**
* @method updateRemoteMeta
* @description
*
*
* ID便
*
* @param gid Google Task ID
* @param sqlNote 便
*/
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
if (metaData != null) {
// 更新现有元数据
metaData.setMeta(gid, sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(metaData);
} else {
// 创建新的元数据
metaData = new MetaData();
metaData.setMeta(gid, sqlNote.getContent());
mMetaList.addChildTask(metaData);
@ -746,17 +862,18 @@ public class GTaskManager {
}
}
//同步完成后更新本地便签的同步ID
private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) {
return;
}
if (mCancelled) return;
// get the latest gtask list
// 重新获取最新的任务列表
mGTaskHashMap.clear();
mGTaskListHashMap.clear();
mMetaHashMap.clear();
initGTaskList();
// 更新本地同步ID
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
@ -790,11 +907,13 @@ public class GTaskManager {
}
}
//获取同步账户名称
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}
public void cancelSync() {
mCancelled = true;
}
}
}

@ -23,50 +23,78 @@ import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
public class GTaskSyncService extends Service {
public final static String ACTION_STRING_NAME = "sync_action_type";
public final static int ACTION_START_SYNC = 0;
public final static int ACTION_CANCEL_SYNC = 1;
public final static int ACTION_INVALID = 2;
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
/**
*
* @Package: net.micode.notes.gtask.remote
* @ClassName: GTaskSyncService
* @Description:
* 1. Google Task
* 2. /Intent
* 3. UI线
* 4. 广
*/
public class GTaskSyncService extends Service {
public final static String ACTION_STRING_NAME = "sync_action_type"; // Intent动作类型键
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
public final static int ACTION_START_SYNC = 0; // 开始同步动作
public final static int ACTION_CANCEL_SYNC = 1; // 取消同步动作
public final static int ACTION_INVALID = 2; // 无效动作
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; // 广播名称
private static GTaskASyncTask mSyncTask = null;
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; // 是否正在同步的键
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; // 进度消息的键
private static String mSyncProgress = "";
private static GTaskASyncTask mSyncTask = null; // 同步任务实例
private static String mSyncProgress = ""; // 同步进度信息
/**
*
*
*
* 1.
* 2. GTaskASyncTask
* 3.
* 4. 广
*/
private void startSync() {
// 确保只有一个同步任务在运行
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
public void onComplete() {
mSyncTask = null;
sendBroadcast("");
stopSelf();
mSyncTask = null; // 清理任务引用
sendBroadcast(""); // 发送完成广播
stopSelf(); // 停止服务自身
}
});
sendBroadcast("");
mSyncTask.execute();
sendBroadcast(""); // 发送开始同步广播
mSyncTask.execute(); // 执行异步任务
}
}
//取消同步
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
//初始化同步任务引用
@Override
public void onCreate() {
mSyncTask = null;
}
/**
* @method onStartCommand
* @description Intent
* @param intent Intent
* @param flags
* @param startId ID
* @return START_STICKY
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
@ -81,11 +109,12 @@ public class GTaskSyncService extends Service {
default:
break;
}
return START_STICKY;
return START_STICKY; // 服务被杀死后自动重启
}
return super.onStartCommand(intent, flags, startId);
}
//当系统内存不足时,取消同步任务以释放资源
@Override
public void onLowMemory() {
if (mSyncTask != null) {
@ -93,10 +122,12 @@ public class GTaskSyncService extends Service {
}
}
//此服务不提供绑定功能返回null
public IBinder onBind(Intent intent) {
return null;
}
//发送同步状态广播
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -105,6 +136,8 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent);
}
//设置GTaskManager的Activity上下文并启动服务
public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
@ -112,17 +145,22 @@ public class GTaskSyncService extends Service {
activity.startService(intent);
}
//从Context调用的便捷方法发送取消同步命令到服务
public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
}
//检查是否正在同步
public static boolean isSyncing() {
return mSyncTask != null;
}
public static String getProgressString() {
return mSyncProgress;
}
}
}

@ -34,9 +34,15 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
/**
*
* @Package: net.micode.notes.model
* @ClassName: Note
* @Description: 便便便便
*/
public class Note {
private ContentValues mNoteDiffValues;
private NoteData mNoteData;
private ContentValues mNoteDiffValues;//用于存储便签属性的变化
private NoteData mNoteData;//用于存储便签的具体数据
private static final String TAG = "Note";
/**
* Create a new note id for adding a new note to databases
@ -44,17 +50,17 @@ public class Note {
public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database
ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis();
long createdTime = System.currentTimeMillis();// 获取当前时间作为创建时间
values.put(NoteColumns.CREATED_DATE, createdTime);
values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);//获取新便签的 URI
long noteId = 0;
try {
noteId = Long.valueOf(uri.getPathSegments().get(1));
noteId = Long.valueOf(uri.getPathSegments().get(1));// 从 URI 中提取便签 ID
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0;
@ -71,9 +77,9 @@ public class Note {
}
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
mNoteDiffValues.put(key, value);// 将便签属性的变化存储到 ContentValues 对象中
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);// 标记便签为本地已修改
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());// 更新修改时间
}
public void setTextData(String key, String value) {
@ -97,9 +103,10 @@ public class Note {
}
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();//便签属性或数据是否有本地修改
}
//同步便签到内容提供器中
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -130,6 +137,7 @@ public class Note {
return true;
}
//内部类:用于存储便签的具体数据
private class NoteData {
private long mTextDataId;
@ -178,6 +186,16 @@ public class Note {
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
* @method pushIntoContentResolver
* @description 便Content Provider
* @param context Android访ContentResolver
* @param noteId 便
* @return Uri 便URInull
*
* WorkingNote.saveNote() Note.syncNote() NoteData.pushIntoContentResolver()
*/
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety
@ -189,6 +207,7 @@ public class Note {
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
//处理文本数据变更
if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) {
@ -211,6 +230,7 @@ public class Note {
mTextDataValues.clear();
}
//处理通话数据变更
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
@ -233,10 +253,13 @@ public class Note {
mCallDataValues.clear();
}
//执行批量操作
if (operationList.size() > 0) {
try {
//批量应用所有数据库操作 applyBatch()确保所有操作在单个事务中执行
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList);
//检查批量操作结果 成功时返回便签的完整URI
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) {

@ -60,8 +60,9 @@ public class WorkingNote {
private boolean mIsDeleted;
private NoteSettingChangedListener mNoteSettingStatusListener;
private NoteSettingChangedListener mNoteSettingStatusListener;// 设置变化监听器
//数据表查询字段投影 用于查询便签数据
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
@ -72,6 +73,7 @@ public class WorkingNote {
DataColumns.DATA4,
};
//便签表查询字段投影 用于查询便签属性
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
@ -101,7 +103,7 @@ public class WorkingNote {
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct
// New note construct 创建新便签
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
@ -114,7 +116,7 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
}
// Existing note construct
// Existing note construct 加载现有便签
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
@ -124,7 +126,9 @@ public class WorkingNote {
loadNote();
}
//从数据库加载便签基本属性
private void loadNote() {
// 构建便签查询URI
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null);
@ -143,9 +147,11 @@ public class WorkingNote {
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}
loadNoteData();
loadNoteData(); // 继续加载便签内容数据
}
//加载便签的内容数据
private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
@ -157,10 +163,12 @@ public class WorkingNote {
do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) {
//处理文本便签数据
mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) {
//处理通话便签数据
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else {
Log.d(TAG, "Wrong note type with type:" + type);
@ -174,6 +182,7 @@ public class WorkingNote {
}
}
//创建空便签工厂方法
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
@ -183,24 +192,32 @@ public class WorkingNote {
return note;
}
//加载现有便签的工厂方法
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
public synchronized boolean saveNote() {
if (isWorthSaving()) {
// 新便签创建数据库记录并获取ID
if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false;
}
}
mNote.syncNote(mContext, mNoteId);
mNote.syncNote(mContext, mNoteId);//同步便签数据到数据库
/**
* Update widget content if there exist any widget of this note
*/
/**
*
*
* 1. ID
* 2.
* 3.
*/
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) {
@ -212,11 +229,20 @@ public class WorkingNote {
}
}
//检查便签是否已存在于数据库中
public boolean existInDatabase() {
return mNoteId > 0;
}
private boolean isWorthSaving() {
/**
* 便
*
*
* 1. 便
* 2. 便
* 3. 便
*/
private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
return false;
@ -239,8 +265,10 @@ public class WorkingNote {
}
}
//标记便签为删除状态
public void markDeleted(boolean mark) {
mIsDeleted = mark;
// 如果便签有关联的小部件,通知小部件更新
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
@ -257,6 +285,7 @@ public class WorkingNote {
}
}
//设置清单模式
public void setCheckListMode(int mode) {
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
@ -281,6 +310,7 @@ public class WorkingNote {
}
}
//设置便签工作文本内容
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
@ -288,6 +318,7 @@ public class WorkingNote {
}
}
//将普通便签转换为通话便签
public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
@ -342,6 +373,7 @@ public class WorkingNote {
return mWidgetType;
}
//便签设置变化监听器接口
public interface NoteSettingChangedListener {
/**
* Called when the background color of current note has just changed

Loading…
Cancel
Save