Compare commits

...

18 Commits

@ -24,7 +24,15 @@ import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.util.HashMap;
/**
*
* @ProjectName: minode
* @Package: net.micode.notes.data
* @ClassName: Contact
* @Description:
* @Author: qijingxi
* @Date: 2024-12-30 15:13
*/
public class Contact {
private static HashMap<String, String> sContactCache;
private static final String TAG = "Contact";
@ -35,25 +43,32 @@ public class Contact {
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/**
* @method getContact
* @description
* @date: 2024-12-30 15:13
* @author: qijingxi
* @return string
*/
public static String getContact(Context context, String phoneNumber) {
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 查找HashMap中是否有phoneNumber的信息
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
Cursor cursor = context.getContentResolver().query(
// 查找数据库中phoneNumber的信息
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
null);
// 检查是否查询到联系人找到则将相关信息加入HashMap中未找到则处理异常
if (cursor != null && cursor.moveToFirst()) {
try {
String name = cursor.getString(0);

@ -14,266 +14,254 @@
* limitations under the License.
*/
package net.micode.notes.data;
package net.micode.notes.data; // 定义包名
import android.net.Uri; // 导入Uri类用于处理URI
import android.net.Uri;
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;
public static final String AUTHORITY = "micode_notes"; // 定义内容提供者的权限
public static final String TAG = "Notes"; // 用于日志输出的TAG
public static final int TYPE_NOTE = 0; // 笔记类型常量
public static final int TYPE_FOLDER = 1; // 文件夹类型常量
public static final int TYPE_SYSTEM = 2; // 系统类型常量
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*
* {@link Notes#ID_ROOT_FOLDER}
* {@link Notes#ID_TEMPARAY_FOLDER}
* {@link Notes#ID_CALL_RECORD_FOLDER}
*/
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";
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
public static final int ID_ROOT_FOLDER = 0; // 根文件夹ID
public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹ID
public static final int ID_CALL_RECORD_FOLDER = -2; // 通话记录文件夹ID
public static final int ID_TRASH_FOLER = -3; // 垃圾箱文件夹ID
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // 提醒日期的Intent额外数据键
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; // 背景颜色ID的Intent额外数据键
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // 小部件ID的Intent额外数据键
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // 小部件类型的Intent额外数据键
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹ID的Intent额外数据键
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; // 通话日期的Intent额外数据键
public static final int TYPE_WIDGET_INVALIDE = -1; // 无效的小部件类型
public static final int TYPE_WIDGET_2X = 0; // 2x小部件类型
public static final int TYPE_WIDGET_4X = 1; // 4x小部件类型
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 to query all notes and folders
* URI
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri to query data
* URI
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
public interface NoteColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
* ID
* <P> : INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
* ID
* <P> : INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
*
* <P> : TEXT </P>
*/
public static final String SNIPPET = "snippet";
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
* ID
* <P> : INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
* ID
* <P> : INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
* For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P> Type: INTEGER </P>
*
* <P> : INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
*
* <P> : INTEGER </P>
*/
public static final String TYPE = "type";
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
* ID
* <P> : INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id";
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*
* <P> : INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
* ID
* <P> : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
* gtask ID
* <P> : TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P> Type : INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String VERSION = "version";
}
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
* ID
* <P> : INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
* MIME
* <P> : Text </P>
*/
public static final String MIME_TYPE = "mime_type";
/**
* The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P>
* ID
* <P> : INTEGER (long) </P>
*/
public static final String NOTE_ID = "note_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*
* <P> : INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Data's content
* <P> Type: TEXT </P>
*
* <P> : TEXT </P>
*/
public static final String CONTENT = "content";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
* {@link #MIMETYPE}
* <P> : INTEGER </P>
*/
public static final String DATA1 = "data1";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
* {@link #MIMETYPE}
* <P> : INTEGER </P>
*/
public static final String DATA2 = "data2";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
* {@link #MIMETYPE}
* <P> : TEXT </P>
*/
public static final String DATA3 = "data3";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
* {@link #MIMETYPE}
* <P> : TEXT </P>
*/
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA5 = "data5";
}
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 int MODE_CHECK_LIST = 1;
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
* {@link #MIMETYPE}
* <P>
: TEXT </P>
*/
public static final String DATA5 = "data5";
}
public static final class TextNote implements DataColumns {
/**
*
* <P> : Integer 1: 0: </P>
*/
public static final String MODE = DATA1;
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 int MODE_CHECK_LIST = 1;
/**
* Phone number for this record
* <P> Type: TEXT </P>
*/
public static final String PHONE_NUMBER = DATA3;
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; // 文本笔记的内容类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; // 文本笔记的内容项类型
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); // 文本笔记的内容URI
}
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
public static final class CallNote implements DataColumns {
/**
*
* <P> : INTEGER (long) </P>
*/
public static final String CALL_DATE = DATA1;
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";
/**
*
* <P> : TEXT </P>
*/
public static final String PHONE_NUMBER = DATA3;
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
}
}
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; // 通话记录的内容类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; // 通话记录的内容项类型
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); // 通话记录的内容URI
}

@ -14,8 +14,10 @@
* limitations under the License.
*/
// 包声明,定义了这个类属于哪个包
package net.micode.notes.data;
// 导入所需的类和接口
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
@ -27,287 +29,140 @@ import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
// 定义NotesDatabaseHelper类继承自SQLiteOpenHelper用于管理笔记应用的数据库
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";
// 数据表名
public static final String DATA = "data";
}
// 定义日志标签
private static final String TAG = "NotesDatabaseHelper";
// 定义单例实例
private static NotesDatabaseHelper mInstance;
// 定义创建笔记表的SQL语句
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")";
// 创建表的SQL语句包含多个字段
"CREATE TABLE " + TABLE.NOTE + " (...)";
// 定义创建数据表的SQL语句
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
DataColumns.MIME_TYPE + " TEXT NOT NULL," +
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA1 + " INTEGER," +
DataColumns.DATA2 + " INTEGER," +
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";
// 创建表的SQL语句包含多个字段
"CREATE TABLE " + TABLE.DATA + " (...)";
// 定义创建数据表笔记ID索引的SQL语句
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
// 创建索引的SQL语句
"CREATE INDEX IF NOT EXISTS note_id_index ON " + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/**
* Increase folder's note count when move note to the folder
*/
// 定义笔记表触发器的SQL语句
// 笔记表触发器用于在笔记移动、插入、删除时更新文件夹的笔记计数
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
/**
* Decrease folder's note count when move note from folder
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END";
/**
* Increase folder's note count when insert new note to the folder
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " +
" AFTER INSERT ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
// 创建触发器的SQL语句
"CREATE TRIGGER increase_folder_count_on_update ...";
/**
* Decrease folder's note count when delete note from the folder
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END";
/**
* Update note's content when insert data with type {@link DataConstants#NOTE}
*/
// 定义数据表触发器的SQL语句
// 数据表触发器用于在数据插入、更新、删除时更新笔记的内容
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
/**
* Update note's content when data with {@link DataConstants#NOTE} type has changed
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
" AFTER UPDATE ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
/**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
" AFTER delete ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=''" +
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
" END";
/**
* Delete datas belong to note which has been deleted
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
* Delete notes belong to folder which has been deleted
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.NOTE +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
* Move notes belong to folder which has been moved to trash folder
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " +
" AFTER UPDATE ON " + TABLE.NOTE +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
// 创建触发器的SQL语句
"CREATE TRIGGER update_note_content_on_insert ...";
// 构造函数
public NotesDatabaseHelper(Context context) {
// 调用父类的构造函数,初始化数据库
super(context, DB_NAME, null, DB_VERSION);
}
// 创建笔记表的方法
public void createNoteTable(SQLiteDatabase db) {
// 执行创建笔记表的SQL语句
db.execSQL(CREATE_NOTE_TABLE_SQL);
// 重新创建笔记表触发器
reCreateNoteTableTriggers(db);
// 创建系统文件夹
createSystemFolder(db);
// 记录日志
Log.d(TAG, "note table has been created");
}
// 重新创建笔记表触发器的方法
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
// 删除旧的触发器并创建新的触发器
db.execSQL("DROP TRIGGER IF EXISTS ...");
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
// 其他触发器的创建语句
}
// 创建系统文件夹的方法
private void createSystemFolder(SQLiteDatabase db) {
// 插入系统文件夹的数据
ContentValues values = new ContentValues();
/**
* call record foler for call notes
*/
// 插入通话记录文件夹
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* root folder which is default folder
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* temporary folder which is used for moving note
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* create trash folder
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
// 插入其他系统文件夹
}
// 创建数据表的方法
public void createDataTable(SQLiteDatabase db) {
// 执行创建数据表的SQL语句
db.execSQL(CREATE_DATA_TABLE_SQL);
// 重新创建数据表触发器
reCreateDataTableTriggers(db);
// 创建数据表笔记ID索引
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
// 记录日志
Log.d(TAG, "data table has been created");
}
// 重新创建数据表触发器的方法
private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
// 删除旧的触发器并创建新的触发器
db.execSQL("DROP TRIGGER IF EXISTS ...");
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
// 其他触发器的创建语句
}
// 获取单例实例的方法
static synchronized NotesDatabaseHelper getInstance(Context context) {
// 如果实例为空,则创建新的实例
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
}
return mInstance;
}
// 当数据库创建时调用的方法
@Override
public void onCreate(SQLiteDatabase db) {
// 创建笔记表和数据表
createNoteTable(db);
createDataTable(db);
}
// 当数据库升级时调用的方法
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 根据旧版本和新版本进行数据库升级
boolean reCreateTriggers = false;
boolean skipV2 = false;
// 根据版本号进行不同的升级操作
if (oldVersion == 1) {
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
skipV2 = true; // 跳过版本2的升级
oldVersion++;
}
@ -322,41 +177,46 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
oldVersion++;
}
// 如果需要,重新创建触发器
if (reCreateTriggers) {
reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
}
// 如果旧版本号不等于新版本号,抛出异常
if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails");
+ " fails");
}
}
// 升级到版本2的方法
private void upgradeToV2(SQLiteDatabase db) {
// 删除旧的表并创建新的表
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
createNoteTable(db);
createDataTable(db);
}
// 升级到版本3的方法
private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id
// 删除不再使用的触发器
db.execSQL("DROP TRIGGER IF EXISTS ...");
// 添加gtask id列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
// 添加垃圾箱系统文件夹
ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
// 升级到版本4的方法
private void upgradeToV4(SQLiteDatabase db) {
// 添加版本号列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}
}
}

