完成所有包注释 #49

Merged
pg6wepubk merged 1 commits from develop into master 2 months ago

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -35,14 +35,31 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/**
*
*
*/
public class BackupUtils {
// 日志标签,用于调试时在 Logcat 中标识本类的日志输出
private static final String TAG = "BackupUtils";
// Singleton stuff
// 单例模式:持有 BackupUtils 的唯一实例
private static BackupUtils sInstance;
/**
* BackupUtils 线
*
* <p>
* Application Context
* 使 Activity Context ApplicationContext 使
*
* @param context BackupUtils
* @return BackupUtils
*/
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
// 首次调用时创建实例
sInstance = new BackupUtils(context);
}
return sInstance;
@ -69,14 +86,17 @@ public class BackupUtils {
mTextExport = new TextExport(context);
}
//判断外部存储(如 SD 卡)是否已挂载且可读写
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
//执行导出
public int exportToText() {
return mTextExport.exportToText();
}
//获取导出文件的文件名和目录路径
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
@ -85,12 +105,27 @@ public class BackupUtils {
return mTextExport.mFileDirectory;
}
/**
*
*
* <p> ContentProvider NotesData
* .txt
* 使Projection
*
*/
private static class TextExport {
// === 笔记主表Notes Table查询配置 ===
/**
* 使
*
*/
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,
NoteColumns.TYPE
NoteColumns.ID, // 笔记唯一ID
NoteColumns.MODIFIED_DATE, // 最后修改时间
NoteColumns.SNIPPET, // 笔记摘要/标题
NoteColumns.TYPE // 笔记类型(用于分组或过滤)
};
private static final int NOTE_COLUMN_ID = 0;
@ -99,9 +134,16 @@ public class BackupUtils {
private static final int NOTE_COLUMN_SNIPPET = 2;
// === 数据明细表Data Table查询配置 ===
/**
* 使
* Android Contacts Provider EAV
* MIME_TYPE
*/
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.CONTENT, // 主内容(如文本)
DataColumns.MIME_TYPE, // 数据类型(决定 DATA1~DATA4 的语义)
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
@ -112,19 +154,33 @@ public class BackupUtils {
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_CALL_DATE = 2; //通话日期字段的列索引
private static final int DATA_COLUMN_PHONE_NUMBER = 4; //电话号码字段的列索引
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// === 文本格式模板配置 ===
/**
*
* res/values/arrays.xml R.array.format_for_exported_note
*/
private final String [] TEXT_FORMAT;
private static final int FORMAT_FOLDER_NAME = 0;
private static final int FORMAT_NOTE_DATE = 1;
private static final int FORMAT_NOTE_CONTENT = 2;
private Context mContext;
private String mFileName;
private String mFileDirectory;
private Context mContext; //保存上下文,用于访问系统服务
private String mFileName; //存储最近一次成功导出的文件名
private String mFileDirectory; //存储导出文件所在的目录路径
/**
* TextExport
*
* <p>R.array.format_for_exported_note
*
*
* @param context 访
*/
public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
@ -132,6 +188,9 @@ public class BackupUtils {
mFileDirectory = "";
}
/**
* ID
*/
private String getFormat(int id) {
return TEXT_FORMAT[id];
}
@ -146,7 +205,9 @@ public class BackupUtils {
folderId
}, null);
// 检查查询结果是否有效(非 null
if (notesCursor != null) {
// 尝试将游标移动到第一条记录;若结果集为空,则 moveToFirst() 返回 false跳过循环
if (notesCursor.moveToFirst()) {
do {
// Print note's last modified date
@ -156,8 +217,9 @@ public class BackupUtils {
// Query data belong to this note
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext());
} while (notesCursor.moveToNext()); // 移动到下一条笔记,直到遍历完所有记录
}
// 关闭 Cursor 以释放数据库资源,防止内存泄漏
notesCursor.close();
}
}
@ -166,16 +228,20 @@ public class BackupUtils {
* Export note identified by id to a print stream
*/
private void exportNoteToText(String noteId, PrintStream ps) {
// 查询属于该笔记的所有明细数据Data 表),每条数据可能代表文本、电话记录等
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
}, null);
if (dataCursor != null) {
// 遍历该笔记关联的所有数据行(一个笔记可能包含多条 Data 记录)
if (dataCursor.moveToFirst()) {
do {
// 根据 MIME 类型区分数据类型
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// 处理“通话笔记”类型:包含电话号码、通话时间、附加位置信息
// Print phone number
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
@ -195,6 +261,7 @@ public class BackupUtils {
location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {
// 处理普通文本笔记
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
@ -206,6 +273,13 @@ public class BackupUtils {
dataCursor.close();
}
// print a line separator between note
// 注意:当前实现存在两个问题:
// 1. Character.LINE_SEPARATOR 是 Unicode 行分隔符 '\u2028',多数文本编辑器不识别为换行;
// 2. Character.LETTER_NUMBER 实际值为字符 '1'ASCII 49会意外输出数字 "1"。
// 正确做法应使用标准换行符,例如:
// ps.println(); // 推荐:输出平台兼容换行
// 或 ps.write('\n'); // 简单 LF 换行(适用于纯文本导出)
// 建议后续重构此逻辑以避免导出文件包含乱码或多余字符。
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -219,17 +293,22 @@ public class BackupUtils {
* Note will be exported as text which is user readable
*/
public int exportToText() {
// 检查外部存储是否可用(如 SD 卡是否挂载)
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
}
// 获取用于写入导出文本的 PrintStream
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
}
// First export folder and its notes
// 查询所有“非回收站”的文件夹 + 通话记录专用文件夹(即使它可能不满足普通文件夹条件)
// 条件说明:
// - 类型为 TYPE_FOLDER 且父 ID 不是回收站(排除回收站本身)
// - 或者是固定的通话记录文件夹ID = ID_CALL_RECORD_FOLDER
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -241,6 +320,7 @@ public class BackupUtils {
if (folderCursor.moveToFirst()) {
do {
// Print folder's name
// 获取文件夹名称:通话记录文件夹使用固定字符串,其他取自 SNIPPET 字段
String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
@ -248,9 +328,11 @@ public class BackupUtils {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
}
if (!TextUtils.isEmpty(folderName)) {
// 使用预定义模板输出文件夹标题
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
String folderId = folderCursor.getString(NOTE_COLUMN_ID);
// 递归导出该文件夹下的所有笔记
exportFolderToText(folderId, ps);
} while (folderCursor.moveToNext());
}
@ -258,6 +340,7 @@ public class BackupUtils {
}
// Export notes in root's folder
// 查询“根目录”下的普通笔记(即 PARENT_ID = 0 且类型为普通笔记)
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -267,6 +350,7 @@ public class BackupUtils {
if (noteCursor != null) {
if (noteCursor.moveToFirst()) {
do {
// 输出根目录笔记的最后修改时间
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
@ -286,22 +370,28 @@ public class BackupUtils {
* Get a print stream pointed to the file {@generateExportedTextFile}
*/
private PrintStream getExportToTextPrintStream() {
// 生成导出文件的完整路径(位于外部存储指定目录下)
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format);
if (file == null) {
Log.e(TAG, "create file to exported failed");
return null;
}
// 缓存文件名和目录路径
mFileName = file.getName();
mFileDirectory = mContext.getString(R.string.file_path);
PrintStream ps = null;
try {
// 创建指向该文件的输出流(覆盖写入模式)
FileOutputStream fos = new FileOutputStream(file);
// 包装为 PrintStream便于使用 println() 等文本写入方法
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
// 文件无法创建(如路径无效、权限不足、存储未挂载等)
e.printStackTrace();
return null;
} catch (NullPointerException e) {
// 通常由 generateFileMountedOnSDcard 返回 null 或上下文异常导致
e.printStackTrace();
return null;
}
@ -313,10 +403,13 @@ public class BackupUtils {
* Generate the text file to store imported data
*/
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
// 构建文件完整路径:外部存储根目录 + 资源中定义的子路径
StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory());
sb.append(context.getString(filePathResId));
File filedir = new File(sb.toString());
// 在路径后追加格式化后的文件名
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),
@ -324,21 +417,24 @@ public class BackupUtils {
File file = new File(sb.toString());
try {
// 确保目标目录存在,不存在则尝试创建
if (!filedir.exists()) {
filedir.mkdir();
filedir.mkdir(); // 注意mkdir() 只能创建单层目录,若需多级应使用 mkdirs()
}
// 创建空文件(如果尚不存在)
if (!file.exists()) {
file.createNewFile();
}
return file;
} catch (SecurityException e) {
// 通常因缺少 WRITE_EXTERNAL_STORAGE 权限Android 6.0+ 需动态申请)
e.printStackTrace();
} catch (IOException e) {
// 可能原因:磁盘空间不足、路径为只读、文件被占用等
e.printStackTrace();
}
// 任一异常发生或创建失败时,返回 null 表示文件准备失败
return null;
}
}

@ -34,10 +34,21 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList;
import java.util.HashSet;
/**
*
*
*/
public class DataUtils {
public static final String TAG = "DataUtils";
private static final String TAG = "DataUtils"; // 日志标签
/**
*
* @param resolver 访ContentProvider
* @param ids ID
* @return truefalse
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
// 参数检查如果ID集合为空直接返回成功
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
@ -47,18 +58,24 @@ public class DataUtils {
return true;
}
// 创建批量操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
// 安全检查:不允许删除系统根文件夹
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;
}
// 为每个笔记创建删除操作
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
operationList.add(builder.build());
}
try {
// 执行批量删除操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查操作结果
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
@ -72,32 +89,52 @@ public class DataUtils {
return false;
}
/**
*
* @param resolver
* @param id ID
* @param srcFolderId ID
* @param desFolderId ID
*/
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, desFolderId);
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, desFolderId); // 设置新的父文件夹ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 记录原始父文件夹ID
values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改(用于同步)
// 执行更新操作
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
}
/**
*
* @param resolver
* @param ids ID
* @param folderId ID
* @return truefalse
*/
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
long folderId) {
// 参数检查
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
// 创建批量操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
// 为每个笔记创建更新操作
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
builder.withValue(NoteColumns.PARENT_ID, folderId); // 设置目标文件夹ID
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改
operationList.add(builder.build());
}
try {
// 执行批量移动操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查操作结果
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
@ -112,9 +149,12 @@ public class DataUtils {
}
/**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*
* @param resolver
* @return
*/
public static int getUserFolderCount(ContentResolver resolver) {
// 查询条件:类型为文件夹且不在垃圾箱中
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
@ -125,17 +165,24 @@ public class DataUtils {
if(cursor != null) {
if(cursor.moveToFirst()) {
try {
count = cursor.getInt(0);
count = cursor.getInt(0); // 获取数量
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "get folder count failed:" + e.toString());
} finally {
cursor.close();
cursor.close(); // 确保游标被关闭
}
}
}
return count;
}
/**
* ID
* @param resolver
* @param noteId ID
* @param type
* @return truefalse
*/
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
@ -146,13 +193,19 @@ public class DataUtils {
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
exist = true; // 有记录存在
}
cursor.close();
}
return exist;
}
/**
* ID
* @param resolver
* @param noteId ID
* @return truefalse
*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
@ -167,6 +220,12 @@ public class DataUtils {
return exist;
}
/**
* ID
* @param resolver
* @param dataId ID
* @return truefalse
*/
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
@ -181,11 +240,17 @@ public class DataUtils {
return exist;
}
/**
*
* @param resolver
* @param name
* @return truefalse
*/
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);
boolean exist = false;
if(cursor != null) {
@ -197,7 +262,14 @@ public class DataUtils {
return exist;
}
/**
*
* @param resolver
* @param folderId ID
* @return null
*/
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 查询文件夹中所有笔记的小部件信息
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
@ -210,9 +282,10 @@ public class DataUtils {
set = new HashSet<AppWidgetAttribute>();
do {
try {
// 创建小部件属性对象并添加到集合
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
widget.widgetId = c.getInt(0); // 小部件ID
widget.widgetType = c.getInt(1); // 小部件类型
set.add(widget);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString());
@ -224,7 +297,14 @@ public class DataUtils {
return set;
}
/**
* ID
* @param resolver
* @param noteId ID
* @return
*/
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
// 查询通话记录数据
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
@ -233,37 +313,52 @@ public class DataUtils {
if (cursor != null && cursor.moveToFirst()) {
try {
return cursor.getString(0);
return cursor.getString(0); // 返回电话号码
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString());
} finally {
cursor.close();
cursor.close(); // 确保游标被关闭
}
}
return "";
return ""; // 没有找到返回空字符串
}
/**
* ID
* @param resolver
* @param phoneNumber
* @param callDate
* @return ID0
*/
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
// 使用自定义的PHONE_NUMBERS_EQUAL函数比较电话号码
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)",
+ CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
try {
return cursor.getLong(0);
return cursor.getLong(0); // 返回笔记ID
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString());
}
}
cursor.close();
}
return 0;
return 0; // 没有找到返回0
}
/**
* ID
* @param resolver
* @param noteId ID
* @return
* @throws IllegalArgumentException
*/
public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
@ -274,7 +369,7 @@ public class DataUtils {
if (cursor != null) {
String snippet = "";
if (cursor.moveToFirst()) {
snippet = cursor.getString(0);
snippet = cursor.getString(0); // 获取内容摘要
}
cursor.close();
return snippet;
@ -282,14 +377,19 @@ public class DataUtils {
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
/**
*
* @param snippet
* @return
*/
public static String getFormattedSnippet(String snippet) {
if (snippet != null) {
snippet = snippet.trim();
int index = snippet.indexOf('\n');
snippet = snippet.trim(); // 去除首尾空格
int index = snippet.indexOf('\n'); // 查找第一个换行符
if (index != -1) {
snippet = snippet.substring(0, index);
snippet = snippet.substring(0, index); // 只保留第一行
}
}
return snippet;
}
}
}

@ -16,98 +16,112 @@
package net.micode.notes.tool;
/**
* GTask
* Google Task APIJSON
* 便Google Task
*/
public class GTaskStringUtils {
// ==================== 动作相关常量 ====================
/** 动作ID字段名 */
public final static String GTASK_JSON_ACTION_ID = "action_id";
/** 动作列表字段名 */
public final static String GTASK_JSON_ACTION_LIST = "action_list";
/** 动作类型字段名 */
public final static String GTASK_JSON_ACTION_TYPE = "action_type";
/** 创建动作类型 */
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
/** 获取所有动作类型 */
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
/** 移动动作类型 */
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
/** 更新动作类型 */
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
// ==================== 实体属性相关常量 ====================
/** 创建者ID字段名 */
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
/** 子实体字段名 */
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
/** 客户端版本字段名 */
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
/** 完成状态字段名 */
public final static String GTASK_JSON_COMPLETED = "completed";
/** 当前列表ID字段名 */
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
/** 默认列表ID字段名 */
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
/** 删除状态字段名 */
public final static String GTASK_JSON_DELETED = "deleted";
/** 目标列表字段名 */
public final static String GTASK_JSON_DEST_LIST = "dest_list";
/** 目标父级字段名 */
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
/** 目标父级类型字段名 */
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
/** 实体增量字段名 */
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
/** 实体类型字段名 */
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
/** 获取已删除项字段名 */
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
/** ID字段名 */
public final static String GTASK_JSON_ID = "id";
/** 索引字段名 */
public final static String GTASK_JSON_INDEX = "index";
/** 最后修改时间字段名 */
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
/** 最新同步点字段名 */
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
/** 列表ID字段名 */
public final static String GTASK_JSON_LIST_ID = "list_id";
// ==================== 数据结构相关常量 ====================
/** 列表集合字段名 */
public final static String GTASK_JSON_LISTS = "lists";
/** 名称字段名 */
public final static String GTASK_JSON_NAME = "name";
/** 新ID字段名 */
public final static String GTASK_JSON_NEW_ID = "new_id";
/** 便签字段名 */
public final static String GTASK_JSON_NOTES = "notes";
/** 父级ID字段名 */
public final static String GTASK_JSON_PARENT_ID = "parent_id";
/** 前一个兄弟节点ID字段名 */
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
/** 结果字段名 */
public final static String GTASK_JSON_RESULTS = "results";
/** 源列表字段名 */
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
/** 任务字段名 */
public final static String GTASK_JSON_TASKS = "tasks";
/** 类型字段名 */
public final static String GTASK_JSON_TYPE = "type";
/** 组类型(文件夹) */
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
/** 任务类型(便签) */
public final static String GTASK_JSON_TYPE_TASK = "TASK";
/** 用户字段名 */
public final static String GTASK_JSON_USER = "user";
// ==================== MIUI便签特定常量 ====================
/** MIUI文件夹前缀用于标识MIUI便签创建的文件夹 */
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
/** 默认文件夹名称 */
public final static String FOLDER_DEFAULT = "Default";
/** 通话记录便签文件夹名称 */
public final static String FOLDER_CALL_NOTE = "Call_Note";
/** 元数据文件夹名称 */
public final static String FOLDER_META = "METADATA";
// ==================== 元数据相关常量 ====================
/** 元数据头Google Task ID */
public final static String META_HEAD_GTASK_ID = "meta_gid";
/** 元数据头:便签信息 */
public final static String META_HEAD_NOTE = "meta_note";
/** 元数据头:数据信息 */
public final static String META_HEAD_DATA = "meta_data";
/** 元数据便签名称,提示用户不要修改或删除 */
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
}
}

@ -22,151 +22,253 @@ import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
*
* 便
* ID
*/
public class ResourceParser {
// ==================== 颜色常量定义 ====================
/** 黄色 - 便签背景颜色标识 */
public static final int YELLOW = 0;
/** 蓝色 - 便签背景颜色标识 */
public static final int BLUE = 1;
/** 白色 - 便签背景颜色标识 */
public static final int WHITE = 2;
/** 绿色 - 便签背景颜色标识 */
public static final int GREEN = 3;
/** 红色 - 便签背景颜色标识 */
public static final int RED = 4;
/** 默认背景颜色 - 黄色 */
public static final int BG_DEFAULT_COLOR = YELLOW;
// ==================== 字体大小常量定义 ====================
/** 小号字体 */
public static final int TEXT_SMALL = 0;
/** 中号字体 */
public static final int TEXT_MEDIUM = 1;
/** 大号字体 */
public static final int TEXT_LARGE = 2;
/** 超大号字体 */
public static final int TEXT_SUPER = 3;
/** 默认字体大小 - 中号 */
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
/**
* 便
* 便
*/
public static class NoteBgResources {
/** 便签编辑区域背景资源数组,按颜色顺序排列 */
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
R.drawable.edit_yellow, // 黄色背景
R.drawable.edit_blue, // 蓝色背景
R.drawable.edit_white, // 白色背景
R.drawable.edit_green, // 绿色背景
R.drawable.edit_red // 红色背景
};
/** 便签标题区域背景资源数组,按颜色顺序排列 */
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
R.drawable.edit_title_white,
R.drawable.edit_title_green,
R.drawable.edit_title_red
R.drawable.edit_title_yellow, // 黄色标题背景
R.drawable.edit_title_blue, // 蓝色标题背景
R.drawable.edit_title_white, // 白色标题背景
R.drawable.edit_title_green, // 绿色标题背景
R.drawable.edit_title_red // 红色标题背景
};
/**
* ID便
* @param id ID (YELLOW, BLUE, WHITE, GREEN, RED)
* @return ID
*/
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
/**
* ID便
* @param id ID (YELLOW, BLUE, WHITE, GREEN, RED)
* @return ID
*/
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
/**
* ID
* 使
* @param context
* @return ID
*/
public static int getDefaultBgId(Context context) {
// 检查用户是否启用了随机背景颜色功能
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 启用随机颜色返回0-4之间的随机数
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
// 使用默认颜色:黄色
return BG_DEFAULT_COLOR;
}
}
/**
* 便
* 便
*/
public static class NoteItemBgResources {
/** 列表第一个项的背景资源数组 */
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
R.drawable.list_white_up,
R.drawable.list_green_up,
R.drawable.list_red_up
R.drawable.list_yellow_up, // 黄色第一个项
R.drawable.list_blue_up, // 蓝色第一个项
R.drawable.list_white_up, // 白色第一个项
R.drawable.list_green_up, // 绿色第一个项
R.drawable.list_red_up // 红色第一个项
};
/** 列表中间项的背景资源数组 */
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
R.drawable.list_white_middle,
R.drawable.list_green_middle,
R.drawable.list_red_middle
R.drawable.list_yellow_middle, // 黄色中间项
R.drawable.list_blue_middle, // 蓝色中间项
R.drawable.list_white_middle, // 白色中间项
R.drawable.list_green_middle, // 绿色中间项
R.drawable.list_red_middle // 红色中间项
};
/** 列表最后一个项的背景资源数组 */
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
R.drawable.list_white_down,
R.drawable.list_green_down,
R.drawable.list_red_down,
R.drawable.list_yellow_down, // 黄色最后一个项
R.drawable.list_blue_down, // 蓝色最后一个项
R.drawable.list_white_down, // 白色最后一个项
R.drawable.list_green_down, // 绿色最后一个项
R.drawable.list_red_down, // 红色最后一个项
};
/** 单独一项的背景资源数组(列表只有一项时使用) */
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
R.drawable.list_white_single,
R.drawable.list_green_single,
R.drawable.list_red_single
R.drawable.list_yellow_single, // 黄色单独项
R.drawable.list_blue_single, // 蓝色单独项
R.drawable.list_white_single, // 白色单独项
R.drawable.list_green_single, // 绿色单独项
R.drawable.list_red_single // 红色单独项
};
/**
*
* @param id ID
* @return ID
*/
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
/**
*
* @param id ID
* @return ID
*/
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
/**
* 使
* @param id ID
* @return ID
*/
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
/**
*
* @param id ID
* @return ID
*/
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
/**
*
* @return ID
*/
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
/**
*
*
*/
public static class WidgetBgResources {
/** 2x尺寸小部件的背景资源数组 */
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
R.drawable.widget_2x_yellow, // 黄色2x小部件
R.drawable.widget_2x_blue, // 蓝色2x小部件
R.drawable.widget_2x_white, // 白色2x小部件
R.drawable.widget_2x_green, // 绿色2x小部件
R.drawable.widget_2x_red, // 红色2x小部件
};
/**
* 2x
* @param id ID
* @return ID
*/
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
/** 4x尺寸小部件的背景资源数组 */
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
R.drawable.widget_4x_yellow, // 黄色4x小部件
R.drawable.widget_4x_blue, // 蓝色4x小部件
R.drawable.widget_4x_white, // 白色4x小部件
R.drawable.widget_4x_green, // 绿色4x小部件
R.drawable.widget_4x_red // 红色4x小部件
};
/**
* 4x
* @param id ID
* @return ID
*/
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
/**
*
*
*/
public static class TextAppearanceResources {
/** 文本外观样式资源数组,按字体大小顺序排列 */
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
R.style.TextAppearanceNormal, // 正常字体样式
R.style.TextAppearanceMedium, // 中等字体样式
R.style.TextAppearanceLarge, // 大字体样式
R.style.TextAppearanceSuper // 超大字体样式
};
/**
* ID
*
* @param id ID (TEXT_SMALL, TEXT_MEDIUM, TEXT_LARGE, TEXT_SUPER)
* @return ID
*/
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
* HACKME: SharedPreferenceIDbug
* ID
*
*/
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE;
@ -174,8 +276,12 @@ public class ResourceParser {
return TEXTAPPEARANCE_RESOURCES[id];
}
/**
*
* @return
*/
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}
}