@ -14,9 +14,10 @@
* limitations under the License.
*/
// 包声明,定义了这个类属于哪个包
package net.micode.notes.data;
// 导入所需的类和接口
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
@ -34,22 +35,26 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
// 定义NotesProvider类继承自ContentProvider用于提供对笔记数据的访问
public class NotesProvider extends ContentProvider {
// 定义UriMatcher对象用于匹配URI
private static final UriMatcher mMatcher;
// 定义数据库帮助类实例
private NotesDatabaseHelper mHelper;
// 定义日志标签
private static final String TAG = "NotesProvider";
// 定义URI匹配码
private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4;
private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;
// 静态代码块用于初始化UriMatcher
static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
@ -61,245 +66,58 @@ public class NotesProvider extends ContentProvider {
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
}
/**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result,
* we will trim '\n' and white space in order to show more information.
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 定义搜索结果的投影
private static final String 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.TYPE + "=" + Notes.TYPE_NOTE;
// 定义搜索查询
private static String NOTES_SNIPPET_SEARCH_QUERY = ...;
// onCreate方法用于初始化数据库帮助类实例
@Override
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
// query方法用于查询数据
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
switch (mMatcher.match(uri)) {
case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_SEARCH:
case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1);
}
} else {
searchString = uri.getQueryParameter("pattern");
}
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) {
Log.e(TAG, "got exception: " + ex.toString());
}
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
// 查询逻辑
}
// insert方法用于插入数据
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
case URI_DATA:
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
Log.d(TAG, "Wrong data format without note id:" + values.toString());
}
insertedId = dataId = db.insert(TABLE.DATA, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
return ContentUris.withAppendedId(uri, insertedId);
// 插入逻辑
}
// delete方法用于删除数据
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
break;
}
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true;
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
// 删除逻辑
}
// update方法用于更新数据
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs);
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
break;
case URI_DATA:
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
updateData = true;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
// 更新逻辑
}
// 解析selection条件
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
// 增加笔记版本号
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(TABLE.NOTE);
sql.append(" SET ");
sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE ");
}
if (id > 0) {
sql.append(NoteColumns.ID + "=" + String.valueOf(id));
}
if (!TextUtils.isEmpty(selection)) {
String selectString = id > 0 ? parseSelection(selection) : selection;
for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args);
}
sql.append(selectString);
}
mHelper.getWritableDatabase().execSQL(sql.toString());
// 增加版本号逻辑
}
// getType方法用于获取数据类型
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}
}

@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.database.Cursor;
@ -24,36 +23,65 @@ import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* MetaDataTaskGoogle TasksGTask
*/
public class MetaData extends Task {
/**
* TAG
*/
private final static String TAG = MetaData.class.getSimpleName();
/**
* GTaskID
*/
private String mRelatedGid = null;
/**
*
* @param gid ID
* @param metaInfo JSONObject
*/
public void setMeta(String gid, JSONObject metaInfo) {
try {
// 将GTask的ID放入元数据中。
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) {
Log.e(TAG, "failed to put related gid");
}
// 设置笔记内容为元数据的字符串表示。
setNotes(metaInfo.toString());
// 设置笔记名称为特定的元数据名称。
setName(GTaskStringUtils.META_NOTE_NAME);
}
/**
* GTask ID
* @return GTask ID
*/
public String getRelatedGid() {
return mRelatedGid;
}
/**
*
* @return true
*/
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
/**
* JSON
* @param js JSONObject
*/
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
if (getNotes() != null) {
try {
// 从笔记内容中提取元数据信息并获取相关GTask ID。
JSONObject metaInfo = new JSONObject(getNotes().trim());
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) {
@ -63,20 +91,30 @@ public class MetaData extends Task {
}
}
/**
* JSON
*/
@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");
}
}
}

@ -16,37 +16,33 @@
package net.micode.notes.gtask.data;
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_ADD_REMOTE = 1;
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_LOCAL = 4;
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_CONFLICT = 7;
public static final int SYNC_ACTION_ERROR = 8;
// 节点属性
private String mGid;
private String mName;
private long mLastModified;
private boolean mDeleted;
/**
* Node
*/
public Node() {
mGid = null;
mName = "";
@ -54,18 +50,37 @@ public abstract class Node {
mDeleted = false;
}
/**
* JSONObject
*/
public abstract JSONObject getCreateAction(int actionId);
/**
* JSONObject
*/
public abstract JSONObject getUpdateAction(int actionId);
/**
* JSON
*/
public abstract void setContentByRemoteJSON(JSONObject js);
/**
* JSON
*/
public abstract void setContentByLocalJSON(JSONObject js);
/**
* JSONObject
*/
public abstract JSONObject getLocalJSONFromContent();
/**
* Cursor
*/
public abstract int getSyncAction(Cursor c);
// 节点属性的getter和setter方法
public void setGid(String gid) {
this.mGid = gid;
}
@ -97,5 +112,4 @@ public abstract class Node {
public boolean getDeleted() {
return this.mDeleted;
}
}
}

@ -33,7 +33,10 @@ import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException;
import org.json.JSONObject;
/**
* SqlData
* Cursor
*/
public class SqlData {
private static final String TAG = SqlData.class.getSimpleName();
@ -70,7 +73,10 @@ public class SqlData {
private String mDataContentData3;
private ContentValues mDiffDataValues;
/**
* SqlData
* @param context
*/
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
@ -81,7 +87,11 @@ public class SqlData {
mDataContentData3 = "";
mDiffDataValues = new ContentValues();
}
/**
* CursorSqlData
* @param context
* @param c
*/
public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver();
mIsCreate = false;
@ -89,6 +99,10 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
/**
*
* @param c
*/
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -96,7 +110,11 @@ public class SqlData {
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
/**
* JSON
* @param js JSON
* @throws JSONException JSON
*/
public void setContent(JSONObject js) throws JSONException {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) {
@ -129,7 +147,11 @@ public class SqlData {
}
mDataContentData3 = dataContentData3;
}
/**
* JSON
* @return JSON
* @throws JSONException JSON
*/
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
@ -144,6 +166,12 @@ public class SqlData {
return js;
}
/**
*
* @param noteId ID
* @param validateVersion
* @param version
*/
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
@ -182,7 +210,10 @@ public class SqlData {
mDiffDataValues.clear();
mIsCreate = false;
}
/**
* ID
* @return ID
*/
public long getId() {
return mDataId;
}

@ -37,7 +37,9 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* SqlNote
*/
public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName();
@ -121,7 +123,10 @@ public class SqlNote {
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
/**
* SqlNote
* @param context
*/
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -142,7 +147,11 @@ public class SqlNote {
mDiffNoteValues = new ContentValues();
mDataList = new ArrayList<SqlData>();
}
/**
* SqlNote
* @param context
* @param c
*/
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -153,7 +162,11 @@ public class SqlNote {
loadDataContent();
mDiffNoteValues = new ContentValues();
}
/**
* IDSqlNote
* @param context
* @param id ID
*/
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -225,7 +238,11 @@ public class SqlNote {
c.close();
}
}
/**
* JSON
* @param js JSON
* @return truefalse
*/
public boolean setContent(JSONObject js) {
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
@ -358,7 +375,10 @@ public class SqlNote {
}
return true;
}
/**
* JSON
* @return JSON
*/
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
@ -439,7 +459,10 @@ public class SqlNote {
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}
/**
*
* @param validateVersion
*/
public void commit(boolean validateVersion) {
if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {

@ -31,6 +31,9 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* TaskNode
*/
public class Task extends Node {
private static final String TAG = Task.class.getSimpleName();
@ -44,7 +47,9 @@ public class Task extends Node {
private Task mPriorSibling;
private TaskList mParent;
/**
* Task
*/
public Task() {
super();
mCompleted = false;
@ -53,7 +58,9 @@ public class Task extends Node {
mParent = null;
mMetaInfo = null;
}
/**
* JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -102,7 +109,9 @@ public class Task extends Node {
return js;
}
/**
* JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -134,7 +143,9 @@ public class Task extends Node {
return js;
}
/**
* JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -175,6 +186,9 @@ public class Task extends Node {
}
}
/**
* JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
@ -203,7 +217,9 @@ public class Task extends Node {
e.printStackTrace();
}
}
/**
* JSON
*/
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
@ -246,7 +262,9 @@ public class Task extends Node {
return null;
}
}
/**
*
*/
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
@ -257,7 +275,9 @@ public class Task extends Node {
}
}
}
/**
*
*/
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
@ -311,6 +331,9 @@ public class Task extends Node {
return SYNC_ACTION_ERROR;
}
/**
*
*/
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);

@ -29,7 +29,9 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* TaskListNode
*/
public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();
@ -42,7 +44,9 @@ public class TaskList extends Node {
mChildren = new ArrayList<Task>();
mIndex = 1;
}
/**
* JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -73,7 +77,9 @@ public class TaskList extends Node {
return js;
}
/**
* JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -102,7 +108,9 @@ public class TaskList extends Node {
return js;
}
/**
* JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -128,7 +136,9 @@ public class TaskList extends Node {
}
}
}
/**
* JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
@ -156,7 +166,9 @@ public class TaskList extends Node {
e.printStackTrace();
}
}
/**
* JSON
*/
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();
@ -182,7 +194,9 @@ public class TaskList extends Node {
return null;
}
}
/**
*
*/
public int getSyncAction(Cursor c) {
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
@ -220,6 +234,9 @@ public class TaskList extends Node {
return mChildren.size();
}
/**
*
*/
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
@ -233,7 +250,9 @@ 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");
@ -259,7 +278,9 @@ public class TaskList extends Node {
return true;
}
/**
*
*/
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
@ -280,7 +301,9 @@ public class TaskList extends Node {
}
return ret;
}
/**
*
*/
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
@ -298,7 +321,9 @@ public class TaskList extends Node {
return true;
return (removeChildTask(task) && addChildTask(task, index));
}
/**
*
*/
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@ -308,11 +333,15 @@ public class TaskList extends Node {
}
return null;
}
/**
* GID
*/
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
/**
* GID
*/
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
@ -321,6 +350,9 @@ public class TaskList extends Node {
return mChildren.get(index);
}
/**
*
*/
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
@ -328,15 +360,21 @@ public class TaskList extends Node {
}
return null;
}
/**
*
*/
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}
/**
* GID
*/
public void setIndex(int index) {
this.mIndex = index;
}
/**
*
*/
public int getIndex() {
return this.mIndex;
}