@ -39,21 +39,26 @@ import net.micode.notes.tool.DataUtils;
import java.io.IOException;
/**
* - 便
*
*/
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId;
private String mSnippet;
private static final int SNIPPET_PREW_MAX_LEN = 60;
MediaPlayer mPlayer;
private long mNoteId; // 便签ID
private String mSnippet; // 便签内容片段
private static final int SNIPPET_PREW_MAX_LEN = 60; // 片段预览最大长度
MediaPlayer mPlayer; // 媒体播放器,用于播放闹钟声音
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置无标题栏
final Window win = getWindow();
// 添加窗口标志,允许在锁屏界面显示
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// 如果屏幕未开启,设置相关标志以唤醒屏幕
if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
@ -64,8 +69,10 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
Intent intent = getIntent();
try {
// 从Intent中获取便签ID和内容片段
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
// 截取片段内容,如果过长则添加省略号
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet;
@ -75,84 +82,106 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
}
mPlayer = new MediaPlayer();
// 检查便签是否仍然存在于数据库中且为普通类型
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog();
playAlarmSound();
showActionDialog(); // 显示操作对话框
playAlarmSound(); // 播放闹钟声音
} else {
finish();
finish(); // 如果便签不存在,直接结束活动
}
}
/**
*
*/
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
}
/**
*
*/
private void playAlarmSound() {
// 获取默认的闹钟铃声URI
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 获取受静音模式影响的音频流设置
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 设置音频流类型,考虑静音模式设置
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
} else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
try {
// 设置数据源并准备播放
mPlayer.setDataSource(this, url);
mPlayer.prepare();
mPlayer.setLooping(true);
mPlayer.start();
mPlayer.setLooping(true); // 设置循环播放
mPlayer.start(); // 开始播放
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
*/
private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.app_name);
dialog.setMessage(mSnippet);
dialog.setPositiveButton(R.string.notealert_ok, this);
dialog.setTitle(R.string.app_name); // 设置应用名称作为标题
dialog.setMessage(mSnippet); // 设置便签片段作为内容
dialog.setPositiveButton(R.string.notealert_ok, this); // 确定按钮
// 如果屏幕已开启,显示进入按钮(用于跳转到便签编辑界面)
if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this);
}
dialog.show().setOnDismissListener(this);
dialog.show().setOnDismissListener(this); // 设置对话框关闭监听器
}
/**
*
*/
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
case DialogInterface.BUTTON_NEGATIVE: // 点击"进入"按钮
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent);
intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递便签ID
startActivity(intent); // 跳转到便签编辑界面
break;
default:
break;
break; // 确定按钮或其他按钮,不执行特殊操作
}
}
/**
*
*/
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
finish();
stopAlarmSound(); // 停止闹钟声音
finish(); // 结束活动
}
/**
*
*/
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
mPlayer.stop(); // 停止播放
mPlayer.release(); // 释放资源
mPlayer = null; // 置空引用
}
}
}
}