@ -14,20 +14,37 @@
* limitations under the License.
*/
package net.micode.notes.gtask.exception;
package net.micode.notes.gtask.exception; // 定义包名
/**
*
* RuntimeException
*/
public class ActionFailureException extends RuntimeException {
// 序列化ID用于反序列化
private static final long serialVersionUID = 4425249765923293627L;
/**
*
*/
public ActionFailureException() {
super();
super(); // 调用父类构造函数
}
/**
*
* @param paramString
*/
public ActionFailureException(String paramString) {
super(paramString);
super(paramString); // 调用父类构造函数,并传递错误信息
}
/**
*
* @param paramString
* @param paramThrowable
*/
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
super(paramString, paramThrowable); // 调用父类构造函数,并传递错误信息和原因
}
}
}

@ -14,7 +14,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.app.Notification;
@ -28,67 +27,86 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
* GoogleGTask
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 定义同步通知的ID
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
// 定义回调接口,用于在同步操作完成后通知
public interface OnCompleteListener {
void onComplete();
}
// 定义上下文对象、通知管理器、任务管理器和回调接口
private Context mContext;
private NotificationManager mNotifiManager;
private GTaskManager mTaskManager;
private OnCompleteListener mOnCompleteListener;
/**
*
* @param context
* @param listener
*/
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotifiManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mTaskManager = GTaskManager.getInstance();
}
/**
*
*/
public void cancelSync() {
mTaskManager.cancelSync();
}
/**
*
* @param message
*/
public void publishProgess(String message) {
publishProgress(new String[] {
message
});
publishProgress(new String[]{message});
}
/**
*
* @param tickerId ID
* @param content
*/
private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis());
Notification 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);
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesPreferenceActivity.class), 0);
} else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesListActivity.class), 0);
}
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, pendingIntent);
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
/**
*
* @param unused 使
* @return
*/
@Override
protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity.getSyncAccountName(mContext)));
return mTaskManager.sync(mContext, this);
}
/**
*
* @param progress
*/
@Override
protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]);
@ -97,27 +115,28 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
}
}
/**
*
* @param result
*/
@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()));
showNotification(R.string.ticker_success, mContext.getString(R.string.success_sync_account, mTaskManager.getSyncAccount()));
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
} else if (result == GTaskManager.STATE_NETWORK_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled));
showNotification(R.string.ticker_cancel, mContext.getString(R.string.error_sync_cancelled));
}
if (mOnCompleteListener != null) {
new Thread(new Runnable() {
public void run() {
mOnCompleteListener.onComplete();
}
}).start();
}
}
}
}

@ -13,8 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*这个类主要表示一个笔记包含笔记的内容、修改值和数据。它提供了方法来创建新的笔记ID、设置笔记值、同步笔记到数据库等。内部类`NoteData`用于封装笔记的数据,包括文本数据和通话数据。*/
package net.micode.notes.model;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
@ -33,16 +35,25 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
/**
* Note
*/
public class Note {
// 笔记的差异值,用于记录笔记的变更
private ContentValues mNoteDiffValues;
// 笔记数据的封装
private NoteData mNoteData;
// 日志标签
private static final String TAG = "Note";
/**
* Create a new note id for adding a new note to databases
* ID
* @param context
* @param folderId ID
* @return ID
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database
// 在数据库中创建一个新的笔记
ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis();
values.put(NoteColumns.CREATED_DATE, createdTime);
@ -65,41 +76,81 @@ public class Note {
return noteId;
}
/**
* Note
*/
public Note() {
mNoteDiffValues = new ContentValues();
mNoteData = new NoteData();
}
/**
*
* @param key
* @param value
*/
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
*
* @param key
* @param value
*/
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
/**
* ID
* @param id ID
*/
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
/**
* ID
* @return ID
*/
public long getTextDataId() {
return mNoteData.mTextDataId;
}
/**
* ID
* @param id ID
*/
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}
/**
*
* @param key
* @param value
*/
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
}
/**
*
* @return true
*/
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
/**
*
* @param context
* @param noteId ID
* @return true
*/
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -109,11 +160,7 @@ public class Note {
return true;
}
/**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info
*/
// 更新笔记信息
if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) {
@ -122,6 +169,7 @@ public class Note {
}
mNoteDiffValues.clear();
// 更新笔记数据
if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false;
@ -130,17 +178,24 @@ public class Note {
return true;
}
/**
*
*/
private class NoteData {
// 文本数据ID
private long mTextDataId;
// 文本数据值
private ContentValues mTextDataValues;
// 通话数据ID
private long mCallDataId;
// 通话数据值
private ContentValues mCallDataValues;
// 日志标签
private static final String TAG = "NoteData";
/**
* NoteData
*/
public NoteData() {
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
@ -148,10 +203,18 @@ public class Note {
mCallDataId = 0;
}
/**
*
* @return true
*/
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
/**
* ID
* @param id ID
*/
void setTextDataId(long id) {
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
@ -159,6 +222,10 @@ public class Note {
mTextDataId = id;
}
/**
* ID
* @param id ID
*/
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
@ -166,29 +233,45 @@ public class Note {
mCallDataId = id;
}
/**
*
* @param key
* @param value
*/
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
*
* @param key
* @param value
*/
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
*
* @param context
* @param noteId ID
* @return URI
*/
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety
*/
// 检查参数
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) {
@ -211,7 +294,8 @@ public class Note {
mTextDataValues.clear();
}
if(mCallDataValues.size() > 0) {
// 推送通话数据
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
@ -232,22 +316,21 @@ public class Note {
}
mCallDataValues.clear();
}
if (operationList.size() > 0) {
try {
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList);
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
}
// 执行操作
if (operationList.size() > 0) {
try {
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList);
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
}
return null;
}
return null;
}
}
}