@ -27,39 +27,64 @@ import android.database.Cursor;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
/**
* - 便
* 广
*/
public class AlarmInitReceiver extends BroadcastReceiver {
// 数据库查询的列投影只需要ID和提醒日期
private static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE
NoteColumns.ID, // 便签ID
NoteColumns.ALERTED_DATE // 提醒日期时间戳
};
private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1;
// 列索引常量,提高代码可读性
private static final int COLUMN_ID = 0; // ID列索引
private static final int COLUMN_ALERTED_DATE = 1; // 提醒日期列索引
/**
* 广广
* @param context
* @param intent 广
*/
@Override
public void onReceive(Context context, Intent intent) {
long currentDate = System.currentTimeMillis();
long currentDate = System.currentTimeMillis(); // 获取当前时间戳
// 查询数据库:查找所有未来需要提醒的普通便签
// 条件:提醒日期 > 当前时间 且 类型为普通便签
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
new String[] { String.valueOf(currentDate) },
new String[] { String.valueOf(currentDate) }, // 参数:当前时间
null);
if (c != null) {
// 遍历查询结果,为每个未来的提醒设置闹钟
if (c.moveToFirst()) {
do {
long alertDate = c.getLong(COLUMN_ALERTED_DATE);
long alertDate = c.getLong(COLUMN_ALERTED_DATE); // 获取提醒时间
long noteId = c.getLong(COLUMN_ID); // 获取便签ID
// 创建闹钟触发时的广播意图
Intent sender = new Intent(context, AlarmReceiver.class);
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 设置数据URI便于AlarmReceiver识别具体便签
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId));
// 创建待定意图,用于闹钟管理器
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
AlarmManager alermManager = (AlarmManager) context
// 获取闹钟管理器服务
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext());
// 设置精确闹钟RTC_WAKEUP表示即使设备休眠也会唤醒并触发
alarmManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); // 继续处理下一条记录
}
c.close();
c.close(); // 关闭游标,释放资源
}
}
}
}

@ -20,11 +20,29 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* - AlarmManager广
* 广
*/
public class AlarmReceiver extends BroadcastReceiver {
/**
*
* 广
*
* @param context Activity
* @param intent 广便URI
*/
@Override
public void onReceive(Context context, Intent intent) {
// 将当前意图的类设置为闹钟提醒活动
intent.setClass(context, AlarmAlertActivity.class);
// 添加标志确保在新的任务栈中启动Activity
// 这是必要的因为广播接收器本身没有Activity上下文
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动闹钟提醒界面
context.startActivity(intent);
}
}
}