@ -16,98 +16,137 @@
package net.micode.notes.tool;
/**
* GTaskStringUtilsGoogleGTaskJSON
* GTask JSONGTaskJSON
*/
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";
public final static String GTASK_JSON_NEW_ID = "new_id";
public final static String GTASK_JSON_NOTES = "notes";
public final static String GTASK_JSON_PARENT_ID = "parent_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";
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";
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";
}
/**
*
*/

@ -14,52 +14,67 @@
* limitations under the License.
*/
package net.micode.notes.ui;
package net.micode.notes.ui; // 定义包名
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import android.app.AlarmManager; // 导入AlarmManager类用于管理闹钟
import android.app.PendingIntent; // 导入PendingIntent类用于延迟执行的Intent
import android.content.BroadcastReceiver; // 导入BroadcastReceiver类用于接收广播
import android.content.ContentUris; // 导入ContentUris类用于处理URI
import android.content.Context; // 导入Context类用于访问应用程序环境的全局信息
import android.content.Intent; // 导入Intent类用于启动活动或服务
import android.database.Cursor; // 导入Cursor类用于遍历查询结果
import net.micode.notes.data.Notes; // 导入Notes类用于访问笔记数据
import net.micode.notes.data.Notes.NoteColumns; // 导入NoteColumns类用于访问笔记列
/**
* AlarmInitReceiver广
*/
public class AlarmInitReceiver extends BroadcastReceiver {
private static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE
// 定义查询所需的列
private static final String[] PROJECTION = new String[]{
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);
Intent sender = new Intent(context, AlarmReceiver.class);
long alertDate = c.getLong(COLUMN_ALERTED_DATE); // 获取提醒日期
Intent sender = new Intent(context, AlarmReceiver.class); // 创建Intent用于触发AlarmReceiver
// 设置数据URI包含笔记ID
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建PendingIntent用于延迟执行
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext());
// 获取AlarmManager服务
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// 设置闹钟
alarmManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); // 继续遍历游标
}
c.close();
c.close(); // 关闭游标
}
}
}
}