@ -21,92 +21,122 @@ import java.util.Calendar;
import net.micode.notes.R;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.NumberPicker;
/**
*
* AM/PM
* 1224
*/
public class DateTimePicker extends FrameLayout {
// 默认启用状态
private static final boolean DEFAULT_ENABLE_STATE = true;
private static final int HOURS_IN_HALF_DAY = 12;
private static final int HOURS_IN_ALL_DAY = 24;
private static final int DAYS_IN_ALL_WEEK = 7;
private static final int DATE_SPINNER_MIN_VAL = 0;
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
private static final int MINUT_SPINNER_MIN_VAL = 0;
private static final int MINUT_SPINNER_MAX_VAL = 59;
private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MAX_VAL = 1;
private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner;
private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner;
private Calendar mDate;
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
private boolean mIsAm;
private boolean mIs24HourView;
private boolean mIsEnabled = DEFAULT_ENABLE_STATE;
private boolean mInitialising;
// 时间相关常量定义
private static final int HOURS_IN_HALF_DAY = 12; // 半天的小时数12小时制
private static final int HOURS_IN_ALL_DAY = 24; // 全天小时数24小时制
private static final int DAYS_IN_ALL_WEEK = 7; // 一周天数
// 各选择器的数值范围常量
private static final int DATE_SPINNER_MIN_VAL = 0; // 日期选择器最小值
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; // 日期选择器最大值
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; // 24小时制小时最小值
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; // 24小时制小时最大值
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; // 12小时制小时最小值
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; // 12小时制小时最大值
private static final int MINUT_SPINNER_MIN_VAL = 0; // 分钟选择器最小值
private static final int MINUT_SPINNER_MAX_VAL = 59; // 分钟选择器最大值
private static final int AMPM_SPINNER_MIN_VAL = 0; // AM/PM选择器最小值
private static final int AMPM_SPINNER_MAX_VAL = 1; // AM/PM选择器最大值
// UI组件
private final NumberPicker mDateSpinner; // 日期选择器
private final NumberPicker mHourSpinner; // 小时选择器
private final NumberPicker mMinuteSpinner; // 分钟选择器
private final NumberPicker mAmPmSpinner; // AM/PM选择器
// 数据状态
private Calendar mDate; // 当前选择的日期时间
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; // 日期显示文本数组
private boolean mIsAm; // 是否为上午AM
private boolean mIs24HourView; // 是否为24小时制显示
private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 控件是否启用
private boolean mInitialising; // 初始化状态标志,防止初始化期间触发回调
// 回调接口
private OnDateTimeChangedListener mOnDateTimeChangedListener;
/**
*
*
*/
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 根据新旧值差异调整日期
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl();
onDateTimeChanged();
updateDateControl(); // 更新日期显示
onDateTimeChanged(); // 触发日期时间变化回调
}
};
/**
*
* 12/24
*/
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;
boolean isDateChanged = false; // 标记是否需要调整日期
Calendar cal = Calendar.getInstance();
if (!mIs24HourView) {
// 12小时制下的特殊处理
// 下午11点->12点需要增加一天
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
}
// 上午12点->11点需要减少一天
else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;
updateAmPmControl();
// 处理AM/PM切换11点<->12点
if ((oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) ||
(oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1)) {
mIsAm = !mIsAm; // 切换AM/PM状态
updateAmPmControl(); // 更新AM/PM显示
}
} else {
// 24小时制下的特殊处理
// 23点->0点需要增加一天
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
}
// 0点->23点需要减少一天
else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
}
// 计算实际的小时值12小时制需要转换为24小时制
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged();
onDateTimeChanged(); // 触发回调
// 如果需要调整日期,则更新年月日
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
@ -115,111 +145,169 @@ public class DateTimePicker extends FrameLayout {
}
};
/**
*
*
*/
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0;
int offset = 0; // 小时调整偏移量
// 处理分钟循环59->0需要增加1小时0->59需要减少1小时
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
offset += 1; // 向前滚动增加1小时
} else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
offset -= 1; // 向后滚动减少1小时
}
// 如果需要调整小时
if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();
mDate.add(Calendar.HOUR_OF_DAY, offset); // 调整小时
mHourSpinner.setValue(getCurrentHour()); // 更新小时显示
updateDateControl(); // 更新日期显示(可能因小时调整而跨天)
// 检查并更新AM/PM状态
int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
mIsAm = false; // 下午
updateAmPmControl();
} else {
mIsAm = true;
mIsAm = true; // 上午
updateAmPmControl();
}
}
// 设置新的分钟值
mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged();
onDateTimeChanged(); // 触发回调
}
};
/**
* AM/PM
* AM/PM12
*/
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
mIsAm = !mIsAm; // 切换AM/PM状态
// 根据AM/PM切换调整12小时
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); // PM->AM减少12小时
} else {
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); // AM->PM增加12小时
}
updateAmPmControl();
onDateTimeChanged();
updateAmPmControl(); // 更新AM/PM显示
onDateTimeChanged(); // 触发回调
}
};
/**
*
*/
public interface OnDateTimeChangedListener {
/**
*
* @param view DateTimePicker
* @param year
* @param month 0-11
* @param dayOfMonth 1-31
* @param hourOfDay 0-23
* @param minute 0-59
*/
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
int dayOfMonth, int hourOfDay, int minute);
}
/**
* - 使
* @param context
*/
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
/**
* - 使
* @param context
* @param date
*/
public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context));
}
/**
* -
* @param context
* @param date
* @param is24HourView 24
*/
public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context);
mDate = Calendar.getInstance();
mInitialising = true;
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
mDate = Calendar.getInstance(); // 创建日历实例
mInitialising = true; // 标记开始初始化
// 根据当前时间判断初始AM/PM状态
mIsAm = (getCurrentHourOfDay() < HOURS_IN_HALF_DAY);
// 加载布局文件
inflate(context, R.layout.datetime_picker, this);
// 初始化日期选择器
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
// 初始化小时选择器
mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
// 初始化分钟选择器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnLongPressUpdateInterval(100); // 设置长按更新间隔
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
// 初始化AM/PM选择器
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); // 获取本地化的AM/PM文本
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setDisplayedValues(stringsForAmPm); // 设置显示文本
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state
updateDateControl();
updateHourControl();
updateAmPmControl();
// 更新各控件到初始状态
updateDateControl(); // 更新日期显示
updateHourControl(); // 更新小时显示范围
updateAmPmControl(); // 更新AM/PM显示
set24HourView(is24HourView);
set24HourView(is24HourView); // 设置时间显示格式
// set to current time
setCurrentDate(date);
setCurrentDate(date); // 设置初始时间
setEnabled(isEnabled());
setEnabled(isEnabled()); // 设置启用状态
// set the content descriptions
mInitialising = false;
mInitialising = false; // 标记初始化完成
}
/**
*
* @param enabled truefalse
*/
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
return;
return; // 状态未变化,直接返回
}
super.setEnabled(enabled);
// 设置各子组件的启用状态
mDateSpinner.setEnabled(enabled);
mMinuteSpinner.setEnabled(enabled);
mHourSpinner.setEnabled(enabled);
@ -227,43 +315,45 @@ public class DateTimePicker extends FrameLayout {
mIsEnabled = enabled;
}
/**
*
* @return truefalse
*/
@Override
public boolean isEnabled() {
return mIsEnabled;
}
/**
* Get the current date in millis
*
* @return the current date in millis
*
* @return
*/
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
/**
* Set the current date
*
* @param date The current date in millis
*
* @param date
*/
public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date);
// 分解设置年月日时分
setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
}
/**
* Set the current date
*
* @param year The current year
* @param month The current month
* @param dayOfMonth The current dayOfMonth
* @param hourOfDay The current hourOfDay
* @param minute The current minute
*
* @param year
* @param month 0-11
* @param dayOfMonth 1-31
* @param hourOfDay 0-23
* @param minute 0-59
*/
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
@ -272,41 +362,38 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current year
*
* @return The current year
*
* @return
*/
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}
/**
* Set current year
*
* @param year The current year
*
* @param year
*/
public void setCurrentYear(int year) {
// 初始化期间或年份未变化时跳过回调
if (!mInitialising && year == getCurrentYear()) {
return;
}
mDate.set(Calendar.YEAR, year);
updateDateControl();
onDateTimeChanged();
updateDateControl(); // 更新日期显示
onDateTimeChanged(); // 触发回调
}
/**
* Get current month in the year
*
* @return The current month in the year
*
* @return 0-11
*/
public int getCurrentMonth() {
return mDate.get(Calendar.MONTH);
}
/**
* Set current month in the year
*
* @param month The month in the year
*
* @param month 0-11
*/
public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) {
@ -318,18 +405,16 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current day of the month
*
* @return The day of the month
*
* @return 1-31
*/
public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH);
}
/**
* Set current day of the month
*
* @param dayOfMonth The day of the month
*
* @param dayOfMonth 1-31
*/
public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) {
@ -341,145 +426,179 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current hour in 24 hour mode, in the range (0~23)
* @return The current hour in 24 hour mode
* 24
* @return 0-23
*/
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}
/**
* 12/24
* @return 121-12240-23
*/
private int getCurrentHour() {
if (mIs24HourView){
return getCurrentHourOfDay();
return getCurrentHourOfDay(); // 24小时制直接返回
} else {
int hour = getCurrentHourOfDay();
// 12小时制转换0点显示为1213-23点转换为1-11
if (hour > HOURS_IN_HALF_DAY) {
return hour - HOURS_IN_HALF_DAY;
return hour - HOURS_IN_HALF_DAY; // 下午时间13-23 -> 1-11
} else {
return hour == 0 ? HOURS_IN_HALF_DAY : hour;
return hour == 0 ? HOURS_IN_HALF_DAY : hour; // 0点显示为121-11点不变
}
}
}
/**
* Set current hour in 24 hour mode, in the range (0~23)
*
* @param hourOfDay
* 24
* @param hourOfDay 0-23
*/
public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return;
}
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
// 12小时制需要额外处理AM/PM状态
if (!mIs24HourView) {
if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false;
mIsAm = false; // 下午
if (hourOfDay > HOURS_IN_HALF_DAY) {
hourOfDay -= HOURS_IN_HALF_DAY;
hourOfDay -= HOURS_IN_HALF_DAY; // 13-23点转换为1-11点
}
} else {
mIsAm = true;
mIsAm = true; // 上午
if (hourOfDay == 0) {
hourOfDay = HOURS_IN_HALF_DAY;
hourOfDay = HOURS_IN_HALF_DAY; // 0点转换为12点
}
}
updateAmPmControl();
updateAmPmControl(); // 更新AM/PM显示
}
mHourSpinner.setValue(hourOfDay);
onDateTimeChanged();
mHourSpinner.setValue(hourOfDay); // 设置小时选择器值
onDateTimeChanged(); // 触发回调
}
/**
* Get currentMinute
*
* @return The Current Minute
*
* @return 0-59
*/
public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE);
}
/**
* Set current minute
*
* @param minute 0-59
*/
public void setCurrentMinute(int minute) {
if (!mInitialising && minute == getCurrentMinute()) {
return;
}
mMinuteSpinner.setValue(minute);
mDate.set(Calendar.MINUTE, minute);
onDateTimeChanged();
mMinuteSpinner.setValue(minute); // 设置分钟选择器值
mDate.set(Calendar.MINUTE, minute); // 设置日历分钟
onDateTimeChanged(); // 触发回调
}
/**
* @return true if this is in 24 hour view else false.
* 24
* @return true24false12
*/
public boolean is24HourView () {
return mIs24HourView;
}
/**
* Set whether in 24 hour or AM/PM mode.
*
* @param is24HourView True for 24 hour mode. False for AM/PM mode.
*
* @param is24HourView true24false12
*/
public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) {
return;
return; // 显示模式未变化,直接返回
}
mIs24HourView = is24HourView;
// 显示/隐藏AM/PM选择器
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay();
updateHourControl();
setCurrentHour(hour);
updateAmPmControl();
int hour = getCurrentHourOfDay(); // 保存当前小时
updateHourControl(); // 更新小时选择器范围
setCurrentHour(hour); // 重新设置小时(会进行格式转换)
updateAmPmControl(); // 更新AM/PM显示
}
/**
*
* 37
*/
private void updateDateControl() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis());
// 从当前日期前3天开始计算中间项为当前日期
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
mDateSpinner.setDisplayedValues(null);
mDateSpinner.setDisplayedValues(null); // 清空显示值
// 生成7天的日期显示文本
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.add(Calendar.DAY_OF_YEAR, 1); // 增加一天
// 格式化为"月.日 星期几"的格式
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
}
mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate();
mDateSpinner.setDisplayedValues(mDateDisplayValues); // 设置显示文本
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); // 选中中间项(当前日期)
mDateSpinner.invalidate(); // 刷新显示
}
/**
* AM/PM
* 24AM/PM
*/
private void updateAmPmControl() {
if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE);
mAmPmSpinner.setVisibility(View.GONE); // 24小时制隐藏AM/PM
} else {
int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE);
int index = mIsAm ? Calendar.AM : Calendar.PM; // 计算AM/PM索引
mAmPmSpinner.setValue(index); // 设置AM/PM选择器值
mAmPmSpinner.setVisibility(View.VISIBLE); // 显示AM/PM选择器
}
}
/**
*
* 12/24
*/
private void updateHourControl() {
if (mIs24HourView) {
// 24小时制0-23
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
} else {
// 12小时制1-12
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
}
}
/**
* Set the callback that indicates the 'Set' button has been pressed.
* @param callback the callback, if null will do nothing
*
* @param callback
*/
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback;
}
/**
*
*
*/
private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}
}
}
}