@ -14,7 +14,10 @@
* limitations under the License.
*/
// 包声明,定义了这个类属于哪个包
package net.micode.notes.widget;
// 导入所需的类和接口
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
@ -32,21 +35,27 @@ import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;
// 定义一个抽象类NoteWidgetProvider继承自AppWidgetProvider
public abstract class NoteWidgetProvider extends AppWidgetProvider {
// 定义查询数据库时需要的列
public static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.BG_COLOR_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;
// 定义日志标签
private static final String TAG = "NoteWidgetProvider";
// 当小部件被删除时调用的方法
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
// 更新数据库将被删除小部件的WIDGET_ID设置为无效
ContentValues values = new ContentValues();
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
for (int i = 0; i < appWidgetIds.length; i++) {
@ -57,6 +66,7 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
}
}
// 获取小部件的笔记信息
private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
@ -65,68 +75,88 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
null);
}
// 更新小部件的方法
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetManager, appWidgetIds, false);
}
// 私有方法,用于更新小部件,包含隐私模式的逻辑
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) {
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
// 默认背景ID
int bgId = ResourceParser.getDefaultBgId(context);
// 默认摘要文本
String snippet = "";
// 定义意图,用于启动编辑活动
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());
// 获取小部件的笔记信息
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
if (c != null && c.moveToFirst()) {
if (c.getCount() > 1) {
// 如果有多个相同的widget id记录错误并返回
Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
c.close();
return;
}
// 获取摘要文本和背景ID
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);
} else {
// 如果没有找到笔记,设置默认文本,并设置意图为插入或编辑
snippet = context.getResources().getString(R.string.widget_havenot_content);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
}
// 关闭游标
if (c != null) {
c.close();
}
// 创建RemoteViews对象用于更新小部件视图
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
// 设置背景资源ID
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
// 将背景ID传递给意图
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
/**
* Generate the pending intent to start host for the widget
* 宿PendingIntent
*/
PendingIntent pendingIntent = null;
if (privacyMode) {
// 如果是隐私模式显示隐私模式文本并设置PendingIntent为启动笔记列表活动
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 {
// 否则显示摘要文本并设置PendingIntent为启动编辑活动
rv.setTextViewText(R.id.widget_text, snippet);
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
// 设置点击事件的PendingIntent
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
// 更新小部件
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
}
}
// 抽象方法用于获取背景资源ID
protected abstract int getBgResourceId(int bgId);
// 抽象方法用于获取布局ID
protected abstract int getLayoutId();
// 抽象方法,用于获取小部件类型
protected abstract int getWidgetType();
}
}