@ -29,62 +29,133 @@ import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
/**
*
* DateTimePicker
* /
*/
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 当前选择的日期时间
private Calendar mDate = Calendar.getInstance();
// 是否为24小时制显示
private boolean mIs24HourView;
// 日期时间设置回调接口
private OnDateTimeSetListener mOnDateTimeSetListener;
// 内嵌的日期时间选择器
private DateTimePicker mDateTimePicker;
/**
*
*
*/
public interface OnDateTimeSetListener {
/**
*
* @param dialog
* @param date
*/
void OnDateTimeSet(AlertDialog dialog, long date);
}
/**
*
* @param context
* @param date
*/
public DateTimePickerDialog(Context context, long date) {
super(context);
// 创建日期时间选择器实例
mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker);
setView(mDateTimePicker); // 将选择器设置为对话框内容视图
// 设置日期时间变化监听器
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
/**
*
*
*/
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
int dayOfMonth, int hourOfDay, int minute) {
// 更新内部 Calendar 对象
mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute);
// 更新对话框标题显示新的日期时间
updateTitle(mDate.getTimeInMillis());
}
});
// 设置初始日期时间
mDate.setTimeInMillis(date);
mDate.set(Calendar.SECOND, 0);
mDate.set(Calendar.SECOND, 0); // 秒数设为0确保时间精度一致
// 更新日期时间选择器的显示
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
setButton(context.getString(R.string.datetime_dialog_ok), this);
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 设置对话框按钮
setButton(DialogInterface.BUTTON_POSITIVE, context.getString(R.string.datetime_dialog_ok), this);
setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 根据系统设置确定时间显示格式
set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 初始化对话框标题
updateTitle(mDate.getTimeInMillis());
}
/**
*
* @param is24HourView true24false12
*/
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
// 注意:这里应该调用 mDateTimePicker.set24HourView(is24HourView) 来同步内部选择器
// 当前实现可能存在问题,只更新了本地变量而没有更新内部选择器
}
/**
*
* @param callBack
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
/**
*
*
* @param date
*/
private void updateTitle(long date) {
// 设置日期时间显示格式标志
int flag =
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
DateUtils.FORMAT_SHOW_YEAR | // 显示年份
DateUtils.FORMAT_SHOW_DATE | // 显示日期
DateUtils.FORMAT_SHOW_TIME; // 显示时间
// 设置时间格式24小时制或12小时制
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
// 注意:上面的逻辑有误,应该是 FORMAT_24HOUR 或 FORMAT_12HOUR
// 正确写法flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR;
// 格式化日期时间并设置为对话框标题
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
/**
*
*
* @param arg0
* @param arg1 ID
*/
public void onClick(DialogInterface arg0, int arg1) {
// 触发日期时间设置完成回调
if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}
}

@ -27,17 +27,33 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
/**
*
* PopupMenu
*
*/
public class DropdownMenu {
private Button mButton;
private PopupMenu mPopupMenu;
private Menu mMenu;
private Button mButton; // 触发下拉菜单的按钮
private PopupMenu mPopupMenu; // Android原生弹出菜单
private Menu mMenu; // 菜单对象
/**
*
* @param context
* @param button
* @param menuId IDR.menu.xxx
*/
public DropdownMenu(Context context, Button button, int menuId) {
mButton = button;
// 设置按钮背景为下拉图标
mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 创建弹出菜单,锚点为按钮
mPopupMenu = new PopupMenu(context, mButton);
// 获取菜单对象
mMenu = mPopupMenu.getMenu();
// 从资源文件加载菜单项
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 设置按钮点击事件:点击时显示下拉菜单
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
@ -45,17 +61,30 @@ public class DropdownMenu {
});
}
/**
*
* @param listener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
/**
* ID
* @param id ID
* @return null
*/
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
/**
*
* @param title
*/
public void setTitle(CharSequence title) {
mButton.setText(title);
}
}
}

@ -28,53 +28,102 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
/**
*
*
*/
public class FoldersListAdapter extends CursorAdapter {
// 数据库查询的列投影只需要ID和名称两列
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
NoteColumns.ID, // 文件夹ID
NoteColumns.SNIPPET // 文件夹名称存储在snippet字段中
};
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1;
// 列索引常量
public static final int ID_COLUMN = 0; // ID列的索引
public static final int NAME_COLUMN = 1; // 名称列的索引
/**
*
* @param context
* @param c
*/
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
/**
*
* @param context
* @param cursor
* @param parent
* @return
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// 创建自定义的文件夹列表项
return new FolderListItem(context);
}
/**
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
// 检查视图类型是否正确
if (view instanceof FolderListItem) {
// 根据ID判断文件夹名称根文件夹显示特殊文本其他文件夹显示实际名称
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
// 绑定文件夹名称到视图
((FolderListItem) view).bind(folderName);
}
}
/**
*
* @param context
* @param position
* @return
*/
public String getFolderName(Context context, int position) {
// 获取指定位置的数据游标
Cursor cursor = (Cursor) getItem(position);
// 根据ID判断文件夹名称根文件夹显示"父文件夹",其他显示实际名称
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}
/**
*
*
*/
private class FolderListItem extends LinearLayout {
private TextView mName;
private TextView mName; // 显示文件夹名称的文本视图
/**
*
* @param context
*/
public FolderListItem(Context context) {
super(context);
// 从布局文件加载视图
inflate(context, R.layout.folder_list_item, this);
// 查找名称文本视图
mName = (TextView) findViewById(R.id.tv_folder_name);
}
/**
*
* @param name
*/
public void bind(String name) {
// 设置文件夹名称文本
mName.setText(name);
}
}
}
}

File diff suppressed because it is too large Load Diff

@ -37,115 +37,167 @@ import net.micode.notes.R;
import java.util.HashMap;
import java.util.Map;
/**
*
*
*/
public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText";
private int mIndex;
private int mSelectionStartBeforeDelete;
private int mIndex; // 当前编辑框在清单列表中的索引位置
private int mSelectionStartBeforeDelete; // 记录删除操作前光标起始位置
private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ;
// 链接协议常量定义
private static final String SCHEME_TEL = "tel:" ; // 电话协议
private static final String SCHEME_HTTP = "http:" ; // 网页协议
private static final String SCHEME_EMAIL = "mailto:" ; // 邮件协议
// 链接协议与对应字符串资源的映射表
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); // 电话 -> "拨打电话"
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); // 网页 -> "打开网页"
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); // 邮件 -> "发送邮件"
}
/**
* Call by the {@link NoteEditActivity} to delete or add edit text
*
* NoteEditActivity
*/
public interface OnTextViewChangeListener {
/**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null
*
* @param index
* @param text
*/
void onEditTextDelete(int index, String text);
/**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen
*
* @param index +1
* @param text
*/
void onEditTextEnter(int index, String text);
/**
* Hide or show item option when text change
*
* @param index
* @param hasText
*/
void onTextChange(int index, boolean hasText);
}
private OnTextViewChangeListener mOnTextViewChangeListener;
/**
* 1Context
*/
public NoteEditText(Context context) {
super(context, null);
mIndex = 0;
mIndex = 0; // 初始化索引为0
}
/**
*
* @param index
*/
public void setIndex(int index) {
mIndex = index;
}
/**
*
* @param listener
*/
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
/**
* 2ContextAttributeSetXML使
*/
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
/**
* 3ContextAttributeSet
*/
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
/**
* -
*
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_DOWN: // 手指按下动作
// 计算点击处在文本内容中的准确坐标
int x = (int) event.getX();
int y = (int) event.getY();
// 减去内边距,得到文本区域内的坐标
x -= getTotalPaddingLeft();
y -= getTotalPaddingTop();
// 加上滚动偏移量,得到文本内容中的绝对坐标
x += getScrollX();
y += getScrollY();
// 获取文本布局对象
Layout layout = getLayout();
// 根据y坐标找到对应的行号
int line = layout.getLineForVertical(y);
// 根据x坐标在该行找到对应的字符偏移量
int off = layout.getOffsetForHorizontal(line, x);
// 将光标设置到计算出的偏移量位置
Selection.setSelection(getText(), off);
break;
}
// 调用父类方法处理其他触摸逻辑(如长按弹出菜单)
return super.onTouchEvent(event);
}
/**
*
*
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_ENTER: // 回车键
if (mOnTextViewChangeListener != null) {
// 如果监听器存在返回false让onKeyUp处理
return false;
}
break;
case KeyEvent.KEYCODE_DEL:
case KeyEvent.KEYCODE_DEL: // 删除键(退格键)
// 记录删除前光标的起始位置用于在onKeyUp中判断是否在行首
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
break;
}
// 其他按键交给父类处理
return super.onKeyDown(keyCode, event);
}
/**
* -
*
*/
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_DEL:
if (mOnTextViewChangeListener != null) {
// 判断条件光标在行首位置0且不是第一个编辑框索引不为0
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
// 触发删除监听通知Activity删除当前编辑框
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true;
return true; // 消费此事件,阻止父类处理
}
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
@ -153,9 +205,13 @@ public class NoteEditText extends EditText {
break;
case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) {
// 获取当前光标位置
int selectionStart = getSelectionStart();
// 截取从光标位置到文本末尾的内容
String text = getText().subSequence(selectionStart, length()).toString();
// 将当前编辑框的文本设置为光标前的内容
setText(getText().subSequence(0, selectionStart));
// 触发回车监听通知Activity插入新编辑框并传递截取的文本
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
@ -167,51 +223,72 @@ public class NoteEditText extends EditText {
return super.onKeyUp(keyCode, event);
}
/**
*
*
*/
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) {
// 如果失去焦点且文本为空,通知无文本状态
if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, false);
} else {
// 其他情况(获得焦点,或失去焦点但文本不为空),通知有文本状态
mOnTextViewChangeListener.onTextChange(mIndex, true);
}
}
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
/**
*
*
*/
@Override
protected void onCreateContextMenu(ContextMenu menu) {
// 检查当前文本是否包含样式(如链接)
if (getText() instanceof Spanned) {
// 获取选区的开始和结束位置
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
// 计算选区的最小和最大位置(考虑用户可能从右向左选择)
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
// 从文本中获取选区范围内的所有链接
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
// 如果选区内有且仅有一个链接
if (urls.length == 1) {
int defaultResId = 0;
int defaultResId = 0; // 菜单项文本的资源ID
// 遍历协议映射检查链接的URL包含哪种协议
for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) {
// 找到匹配的协议获取对应的字符串资源ID
defaultResId = sSchemaActionResMap.get(schema);
break;
}
}
// 如果没有匹配到预定义的协议,使用"其他"选项
if (defaultResId == 0) {
defaultResId = R.string.note_link_other;
}
// 向菜单中添加链接操作项,并设置点击监听器
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// goto a new intent
// 触发链接的默认行为(如打开浏览器、拨号盘等)
urls[0].onClick(NoteEditText.this);
return true;
return true; // 消费此事件
}
});
}
}
// 调用父类方法添加系统默认的菜单项(复制、粘贴等)
super.onCreateContextMenu(menu);
}
}
}