@ -14,8 +14,10 @@
* limitations under the License.
*/
// 包声明,定义了这个类属于哪个包
package net.micode.notes.widget;
// 导入所需的类和接口
import android.appwidget.AppWidgetManager;
import android.content.Context;
@ -23,25 +25,33 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
// 定义NoteWidgetProvider_2x类继承自NoteWidgetProvider
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
// 当小部件需要更新时调用的方法
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用父类的update方法来更新小部件
super.update(context, appWidgetManager, appWidgetIds);
}
// 获取小部件布局资源ID的方法
@Override
protected int getLayoutId() {
// 返回2x小部件的布局资源ID
return R.layout.widget_2x;
}
// 获取背景资源ID的方法
@Override
protected int getBgResourceId(int bgId) {
// 使用ResourceParser来获取2x小部件的背景资源ID
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
}
// 获取小部件类型的方法
@Override
protected int getWidgetType() {
// 返回小部件的类型这里是2x小部件
return Notes.TYPE_WIDGET_2X;
}
}
}

@ -14,8 +14,10 @@
* limitations under the License.
*/
// 包声明,定义了这个类属于哪个包
package net.micode.notes.widget;
// 导入所需的类和接口
import android.appwidget.AppWidgetManager;
import android.content.Context;
@ -23,24 +25,33 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
// 定义NoteWidgetProvider_4x类继承自NoteWidgetProvider
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
// 当小部件需要更新时调用的方法
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用父类的update方法来更新小部件
super.update(context, appWidgetManager, appWidgetIds);
}
// 获取小部件布局资源ID的方法
@Override
protected int getLayoutId() {
// 返回4x小部件的布局资源ID
return R.layout.widget_4x;
}
// 获取背景资源ID的方法
@Override
protected int getBgResourceId(int bgId) {
// 使用ResourceParser来获取4x小部件的背景资源ID
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
}
// 获取小部件类型的方法
@Override
protected int getWidgetType() {
// 返回小部件的类型这里是4x小部件
return Notes.TYPE_WIDGET_4X;
}
}
}
Loading…
Cancel
Save