@ -25,200 +25,343 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
/**
*
* Cursor
* 使JavaPOJO
*
*/
public class NoteItemData {
/**
* Projection
*
*/
static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID,
NoteColumns.SNIPPET,
NoteColumns.TYPE,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
NoteColumns.ID, // 笔记ID
NoteColumns.ALERTED_DATE, // 提醒日期
NoteColumns.BG_COLOR_ID, // 背景颜色ID
NoteColumns.CREATED_DATE, // 创建日期
NoteColumns.HAS_ATTACHMENT, // 是否有附件
NoteColumns.MODIFIED_DATE, // 最后修改日期
NoteColumns.NOTES_COUNT, // 包含的笔记数量(针对文件夹)
NoteColumns.PARENT_ID, // 父文件夹ID
NoteColumns.SNIPPET, // 内容摘要/片段
NoteColumns.TYPE, // 类型(笔记、文件夹、系统文件夹等)
NoteColumns.WIDGET_ID, // 关联的小部件ID
NoteColumns.WIDGET_TYPE, // 小部件类型
};
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private boolean mHasAttachment;
private long mModifiedDate;
private int mNotesCount;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private String mName;
private String mPhoneNumber;
private boolean mIsLastItem;
private boolean mIsFirstItem;
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;
/**
* PROJECTION
* 使0,1,2
*/
private static final int ID_COLUMN = 0; // ID列的索引
private static final int ALERTED_DATE_COLUMN = 1; // 提醒日期列的索引
private static final int BG_COLOR_ID_COLUMN = 2; // 背景颜色ID列的索引
private static final int CREATED_DATE_COLUMN = 3; // 创建日期列的索引
private static final int HAS_ATTACHMENT_COLUMN = 4; // 是否有附件列的索引
private static final int MODIFIED_DATE_COLUMN = 5; // 修改日期列的索引
private static final int NOTES_COUNT_COLUMN = 6; // 笔记数量列的索引
private static final int PARENT_ID_COLUMN = 7; // 父文件夹ID列的索引
private static final int SNIPPET_COLUMN = 8; // 内容摘要列的索引
private static final int TYPE_COLUMN = 9; // 类型列的索引
private static final int WIDGET_ID_COLUMN = 10; // 小部件ID列的索引
private static final int WIDGET_TYPE_COLUMN = 11; // 小部件类型列的索引
// 成员变量,对应数据库中的各个字段
private long mId; // 笔记/文件夹的唯一标识ID
private long mAlertDate; // 提醒时间戳(毫秒)
private int mBgColorId; // 背景颜色资源ID
private long mCreatedDate; // 创建时间戳(毫秒)
private boolean mHasAttachment; // 是否有附件true/false
private long mModifiedDate; // 最后修改时间戳(毫秒)
private int mNotesCount; // 文件夹中包含的笔记数量(如果是文件夹的话)
private long mParentId; // 父文件夹的ID
private String mSnippet; // 笔记内容的摘要/片段(用于列表显示)
private int mType; // 类型(笔记、文件夹、系统文件夹等)
private int mWidgetId; // 关联的桌面小部件ID
private int mWidgetType; // 桌面小部件的类型
// 额外添加的业务逻辑相关字段(不直接来自数据库)
private String mName; // 联系人姓名(如果是通话记录笔记)
private String mPhoneNumber; // 电话号码(如果是通话记录笔记)
// 位置状态标志,用于判断当前项在列表中的位置关系
private boolean mIsLastItem; // 是否是列表中的最后一项
private boolean mIsFirstItem; // 是否是列表中的第一项
private boolean mIsOnlyOneItem; // 是否是列表中唯一的一项
private boolean mIsOneNoteFollowingFolder; // 是否是一个紧跟在文件夹后面的笔记
private boolean mIsMultiNotesFollowingFolder; // 是否是多个紧跟在文件夹后面的笔记之一
/**
* Cursor
* @param context
* @param cursor
*/
public NoteItemData(Context context, Cursor cursor) {
// 从游标中按列索引获取数据,并赋值给对应的成员变量
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
// 将整数值转换为布尔值大于0表示有附件true否则为false
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN);
// 清理摘要文本中的清单标记符号(对勾和方框),让显示更干净
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
// 初始化电话号码和姓名为空
mPhoneNumber = "";
// 如果当前项属于"通话记录"文件夹
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
// 根据笔记ID查询对应的电话号码
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
// 如果电话号码不为空,通过联系人提供者查询对应的联系人姓名
mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) {
// 如果查询不到联系人,则用电话号码本身作为显示名称
mName = mPhoneNumber;
}
}
}
// 确保姓名不为null避免后续使用时报错
if (mName == null) {
mName = "";
}
// 检查当前项在列表中的位置状态(如是否是第一项、最后一项等)
checkPostion(cursor);
}
/**
*
* UI线
* @param cursor
*/
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1);
// 使用游标的方法判断位置
mIsLastItem = cursor.isLast() ? true : false; // 是否是最后一项
mIsFirstItem = cursor.isFirst() ? true : false; // 是否是第一项
mIsOnlyOneItem = (cursor.getCount() == 1); // 是否只有一项
// 初始化位置关系标志为false
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
// 只有当当前项是笔记类型(不是文件夹),且不是第一项时,才需要检查前面的项
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
// 记录当前位置
int position = cursor.getPosition();
// 将游标移动到前一项(即列表中的上一行)
if (cursor.moveToPrevious()) {
// 检查前一项的类型是否是文件夹或系统文件夹
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
// 判断当前项后面是否还有其他项
if (cursor.getCount() > (position + 1)) {
// 如果后面还有项,说明有多个笔记跟在文件夹后面
mIsMultiNotesFollowingFolder = true;
} else {
// 如果后面没有项了,说明只有一个笔记跟在文件夹后面
mIsOneNoteFollowingFolder = true;
}
}
// 将游标移回原来的位置
if (!cursor.moveToNext()) {
// 理论上不应该发生,如果发生了说明游标状态有问题
throw new IllegalStateException("cursor move to previous but can't move back");
}
}
}
}
// ========== 以下是一系列的getter方法用于外部获取对象的属性值 ==========
/**
*
* @return true
*/
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
/**
*
* @return true
*/
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
}
/**
*
* @return true
*/
public boolean isLast() {
return mIsLastItem;
}
/**
*
* @return
*/
public String getCallName() {
return mName;
}
/**
*
* @return true
*/
public boolean isFirst() {
return mIsFirstItem;
}
/**
*
* @return true
*/
public boolean isSingle() {
return mIsOnlyOneItem;
}
/**
* /ID
* @return ID
*/
public long getId() {
return mId;
}
/**
*
* @return
*/
public long getAlertDate() {
return mAlertDate;
}
/**
*
* @return
*/
public long getCreatedDate() {
return mCreatedDate;
}
/**
*
* @return truefalse
*/
public boolean hasAttachment() {
return mHasAttachment;
}
/**
*
* @return
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* ID
* @return ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* ID
* @return ID
*/
public long getParentId() {
return mParentId;
}
/**
*
* @return
*/
public int getNotesCount() {
return mNotesCount;
}
/**
* IDgetParentId()
* @return ID
*/
public long getFolderId () {
return mParentId;
}
/**
*
* @return
*/
public int getType() {
return mType;
}
/**
*
* @return
*/
public int getWidgetType() {
return mWidgetType;
}
/**
* ID
* @return ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
* /
* @return
*/
public String getSnippet() {
return mSnippet;
}
/**
*
* @return truemAlertDate > 0
*/
public boolean hasAlert() {
return (mAlertDate > 0);
}
/**
*
*
* @return true
*/
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
/**
*
* NoteItemData
* @param cursor
* @return
*/
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}
}

File diff suppressed because it is too large Load Diff

@ -30,58 +30,110 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
/**
*
* CursorAdapter
*/
public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter";
private Context mContext;
private Context mContext; // 上下文对象
// 存储选中状态的映射表key为位置索引value为是否选中
private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount;
private boolean mChoiceMode;
private int mNotesCount; // 笔记总数(不包括文件夹)
private boolean mChoiceMode; // 标记是否处于多选模式
/**
*
*/
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
public int widgetId; // 小部件的唯一标识ID
public int widgetType; // 小部件的类型如2x2、4x4等
};
/**
*
* @param context
*/
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
super(context, null); // 调用父类构造函数初始游标为null
mSelectedIndex = new HashMap<Integer, Boolean>(); // 初始化选中状态记录表
mContext = context;
mNotesCount = 0;
mNotesCount = 0; // 初始笔记数量为0
}
/**
*
* @param context
* @param cursor
* @param parent
* @return
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// 创建自定义的笔记列表项视图
return new NotesListItem(context);
}
/**
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
// 检查视图类型是否正确
if (view instanceof NotesListItem) {
// 从游标数据创建笔记数据对象
NoteItemData itemData = new NoteItemData(context, cursor);
// 将数据绑定到列表项,并传递多选状态信息
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
}
}
/**
*
* @param position
* @param checked truefalse
*/
public void setCheckedItem(final int position, final boolean checked) {
// 更新选中状态映射表
mSelectedIndex.put(position, checked);
// 通知数据发生变化,需要刷新列表显示
notifyDataSetChanged();
}
/**
*
* @return truefalse
*/
public boolean isInChoiceMode() {
return mChoiceMode;
}
/**
*
* @param mode truefalse退
*/
public void setChoiceMode(boolean mode) {
// 清空所有选中状态记录
mSelectedIndex.clear();
mChoiceMode = mode;
}
/**
*
* @param checked truefalse
*/
public void selectAll(boolean checked) {
// 获取当前数据游标
Cursor cursor = getCursor();
// 遍历所有列表项
for (int i = 0; i < getCount(); i++) {
// 将游标移动到指定位置
if (cursor.moveToPosition(i)) {
// 只对笔记类型进行选中操作,跳过文件夹
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked);
}
@ -89,14 +141,24 @@ public class NotesListAdapter extends CursorAdapter {
}
}
/**
* ID
* @return ID
*/
public HashSet<Long> getSelectedItemIds() {
// 创建ID集合
HashSet<Long> itemSet = new HashSet<Long>();
// 遍历所有记录的位置
for (Integer position : mSelectedIndex.keySet()) {
// 检查该位置是否被选中
if (mSelectedIndex.get(position) == true) {
// 获取该项的笔记ID
Long id = getItemId(position);
// 安全检查确保不是根文件夹的ID
if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen");
} else {
// 将有效ID添加到集合中
itemSet.add(id);
}
}
@ -105,19 +167,30 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
/**
*
* @return
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() {
// 创建小部件属性集合
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
// 遍历所有选中项
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
// 获取对应位置的数据游标
Cursor c = (Cursor) getItem(position);
if (c != null) {
// 创建小部件属性对象
AppWidgetAttribute widget = new AppWidgetAttribute();
// 从游标数据创建笔记对象
NoteItemData item = new NoteItemData(mContext, c);
// 设置小部件属性
widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType();
itemSet.add(widget);
/**
* Don't close cursor here, only the adapter could close it
*
*
*/
} else {
Log.e(TAG, "Invalid cursor");
@ -128,14 +201,21 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
/**
*
* @return
*/
public int getSelectedCount() {
// 获取所有选中状态值
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
return 0;
}
// 使用迭代器遍历统计选中数量
Iterator<Boolean> iter = values.iterator();
int count = 0;
while (iter.hasNext()) {
// 如果状态为true计数加1
if (true == iter.next()) {
count++;
}
@ -143,37 +223,65 @@ public class NotesListAdapter extends CursorAdapter {
return count;
}
/**
*
* @return truefalse
*/
public boolean isAllSelected() {
// 获取当前选中数量
int checkedCount = getSelectedCount();
// 全选条件选中数量等于笔记总数且不为0
return (checkedCount != 0 && checkedCount == mNotesCount);
}
/**
*
* @param position
* @return truefalse
*/
public boolean isSelectedItem(final int position) {
// 如果映射表中没有该位置的记录,说明未选中
if (null == mSelectedIndex.get(position)) {
return false;
}
return mSelectedIndex.get(position);
}
/**
*
*/
@Override
protected void onContentChanged() {
super.onContentChanged();
// 重新计算笔记数量
calcNotesCount();
}
/**
*
* @param cursor
*/
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
// 重新计算笔记数量
calcNotesCount();
}
/**
*
*
*/
private void calcNotesCount() {
mNotesCount = 0;
mNotesCount = 0; // 重置计数器
// 遍历所有列表项
for (int i = 0; i < getCount(); i++) {
// 获取指定位置的数据
Cursor c = (Cursor) getItem(i);
if (c != null) {
// 只统计笔记类型,排除文件夹
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++;
mNotesCount++; // 笔记数量加1
}
} else {
Log.e(TAG, "Invalid cursor");
@ -181,4 +289,4 @@ public class NotesListAdapter extends CursorAdapter {
}
}
}
}
}

@ -29,94 +29,143 @@ import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
/**
*
* LinearLayout
*/
public class NotesListItem extends LinearLayout {
private ImageView mAlert;
private TextView mTitle;
private TextView mTime;
private TextView mCallName;
private NoteItemData mItemData;
private CheckBox mCheckBox;
private ImageView mAlert; // 提醒图标(时钟或通话记录图标)
private TextView mTitle; // 标题/内容文本
private TextView mTime; // 修改时间文本
private TextView mCallName; // 通话记录联系人姓名
private NoteItemData mItemData; // 绑定的数据对象
private CheckBox mCheckBox; // 多选模式下的复选框
/**
*
* @param context
*/
public NotesListItem(Context context) {
super(context);
// 从布局文件加载视图
inflate(context, R.layout.note_item, this);
// 初始化各个子视图组件
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name);
// 使用系统预定义的checkbox ID
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
/**
* UI
* @param context
* @param data
* @param choiceMode
* @param checked
*/
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
// 处理多选模式下的复选框显示
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
// 多选模式且是笔记类型:显示复选框并设置选中状态
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
} else {
// 非多选模式或文件夹类型:隐藏复选框
mCheckBox.setVisibility(View.GONE);
}
// 保存数据引用
mItemData = data;
// 根据数据类型显示不同的UI布局
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
// 通话记录文件夹的特殊显示
mCallName.setVisibility(View.GONE); // 隐藏联系人姓名
mAlert.setVisibility(View.VISIBLE); // 显示图标
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 设置主文本样式
// 设置文件夹名称和文件数量显示
mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record);
mAlert.setImageResource(R.drawable.call_record); // 设置通话记录图标
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
// 通话记录笔记的特殊显示
mCallName.setVisibility(View.VISIBLE); // 显示联系人姓名
mCallName.setText(data.getCallName()); // 设置联系人姓名
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); // 设置次文本样式
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 设置格式化后的内容摘要
// 根据是否有提醒设置提醒图标
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setImageResource(R.drawable.clock); // 时钟图标
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
} else {
mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
// 普通笔记或文件夹的显示
mCallName.setVisibility(View.GONE); // 隐藏联系人姓名
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 设置主文本样式
if (data.getType() == Notes.TYPE_FOLDER) {
// 文件夹显示:名称 + 文件数量
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));
mAlert.setVisibility(View.GONE);
data.getNotesCount()));
mAlert.setVisibility(View.GONE); // 文件夹不显示提醒图标
} else {
// 普通笔记显示:内容摘要
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
// 根据是否有提醒设置提醒图标
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setImageResource(R.drawable.clock); // 时钟图标
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
}
}
// 设置相对时间显示(如"2分钟前"、"昨天"等)
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 根据位置和类型设置背景
setBackground(data);
}
/**
*
*
* @param data
*/
private void setBackground(NoteItemData data) {
int id = data.getBgColorId();
int id = data.getBgColorId(); // 获取背景颜色ID
if (data.getType() == Notes.TYPE_NOTE) {
// 笔记类型的背景设置
if (data.isSingle() || data.isOneFollowingFolder()) {
// 单个笔记或紧跟在文件夹后的单个笔记:单一样式背景
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) {
// 列表中的最后一个笔记:底部样式背景
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
// 列表中的第一个笔记或多个紧跟在文件夹后的笔记:顶部样式背景
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else {
// 中间位置的笔记:普通样式背景
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
}
} else {
// 文件夹类型的背景:统一使用文件夹背景
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
/**
*
* @return NoteItemData
*/
public NoteItemData getItemData() {
return mItemData;
}
}
}

@ -47,55 +47,67 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
/**
*
* PreferenceActivityGoogle
*/
public class NotesPreferenceActivity extends PreferenceActivity {
// 偏好设置文件名
public static final String PREFERENCE_NAME = "notes_preferences";
// 同步账户名称的键
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
// 最后同步时间的键
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
// 背景颜色设置的键
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
// 同步账户分类的键
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
// 账户权限过滤器键
private static final String AUTHORITIES_FILTER_KEY = "authorities";
private PreferenceCategory mAccountCategory;
private GTaskReceiver mReceiver;
private Account[] mOriAccounts;
private boolean mHasAddedAccount;
private PreferenceCategory mAccountCategory; // 账户设置分类
private GTaskReceiver mReceiver; // 同步服务广播接收器
private Account[] mOriAccounts; // 原始账户列表
private boolean mHasAddedAccount; // 标记是否添加了新账户
/**
* Activity
*/
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* using the app icon for navigation */
// 在ActionBar中显示返回按钮
getActionBar().setDisplayHomeAsUpEnabled(true);
// 从XML资源加载偏好设置
addPreferencesFromResource(R.xml.preferences);
// 查找账户设置分类
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
// 创建广播接收器监听同步状态变化
mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter);
mOriAccounts = null;
// 加载设置页面的自定义头部布局
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true);
}
/**
* Activity
*/
@Override
protected void onResume() {
super.onResume();
// need to set sync account automatically if user has added a new
// account
// 如果用户添加了新账户,自动设置同步账户
if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts();
// 比较新旧账户列表,找到新添加的账户
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
for (Account accountNew : accounts) {
boolean found = false;
@ -106,6 +118,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
if (!found) {
// 设置新账户为同步账户
setSyncAccount(accountNew.name);
break;
}
@ -113,9 +126,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
// 刷新界面显示
refreshUI();
}
/**
* Activity
*/
@Override
protected void onDestroy() {
if (mReceiver != null) {
@ -124,8 +141,11 @@ public class NotesPreferenceActivity extends PreferenceActivity {
super.onDestroy();
}
/**
*
*/
private void loadAccountPreference() {
mAccountCategory.removeAll();
mAccountCategory.removeAll(); // 清空现有设置项
Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this);
@ -133,18 +153,18 @@ public class NotesPreferenceActivity extends PreferenceActivity {
accountPref.setSummary(getString(R.string.preferences_account_summary));
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
// 检查是否正在同步,同步过程中不允许修改账户
if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account
// 首次设置账户,显示选择账户对话框
showSelectAccountAlertDialog();
} else {
// if the account has already been set, we need to promp
// user about the risk
// 已设置过账户,显示确认对话框
showChangeAccountConfirmAlertDialog();
}
} else {
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
}
return true;
@ -154,11 +174,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mAccountCategory.addPreference(accountPref);
}
/**
*
*/
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state
// 根据同步状态设置按钮文本和点击事件
if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
@ -174,33 +197,44 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
});
}
// 只有设置了同步账户才能启用同步按钮
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time
// 设置最后同步时间显示
if (GTaskSyncService.isSyncing()) {
// 显示同步进度
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) {
// 格式化显示最后同步时间
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime)));
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
// 从未同步过,隐藏时间显示
lastSyncTimeView.setVisibility(View.GONE);
}
}
}
/**
*
*/
private void refreshUI() {
loadAccountPreference();
loadSyncButton();
}
/**
*
*/
private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 设置自定义标题布局
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
@ -208,45 +242,49 @@ public class NotesPreferenceActivity extends PreferenceActivity {
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null);
dialogBuilder.setPositiveButton(null, null); // 不显示确定按钮
Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this);
mOriAccounts = accounts;
mHasAddedAccount = false;
mOriAccounts = accounts; // 保存当前账户列表
mHasAddedAccount = false; // 重置添加账户标记
if (accounts.length > 0) {
// 创建账户选择列表
CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items;
int checkedItem = -1;
int index = 0;
for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index;
checkedItem = index; // 标记当前选中的账户
}
items[index++] = account.name;
}
dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// 用户选择账户后设置同步账户
setSyncAccount(itemMapping[which].toString());
dialog.dismiss();
refreshUI();
refreshUI(); // 刷新界面
}
});
}
// 添加"添加账户"选项
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView);
final AlertDialog dialog = dialogBuilder.show();
addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mHasAddedAccount = true;
mHasAddedAccount = true; // 标记正在添加账户
// 启动系统添加账户界面
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls"
"gmail-ls" // 限制只显示Gmail账户
});
startActivityForResult(intent, -1);
dialog.dismiss();
@ -254,17 +292,21 @@ public class NotesPreferenceActivity extends PreferenceActivity {
});
}
/**
*
*/
private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this)));
getSyncAccountName(this))); // 显示当前账户名
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView);
// 提供三个操作选项:更改账户、移除账户、取消
CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account),
@ -273,22 +315,32 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
// 更改账户
showSelectAccountAlertDialog();
} else if (which == 1) {
// 移除账户
removeSyncAccount();
refreshUI();
}
// which == 2 取消操作,不做任何事
}
});
dialogBuilder.show();
}
/**
* Google
*/
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
return accountManager.getAccountsByType("com.google"); // Google账户类型
}
/**
*
*/
private void setSyncAccount(String account) {
// 只有当账户发生变化时才更新
if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
@ -299,15 +351,15 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
editor.commit();
// clean up last sync time
// 重置最后同步时间
setLastSyncTime(this, 0);
// clean up local gtask related info
// 在新线程中清理本地同步信息
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
values.put(NoteColumns.GTASK_ID, ""); // 清空任务ID
values.put(NoteColumns.SYNC_ID, 0); // 重置同步ID
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
@ -318,9 +370,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
/**
*
*/
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
// 移除账户相关设置
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
}
@ -329,7 +385,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
editor.commit();
// clean up local gtask related info
// 在新线程中清理本地同步信息
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
@ -340,12 +396,18 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}).start();
}
/**
*
*/
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
/**
*
*/
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
@ -354,29 +416,38 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.commit();
}
/**
*
*/
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
/**
* 广
*/
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshUI();
refreshUI(); // 收到广播后刷新界面
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
// 更新同步进度显示
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
}
}
}
/**
*
*/
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// 点击返回按钮,返回到笔记列表
Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
@ -385,4 +456,4 @@ public class NotesPreferenceActivity extends PreferenceActivity {
return false;
}
}
}
}

@ -15,6 +15,7 @@
*/
package net.micode.notes.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
@ -32,101 +33,181 @@ import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;
/**
* 便
* 便
*
*/
public abstract class NoteWidgetProvider extends AppWidgetProvider {
/**
* -
*/
public static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET
NoteColumns.ID, // 便签ID
NoteColumns.BG_COLOR_ID, // 背景颜色ID
NoteColumns.SNIPPET // 便签内容摘要
};
public static final int COLUMN_ID = 0;
public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_SNIPPET = 2;
/**
*
*/
public static final int COLUMN_ID = 0; // ID列索引
public static final int COLUMN_BG_COLOR_ID = 1; // 背景颜色ID列索引
public static final int COLUMN_SNIPPET = 2; // 内容摘要列索引
/**
*
*/
private static final String TAG = "NoteWidgetProvider";
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
/**
*
*
*/
// 创建内容值用于清除小部件ID关联
ContentValues values = new ContentValues();
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
// 遍历所有被删除的小部件ID
for (int i = 0; i < appWidgetIds.length; i++) {
// 更新数据库将对应的小部件ID设为无效值
context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
values,
NoteColumns.WIDGET_ID + "=?",
NoteColumns.WIDGET_ID + "=?", // 条件小部件ID匹配
new String[] { String.valueOf(appWidgetIds[i])});
}
}
/**
* 便
* @param context
* @param widgetId ID
* @return 便Cursor
*/
private Cursor getNoteWidgetInfo(Context context, int widgetId) {
/**
* 便
* ID
*/
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
PROJECTION, // 查询的列
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", // 查询条件
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
null);
null); // 排序方式(无)
}
/**
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用私有更新方法,默认非隐私模式
update(context, appWidgetManager, appWidgetIds, false);
}
/**
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
* @param privacyMode true:false:便
*/
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) {
boolean privacyMode) {
// 遍历所有需要更新的小部件
for (int i = 0; i < appWidgetIds.length; i++) {
// 检查小部件ID是否有效
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
// 初始化默认背景颜色和内容摘要
int bgId = ResourceParser.getDefaultBgId(context);
String snippet = "";
// 创建点击小部件时启动的Intent指向便签编辑页面
Intent intent = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // 单例模式
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); // 传递小部件ID
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); // 传递小部件类型
// 查询数据库获取小部件关联的便签信息
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
if (c != null && c.moveToFirst()) {
// 安全检查:确保一个小部件只关联一个便签
if (c.getCount() > 1) {
Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
c.close();
return;
return; // 发现数据异常,直接返回
}
snippet = c.getString(COLUMN_SNIPPET);
bgId = c.getInt(COLUMN_BG_COLOR_ID);
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
intent.setAction(Intent.ACTION_VIEW);
// 从数据库读取便签信息
snippet = c.getString(COLUMN_SNIPPET); // 获取内容摘要
bgId = c.getInt(COLUMN_BG_COLOR_ID); // 获取背景颜色ID
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); // 传递便签ID
intent.setAction(Intent.ACTION_VIEW); // 设置为查看动作
} else {
// 没有找到关联的便签,显示默认内容
snippet = context.getResources().getString(R.string.widget_havenot_content);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 设置为新建/编辑动作
}
// 关闭Cursor释放资源
if (c != null) {
c.close();
}
// 创建RemoteViews对象用于更新小部件界面
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
// 设置小部件背景图片
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); // 传递背景颜色ID
/**
* Generate the pending intent to start host for the widget
* 宿ActivityPendingIntent
*
*/
PendingIntent pendingIntent = null;
if (privacyMode) {
// 隐私模式:显示保护文本,点击进入主列表页面
rv.setTextViewText(R.id.widget_text,
context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
} else {
// 正常模式:显示便签内容,点击进入编辑页面
rv.setTextViewText(R.id.widget_text, snippet);
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
// 设置小部件文本的点击事件
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
// 更新小部件显示
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
}
}
/**
* IDID
*
* @param bgId ID
* @return ID
*/
protected abstract int getBgResourceId(int bgId);
/**
* ID
*
* @return ID
*/
protected abstract int getLayoutId();
/**
*
*
* @return
*/
protected abstract int getWidgetType();
}
}

@ -23,25 +23,65 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
/**
* 2x2便
* NoteWidgetProvider2x2
* 2x2便
*/
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
/**
*
*
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用父类的通用更新逻辑,避免重复代码
// 父类已经实现了数据查询、界面更新等通用功能
super.update(context, appWidgetManager, appWidgetIds);
}
/**
* ID
* 2x2
*
* @return 2x2ID
*/
@Override
protected int getLayoutId() {
// 返回2x2尺寸小部件的布局文件
// R.layout.widget_2x 定义了2x2小部件的界面结构
return R.layout.widget_2x;
}
/**
* ID2x2ID
* 2x2
*
* @param bgId IDNotes.COLOR_YELLOW, Notes.COLOR_BLUE
* @return 2x2ID
*/
@Override
protected int getBgResourceId(int bgId) {
// 通过资源解析器获取2x2尺寸专用的背景图片
// 不同的颜色ID对应不同的背景图片资源
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
}
/**
*
* 2x2
*
* @return 2x2
*/
@Override
protected int getWidgetType() {
// 返回2x2小部件的类型常量用于区分不同尺寸的小部件
// 在数据存储和Intent传递中标识这是2x2尺寸的小部件
return Notes.TYPE_WIDGET_2X;
}
}
}

@ -23,24 +23,69 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
/**
* 4x4便
* NoteWidgetProvider4x4
* 4x4便
*/
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
/**
*
*
* 4x4使2x2
*
* @param context 访
* @param appWidgetManager
* @param appWidgetIds ID
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 直接调用父类的通用更新逻辑,避免代码重复
// 父类已实现数据查询、界面绑定、点击事件等完整的小部件更新流程
super.update(context, appWidgetManager, appWidgetIds);
}
/**
* 4x4ID
* 4x4
* 4x42x2
*
* @return 4x4IDR.layout.widget_4x
*/
@Override
protected int getLayoutId() {
// 返回4x4尺寸专用的布局文件
// 该布局针对4x4网格进行了优化可能包含更大的文本区域或额外的显示元素
return R.layout.widget_4x;
}
/**
* ID4x4ID
* 4x4
* 4x42x2
*
* @param bgId IDNotes.COLOR_YELLOW, Notes.COLOR_BLUE
* @return 4x4ID
*/
@Override
protected int getBgResourceId(int bgId) {
// 通过资源解析器获取4x4尺寸专用的背景图片资源
// ResourceParser.WidgetBgResources.getWidget4xBgResource()专门处理4x4尺寸的背景映射
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
}
/**
*
* 4x4
* Intent
*
* @return 4x4Notes.TYPE_WIDGET_4X
*/
@Override
protected int getWidgetType() {
// 返回4x4小部件的类型常量
// 这个值会存储在数据库中,用于关联便签数据和小部件实例
return Notes.TYPE_WIDGET_4X;
}
}
}
Loading…
Cancel
Save