新增富文本编辑、隐私文件夹、专注模式功能

pull/17/head
ZxR 3 months ago
parent 5deef06d52
commit 8db6158fb4

@ -0,0 +1,41 @@
package net.micode.notes;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
/**
* Activity
*
* AppCompatActivity使AndroidX
*/
public class MainActivity extends AppCompatActivity {
/**
* Activity
* Activity
*
* @param savedInstanceState Activity
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 启用边缘到边缘显示允许内容延伸到系统UI区域状态栏和导航栏
EdgeToEdge.enable(this);
// 设置Activity的布局文件为activity_main.xml
setContentView(R.layout.activity_main);
// 设置窗口插入监听器处理系统UI区域如状态栏、导航栏与内容的交互
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
// 获取系统栏(状态栏和导航栏)的插入区域
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
// 为视图设置内边距,避免内容被系统栏遮挡
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
// 返回处理后的插入信息
return insets;
});
}
}

@ -14,60 +14,101 @@
* limitations under the License.
*/
package net.micode.notes.data;
package net.micode.notes.data; // 属于小米便签的数据层包,专门处理数据相关操作
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.content.Context; // Android上下文用于访问应用资源
import android.database.Cursor; // 数据库查询结果集,用于遍历查询结果
import android.provider.ContactsContract.CommonDataKinds.Phone; // 通讯录电话号码相关常量
import android.provider.ContactsContract.Data; // 通讯录数据相关常量
import android.telephony.PhoneNumberUtils; // 电话号码工具类,用于格式化比较号码
import android.util.Log; // Android日志工具
import java.util.HashMap;
import java.util.HashMap; // HashMap集合用于缓存联系人信息
/**
* Contact -
*
* 使
*
* 1. 使Android ContentProvider访
* 2. LRU
* 3. 使
*/
public class Contact {
// 静态联系人缓存使用HashMap存储<电话号码, 联系人姓名>键值对
// 使用静态变量实现应用级别的缓存,减少对通讯录的频繁访问
private static HashMap<String, String> sContactCache;
// 日志标签,用于调试和问题追踪
private static final String TAG = "Contact";
// 查询条件语句模板用于构建查询通讯录的SQL WHERE条件
// 注意:这里使用"+"作为占位符,后面会被替换为最小匹配位数
// PHONE_NUMBERS_EQUAL()是Android提供的特殊函数用于电话号码匹配
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 "
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
+ " FROM phone_lookup" // phone_lookup是Android系统的电话号码查询优化表
+ " WHERE min_match = '+')"; // "+"是占位符,会被替换为实际的最小匹配位数
/**
*
* @param context Android访ContentResolver
* @param phoneNumber
* @return null
*
* 1.
* 2.
* 3.
* 4.
*/
public static String getContact(Context context, String phoneNumber) {
// 延迟初始化缓存第一次使用时才创建HashMap
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 检查缓存:如果缓存中已有该号码,直接返回缓存的联系人姓名
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
// 构建查询条件:替换占位符"+"为电话号码的最小匹配位数
// PhoneNumberUtils.toCallerIDMinMatch()计算电话号码的最小匹配位数
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 通过ContentResolver查询系统通讯录
// Data.CONTENT_URI通讯录数据的统一资源标识符
// 查询条件:电话号码匹配且数据类型为电话号码
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
null);
Data.CONTENT_URI, // 通讯录数据URI
new String [] { Phone.DISPLAY_NAME }, // 只查询显示名字段
selection, // 查询条件
new String[] { phoneNumber }, // 查询参数:电话号码
null); // 排序条件:不排序
// 处理查询结果
if (cursor != null && cursor.moveToFirst()) {
try {
// 获取第一条结果的联系人姓名
String name = cursor.getString(0);
// 将结果存入缓存
sContactCache.put(phoneNumber, name);
return name;
} catch (IndexOutOfBoundsException e) {
// 捕获数组越界异常,记录错误日志
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
// 无论是否成功都必须关闭Cursor释放资源
cursor.close();
}
} else {
// 没有找到匹配的联系人,记录调试日志
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}
}

@ -17,24 +17,28 @@
package net.micode.notes.data;
import android.net.Uri;
/**
* Notes - 便
* ContentProvider URIIntent便
*
*/
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;
/**
* 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
*/
// 系统文件夹ID
public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
// Intent Extra键
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
@ -42,238 +46,88 @@ public class Notes {
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;
/**
* DataConstants -
*/
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/**
* Uri to query all notes and folders
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
/**
* Uri to query data
* NoteColumns - 便
*/
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>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
*/
public static final String SNIPPET = "snippet";
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* Note's background color's id
* <P> Type: 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>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
*/
public static final String TYPE = "type";
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id";
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P> Type : INTEGER (long) </P>
*/
public static final String VERSION = "version";
public static final String PINNED = "pinned";
public static final String TITLE = "title"; // 便签标题字段
public static final String PRIVATE = "is_private"; // 是否为隐私文件夹
public static final String IS_STUDY = "is_study"; // 是否为学习文件夹
public static final String FOCUS_DURATION = "focus_duration"; // 专注时长(毫秒)
}
/**
* DataColumns - 便EAV
*/
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: 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>
*/
public static final String NOTE_ID = "note_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Data's content
* <P> Type: 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>
*/
public static final String DATA1 = "data1";
/**
* Generic data column, the meaning is {@link #MIMETYPE} 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
* TEXT data type
* <P> Type: 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>
*/
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";
}
/**
* TextNote - 便
*/
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; // 1:清单模式 0:普通模式
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");
}
/**
* CallNote - 便
*/
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
*/
public static final String CALL_DATE = DATA1;
/**
* Phone number for this record
* <P> Type: TEXT </P>
*/
public static final String PHONE_NUMBER = DATA3;
public static final String CALL_DATE = DATA1; // 通话日期
public static final String PHONE_NUMBER = DATA3; // 电话号码
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");
}
}
}

@ -26,190 +26,194 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
/**
* NotesDatabaseHelper - 便
*
* 便SQLite
* SQLiteOpenHelper
* notedata
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 数据库名称
private static final String DB_NAME = "note.db";
// 数据库版本号,用于数据库升级管理
private static final int DB_VERSION = 8;
private static final int DB_VERSION = 4;
// 表名常量接口
public interface TABLE {
public static final String NOTE = "note";
public static final String DATA = "data";
public static final String NOTE = "note"; // 便签主表
public static final String DATA = "data"; // 便签数据表
}
private static final String TAG = "NotesDatabaseHelper";
private static NotesDatabaseHelper mInstance;
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" +
")";
private static final String TAG = "NotesDatabaseHelper"; // 日志标签
private static NotesDatabaseHelper mInstance; // 单例实例
// 创建note表的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.TITLE + " 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," +
NoteColumns.PINNED + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.PRIVATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.IS_STUDY + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.FOCUS_DURATION + " INTEGER NOT NULL DEFAULT 0" +
")";
// 创建data表的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 ''" +
")";
"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 ''" +
")";
// 创建data表note_id索引的SQL语句
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
"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
*/
// 触发器:当更新便签的父文件夹时,增加目标文件夹的便签计数
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
*/
"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";
// 触发器:当更新便签的父文件夹时,减少原文件夹的便签计数
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
*/
"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";
// 触发器:当插入新便签时,增加父文件夹的便签计数
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";
/**
* Decrease folder's note count when delete note from the folder
*/
"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";
// 触发器:当删除便签时,减少父文件夹的便签计数
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}
*/
"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";
// 触发器当插入数据且类型为普通便签时更新便签的snippet字段
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
*/
"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";
// 触发器当更新数据且类型为普通便签时更新便签的snippet字段
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
*/
"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";
// 触发器当删除数据且类型为普通便签时清空便签的snippet字段
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
*/
"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";
// 触发器:当删除便签时,同步删除该便签的所有数据
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
*/
"CREATE TRIGGER delete_data_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" END";
// 触发器:当删除文件夹时,同步删除该文件夹下的所有便签(级联删除)
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";
"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";
// 触发器:当文件夹被移动到回收站时,将该文件夹下的所有便签也移动到回收站
// 但保持便签的PARENT_ID不变这样可以在回收站中查看完整的文件夹结构
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.ORIGIN_PARENT_ID + "=parent_id" +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END;";
/**
* Move notes belong to folder which has been moved to trash folder
*
* @param context Android
*/
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";
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
* note
* @param db SQLiteDatabase
*/
public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db);
@ -217,6 +221,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "note table has been created");
}
/**
* note
* @param db SQLiteDatabase
*/
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,41 +243,41 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
/**
*
* @param db SQLiteDatabase
*/
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);
}
/**
* data
* @param db SQLiteDatabase
*/
public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db);
@ -277,6 +285,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "data table has been created");
}
/**
* data
* @param db SQLiteDatabase
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
@ -287,6 +299,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
/**
* 线
* @param context Android
* @return NotesDatabaseHelper
*/
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
@ -294,45 +311,88 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance;
}
/**
*
* @param db SQLiteDatabase
*/
@Override
public void onCreate(SQLiteDatabase db) {
createNoteTable(db);
createDataTable(db);
}
/**
*
* @param db SQLiteDatabase
* @param oldVersion
* @param newVersion
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
boolean skipV2 = false;
// 从版本1升级到版本2
if (oldVersion == 1) {
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
skipV2 = true; // 此次升级已包含从v2到v3的升级
oldVersion++;
}
// 从版本2升级到版本3如果未跳过
if (oldVersion == 2 && !skipV2) {
upgradeToV3(db);
reCreateTriggers = true;
oldVersion++;
}
// 从版本3升级到版本4
if (oldVersion == 3) {
upgradeToV4(db);
oldVersion++;
}
// 从版本4升级到版本5
if (oldVersion == 4) {
upgradeToV5(db);
oldVersion++;
}
// 从版本5升级到版本6添加title列用于存储便签标题
if (oldVersion == 5) {
upgradeToV6(db);
oldVersion++;
}
// 从版本6升级到版本7添加is_private列用于标识隐私文件夹
if (oldVersion == 6) {
upgradeToV7(db);
oldVersion++;
}
// 从版本7升级到版本8添加is_study和focus_duration列用于学习文件夹功能
if (oldVersion == 7) {
upgradeToV8(db);
oldVersion++;
}
// 如果需要,重新创建触发器
if (reCreateTriggers) {
reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
}
// 如果版本号不匹配,抛出异常
if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails");
}
}
/**
* 2
* @param db SQLiteDatabase
*/
private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
@ -340,23 +400,72 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
createDataTable(db);
}
/**
* 3
* 1. 使
* 2. gtask_id
* 3.
* @param db SQLiteDatabase
*/
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
// 添加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);
}
/**
* 4version
* @param db SQLiteDatabase
*/
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}
}
/**
* 5pinned便
* @param db SQLiteDatabase
*/
private void upgradeToV5(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.PINNED
+ " INTEGER NOT NULL DEFAULT 0");
}
/**
* 6title便
* @param db SQLiteDatabase
*/
private void upgradeToV6(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.TITLE
+ " TEXT NOT NULL DEFAULT ''");
}
/**
* 7is_private
* @param db SQLiteDatabase
*/
private void upgradeToV7(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.PRIVATE
+ " INTEGER NOT NULL DEFAULT 0");
}
/**
* 8is_studyfocus_duration
* @param db SQLiteDatabase
*/
private void upgradeToV8(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.IS_STUDY
+ " INTEGER NOT NULL DEFAULT 0");
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.FOCUS_DURATION
+ " INTEGER NOT NULL DEFAULT 0");
}
}

@ -16,7 +16,6 @@
package net.micode.notes.data;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
@ -34,22 +33,28 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* NotesProvider - 便ContentProvider
*
* 便访ContentProvider
* ContentProvidernotedataCRUD
*/
public class NotesProvider extends ContentProvider {
private static final UriMatcher mMatcher;
private NotesDatabaseHelper mHelper;
private static final UriMatcher mMatcher; // URI匹配器用于匹配不同的URI请求
private static final String TAG = "NotesProvider";
private NotesDatabaseHelper mHelper; // 数据库帮助类实例
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 String TAG = "NotesProvider"; // 日志标签
private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;
// URI匹配常量定义
private static final int URI_NOTE = 1; // 匹配note表所有记录
private static final int URI_NOTE_ITEM = 2; // 匹配note表单条记录
private static final int URI_DATA = 3; // 匹配data表所有记录
private static final int URI_DATA_ITEM = 4; // 匹配data表单条记录
private static final int URI_SEARCH = 5; // 匹配搜索请求
private static final int URI_SEARCH_SUGGEST = 6; // 匹配搜索建议请求
// 静态初始化块初始化URI匹配器添加各种URI模式
static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
@ -62,76 +67,92 @@ 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.
*
* x'0A' SQLite'\n'
* '\n'
*/
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;
+ 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 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;
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?" // 模糊匹配搜索条件
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER // 排除回收站中的便签
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; // 只搜索普通便签类型
/**
* ContentProvider
* @return true
*/
@Override
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
/**
* URI
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return Cursor
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
String sortOrder) {
Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
switch (mMatcher.match(uri)) {
case URI_NOTE:
case URI_NOTE: // 查询note表所有记录
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
case URI_NOTE_ITEM: // 查询note表单条记录
id = uri.getPathSegments().get(1); // 从URI路径段中获取ID
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
case URI_DATA: // 查询data表所有记录
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM:
case URI_DATA_ITEM: // 查询data表单条记录
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:
case URI_SEARCH_SUGGEST: // 处理搜索和搜索建议请求
if (sortOrder != null || projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
String searchString = null;
// 根据URI类型获取搜索字符串
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1);
}
} else {
searchString = uri.getQueryParameter("pattern");
searchString = uri.getQueryParameter("pattern"); // 从查询参数获取搜索模式
}
if (TextUtils.isEmpty(searchString)) {
return null;
return null; // 搜索字符串为空则返回null
}
try {
searchString = String.format("%%%s%%", searchString);
searchString = String.format("%%%s%%", searchString); // 添加通配符进行模糊匹配
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
} catch (IllegalStateException ex) {
@ -141,21 +162,28 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 设置通知URI以便在数据变化时能够通知观察者
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
/**
*
* @param uri URI
* @param values
* @return URI
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
case URI_NOTE:
case URI_NOTE: // 插入note表记录
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
case URI_DATA:
case URI_DATA: // 插入data表记录
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
@ -166,50 +194,57 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
// 通知note URI的数据变化
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
// 通知data URI的数据变化
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
// 返回新插入数据的URI
return ContentUris.withAppendedId(uri, insertedId);
}
/**
*
* @param uri URI
* @param selection
* @param selectionArgs
* @return
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
boolean deleteData = false; // 标记是否删除data表数据
switch (mMatcher.match(uri)) {
case URI_NOTE:
case URI_NOTE: // 删除note表记录系统文件夹不允许删除
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
case URI_NOTE_ITEM: // 删除note表单条记录
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
* ID0
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
break;
break; // 系统文件夹不删除
}
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
case URI_DATA: // 删除data表记录
count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true;
break;
case URI_DATA_ITEM:
case URI_DATA_ITEM: // 删除data表单条记录
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
@ -218,8 +253,10 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 如果删除了记录,通知数据变化
if (count > 0) {
if (deleteData) {
// 删除data表数据时需要通知note URI
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
@ -227,28 +264,36 @@ public class NotesProvider extends ContentProvider {
return count;
}
/**
*
* @param uri URI
* @param values
* @param selection
* @param selectionArgs
* @return
*/
@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;
boolean updateData = false; // 标记是否更新data表数据
switch (mMatcher.match(uri)) {
case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs);
case URI_NOTE: // 更新note表记录
increaseNoteVersion(-1, selection, selectionArgs); // 增加版本号
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
case URI_NOTE_ITEM: // 更新note表单条记录
id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 增加版本号
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
break;
case URI_DATA:
case URI_DATA: // 更新data表记录
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
break;
case URI_DATA_ITEM:
case URI_DATA_ITEM: // 更新data表单条记录
id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
@ -258,8 +303,10 @@ public class NotesProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 如果更新了记录,通知数据变化
if (count > 0) {
if (updateData) {
// 更新data表数据时需要通知note URI
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
@ -267,18 +314,30 @@ public class NotesProvider extends ContentProvider {
return count;
}
/**
* AND
* @param selection
* @return
*/
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
/**
* 便
* @param id 便ID0-1
* @param selection
* @param selectionArgs
*/
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 ");
sql.append("=" + NoteColumns.VERSION + "+1 "); // 版本号加1
// 构建WHERE子句
if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE ");
}
@ -287,19 +346,25 @@ public class NotesProvider extends ContentProvider {
}
if (!TextUtils.isEmpty(selection)) {
String selectString = id > 0 ? parseSelection(selection) : selection;
// 替换参数占位符
for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args);
}
sql.append(selectString);
}
// 执行SQL语句
mHelper.getWritableDatabase().execSQL(sql.toString());
}
/**
* URIMIME
* @param uri URI
* @return MIME
*/
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}
}

@ -24,59 +24,101 @@ import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* MetaData -
*
* Google Tasks
* Task便Google Tasks
* Google Task ID
*/
public class MetaData extends Task {
private final static String TAG = MetaData.class.getSimpleName();
private final static String TAG = MetaData.class.getSimpleName(); // 日志标签
private String mRelatedGid = null;
private String mRelatedGid = null; // 关联的Google Task ID
/**
*
* @param gid Google TaskID
* @param metaInfo JSONObject
*/
public void setMeta(String gid, JSONObject metaInfo) {
try {
// 将Google Task ID添加到元信息中
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) {
Log.e(TAG, "failed to put related gid");
Log.e(TAG, "failed to put related gid"); // 记录错误日志
}
setNotes(metaInfo.toString());
setName(GTaskStringUtils.META_NOTE_NAME);
setNotes(metaInfo.toString()); // 将JSON字符串设置为便签内容
setName(GTaskStringUtils.META_NOTE_NAME); // 设置元数据便签的名称
}
/**
* Google Task ID
* @return Google Task IDnull
*/
public String getRelatedGid() {
return mRelatedGid;
}
/**
* 便
* @return 便truefalse
*/
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
/**
* JSONGoogle Tasks
* @param js JSONObject
*/
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
super.setContentByRemoteJSON(js); // 调用父类方法设置基础内容
if (getNotes() != null) {
try {
// 解析便签内容为JSON提取关联的Google Task ID
JSONObject metaInfo = new JSONObject(getNotes().trim());
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) {
Log.w(TAG, "failed to get related gid");
mRelatedGid = null;
Log.w(TAG, "failed to get related gid"); // 记录警告日志
mRelatedGid = null; // 解析失败时设为null
}
}
}
/**
* JSON
* @param js JSON
* @throws IllegalAccessError
*/
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
// 此方法不应被调用MetaData不从本地JSON设置内容
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
/**
* JSON
* @return JSON
* @throws IllegalAccessError
*/
@Override
public JSONObject getLocalJSONFromContent() {
// 此方法不应被调用MetaData不生成本地JSON
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
/**
*
* @param c
* @return
* @throws IllegalAccessError
*/
@Override
public int getSyncAction(Cursor c) {
// 此方法不应被调用MetaData不处理同步操作
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
}
}
}

@ -20,33 +20,34 @@ import android.database.Cursor;
import org.json.JSONObject;
/**
* Node -
*
* Google Tasks
* 便
* TaskMetaData
*/
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;
// 同步操作状态码定义
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; // Google Task ID全局唯一标识
private String mName; // 节点名称
private long mLastModified; // 最后修改时间戳
private boolean mDeleted; // 删除标记
/**
*
*/
public Node() {
mGid = null;
mName = "";
@ -54,48 +55,111 @@ public abstract class Node {
mDeleted = false;
}
// =============== 抽象方法定义 ===============
// 这些方法需要子类根据具体的数据类型来实现
/**
* JSON
* @param actionId ID
* @return JSONObject
*/
public abstract JSONObject getCreateAction(int actionId);
/**
* JSON
* @param actionId ID
* @return JSONObject
*/
public abstract JSONObject getUpdateAction(int actionId);
/**
* JSONGoogle Tasks
* @param js JSONObject
*/
public abstract void setContentByRemoteJSON(JSONObject js);
/**
* JSON
* @param js JSONObject
*/
public abstract void setContentByLocalJSON(JSONObject js);
/**
* JSON
* @return JSONObject
*/
public abstract JSONObject getLocalJSONFromContent();
/**
*
* @param c Cursor
* @return SYNC_ACTION_*
*/
public abstract int getSyncAction(Cursor c);
// =============== Getter和Setter方法 ===============
/**
* Google Task ID
* @param gid Google Task
*/
public void setGid(String gid) {
this.mGid = gid;
}
/**
*
* @param name
*/
public void setName(String name) {
this.mName = name;
}
/**
*
* @param lastModified
*/
public void setLastModified(long lastModified) {
this.mLastModified = lastModified;
}
/**
*
* @param deleted truefalse
*/
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}
/**
* Google Task ID
* @return Google Task
*/
public String getGid() {
return this.mGid;
}
/**
*
* @return
*/
public String getName() {
return this.mName;
}
/**
*
* @return
*/
public long getLastModified() {
return this.mLastModified;
}
/**
*
* @return truefalse
*/
public boolean getDeleted() {
return this.mDeleted;
}
}
}

@ -34,61 +34,71 @@ import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException;
import org.json.JSONObject;
/**
* SqlData -
*
* 便dataCRUDJSON
* Google Tasks
*
*/
public class SqlData {
private static final String TAG = SqlData.class.getSimpleName();
private static final String TAG = SqlData.class.getSimpleName(); // 日志标签
private static final int INVALID_ID = -99999;
private static final int INVALID_ID = -99999; // 无效ID标识
// 数据表查询字段投影
public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
};
public static final int DATA_ID_COLUMN = 0;
public static final int DATA_MIME_TYPE_COLUMN = 1;
public static final int DATA_CONTENT_COLUMN = 2;
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver;
private boolean mIsCreate;
private long mDataId;
private String mDataMimeType;
private String mDataContent;
private long mDataContentData1;
private String mDataContentData3;
private ContentValues mDiffDataValues;
// 字段索引常量
public static final int DATA_ID_COLUMN = 0; // ID字段索引
public static final int DATA_MIME_TYPE_COLUMN = 1; // MIME类型字段索引
public static final int DATA_CONTENT_COLUMN = 2; // 内容字段索引
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;// DATA1字段索引
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;// DATA3字段索引
private ContentResolver mContentResolver; // 内容解析器用于访问ContentProvider
private boolean mIsCreate; // 创建标记true表示新数据false表示已存在数据
private long mDataId; // 数据ID
private String mDataMimeType; // 数据MIME类型
private String mDataContent; // 数据内容
private long mDataContentData1; // 数据DATA1字段值
private String mDataContentData3; // 数据DATA3字段值
private ContentValues mDiffDataValues; // 差异数据值,用于记录需要更新的字段
/**
* SqlData
* @param context Android
*/
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
mDataId = INVALID_ID;
mDataMimeType = DataConstants.NOTE;
mDataContent = "";
mDataContentData1 = 0;
mDataContentData3 = "";
mDiffDataValues = new ContentValues();
mIsCreate = true; // 标记为新数据
mDataId = INVALID_ID; // 初始化ID为无效值
mDataMimeType = DataConstants.NOTE; // 默认MIME类型为普通便签
mDataContent = ""; // 初始化内容为空
mDataContentData1 = 0; // 初始化DATA1为0
mDataContentData3 = ""; // 初始化DATA3为空
mDiffDataValues = new ContentValues(); // 创建差异值容器
}
/**
* SqlData
* @param context Android
* @param c Cursor
*/
public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDiffDataValues = new ContentValues();
mIsCreate = false; // 标记为已有数据
loadFromCursor(c); // 从游标加载数据
mDiffDataValues = new ContentValues(); // 创建差异值容器
}
/**
*
* @param c Cursor
*/
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -97,13 +107,20 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
/**
* JSON
* @param js JSONObject
* @throws JSONException JSON
*/
public void setContent(JSONObject js) throws JSONException {
// 处理数据ID
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId);
}
mDataId = dataId;
// 处理MIME类型
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE;
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
@ -111,18 +128,21 @@ public class SqlData {
}
mDataMimeType = dataMimeType;
// 处理内容
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
if (mIsCreate || !mDataContent.equals(dataContent)) {
mDiffDataValues.put(DataColumns.CONTENT, dataContent);
}
mDataContent = dataContent;
// 处理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);
@ -130,11 +150,17 @@ public class SqlData {
mDataContentData3 = dataContentData3;
}
/**
* JSON
* @return JSONObjectnull
* @throws JSONException JSON
*/
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
}
// 创建JSON对象并添加所有字段
JSONObject js = new JSONObject();
js.put(DataColumns.ID, mDataId);
js.put(DataColumns.MIME_TYPE, mDataMimeType);
@ -144,30 +170,41 @@ public class SqlData {
return js;
}
/**
*
* @param noteId 便ID
* @param validateVersion
* @param version validateVersiontrue使
* @throws ActionFailureException
*/
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
// 创建新数据记录
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID);
}
mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
mDiffDataValues.put(DataColumns.NOTE_ID, noteId); // 设置关联的便签ID
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try {
// 从返回的URI中提取新创建的数据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 {
// 更新已有数据记录
if (mDiffDataValues.size() > 0) {
int result = 0;
if (!validateVersion) {
// 不验证版本号,直接更新
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else {
// 验证版本号,确保数据未被其他操作修改
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
String.valueOf(noteId), String.valueOf(version)
@ -179,11 +216,16 @@ public class SqlData {
}
}
// 重置状态
mDiffDataValues.clear();
mIsCreate = false;
}
/**
* ID
* @return ID
*/
public long getId() {
return mDataId;
}
}
}

@ -37,12 +37,16 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* Google Task
* SQLiteJSON
*/
public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName();
private static final String TAG = SqlNote.class.getSimpleName(); // 日志标签
private static final int INVALID_ID = -99999;
private static final int INVALID_ID = -99999; // 无效ID常量
// 数据库查询的投影字段(需要查询的列)
public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@ -52,454 +56,517 @@ public class SqlNote {
NoteColumns.VERSION
};
public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1;
public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3;
public static final int HAS_ATTACHMENT_COLUMN = 4;
public static final int MODIFIED_DATE_COLUMN = 5;
public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8;
public static final int TYPE_COLUMN = 9;
public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12;
public static final int LOCAL_MODIFIED_COLUMN = 13;
public static final int ORIGIN_PARENT_ID_COLUMN = 14;
public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16;
private Context mContext;
private ContentResolver mContentResolver;
private boolean mIsCreate;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private int mHasAttachment;
private long mModifiedDate;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private long mOriginParent;
private long mVersion;
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
// 投影字段对应的索引号
public static final int ID_COLUMN = 0; // ID列索引
public static final int ALERTED_DATE_COLUMN = 1; // 提醒日期列索引
public static final int BG_COLOR_ID_COLUMN = 2; // 背景颜色ID列索引
public static final int CREATED_DATE_COLUMN = 3; // 创建日期列索引
public static final int HAS_ATTACHMENT_COLUMN = 4; // 是否有附件列索引
public static final int MODIFIED_DATE_COLUMN = 5; // 修改日期列索引
public static final int NOTES_COUNT_COLUMN = 6; // 笔记数量列索引
public static final int PARENT_ID_COLUMN = 7; // 父ID列索引
public static final int SNIPPET_COLUMN = 8; // 摘要内容列索引
public static final int TYPE_COLUMN = 9; // 类型列索引
public static final int WIDGET_ID_COLUMN = 10; // 小部件ID列索引
public static final int WIDGET_TYPE_COLUMN = 11; // 小部件类型列索引
public static final int SYNC_ID_COLUMN = 12; // 同步ID列索引
public static final int LOCAL_MODIFIED_COLUMN = 13; // 本地修改标记列索引
public static final int ORIGIN_PARENT_ID_COLUMN = 14; // 原始父ID列索引
public static final int GTASK_ID_COLUMN = 15; // Google Task ID列索引
public static final int VERSION_COLUMN = 16; // 版本号列索引
private Context mContext; // 上下文对象
private ContentResolver mContentResolver; // 内容解析器,用于数据库操作
private boolean mIsCreate; // 标记是否为新建笔记true表示新建false表示从数据库加载
private long mId; // 笔记ID
private long mAlertDate; // 提醒日期
private int mBgColorId; // 背景颜色ID
private long mCreatedDate; // 创建日期
private int mHasAttachment; // 是否有附件0表示无1表示有
private long mModifiedDate; // 修改日期
private long mParentId; // 父文件夹ID
private String mSnippet; // 笔记内容摘要
private int mType; // 笔记类型(笔记、文件夹、系统文件夹等)
private int mWidgetId; // 关联的小部件ID
private int mWidgetType; // 小部件类型
private long mOriginParent; // 原始父文件夹ID用于恢复操作
private long mVersion; // 版本号(用于乐观锁控制)
private ContentValues mDiffNoteValues; // 存储需要更新的字段值(用于数据库更新)
private ArrayList<SqlData> mDataList; // 笔记内容数据列表(用于普通笔记类型)
/**
* -
*
* @param context
*/
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = true;
mId = INVALID_ID;
mAlertDate = 0;
mBgColorId = ResourceParser.getDefaultBgId(context);
mCreatedDate = System.currentTimeMillis();
mHasAttachment = 0;
mModifiedDate = System.currentTimeMillis();
mParentId = 0;
mSnippet = "";
mType = Notes.TYPE_NOTE;
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
mOriginParent = 0;
mVersion = 0;
mDiffNoteValues = new ContentValues();
mDataList = new ArrayList<SqlData>();
mIsCreate = true; // 标记为新建笔记
mId = INVALID_ID; // 使用无效ID
mAlertDate = 0; // 默认无提醒
mBgColorId = ResourceParser.getDefaultBgId(context); // 获取默认背景颜色ID
mCreatedDate = System.currentTimeMillis(); // 使用当前时间作为创建时间
mHasAttachment = 0; // 默认无附件
mModifiedDate = System.currentTimeMillis(); // 使用当前时间作为修改时间
mParentId = 0; // 默认父ID为0
mSnippet = ""; // 空摘要
mType = Notes.TYPE_NOTE; // 默认为普通笔记类型
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; // 无效的小部件ID
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 无效的小部件类型
mOriginParent = 0; // 默认原始父ID为0
mVersion = 0; // 初始版本为0
mDiffNoteValues = new ContentValues(); // 初始化更新字段容器
mDataList = new ArrayList<SqlData>(); // 初始化数据列表
}
/**
* -
*
* @param context
* @param c
*/
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDataList = new ArrayList<SqlData>();
mIsCreate = false; // 标记为从数据库加载
loadFromCursor(c); // 从游标加载数据
mDataList = new ArrayList<SqlData>(); // 初始化数据列表
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
loadDataContent(); // 如果是普通笔记类型,加载笔记内容数据
mDiffNoteValues = new ContentValues(); // 初始化更新字段容器
}
/**
* - ID
* ID
* @param context
* @param id ID
*/
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(id);
mDataList = new ArrayList<SqlData>();
mIsCreate = false; // 标记为从数据库加载
loadFromCursor(id); // 通过ID从数据库加载数据
mDataList = new ArrayList<SqlData>(); // 初始化数据列表
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
loadDataContent(); // 如果是普通笔记类型,加载笔记内容数据
mDiffNoteValues = new ContentValues(); // 初始化更新字段容器
}
/**
* ID
* ID
* @param id ID
*/
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)
String.valueOf(id)
}, null);
if (c != null) {
c.moveToNext();
loadFromCursor(c);
c.moveToNext(); // 移动到查询结果的第一行
loadFromCursor(c); // 从游标加载数据
} else {
Log.w(TAG, "loadFromCursor: cursor = null");
Log.w(TAG, "loadFromCursor: cursor = null"); // 日志记录游标为空
}
} finally {
if (c != null)
c.close();
c.close(); // 关闭游标
}
}
/**
*
*
* @param c
*/
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = c.getLong(CREATED_DATE_COLUMN);
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN);
mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN);
mParentId = c.getLong(PARENT_ID_COLUMN);
mSnippet = c.getString(SNIPPET_COLUMN);
mType = c.getInt(TYPE_COLUMN);
mWidgetId = c.getInt(WIDGET_ID_COLUMN);
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
mVersion = c.getLong(VERSION_COLUMN);
mId = c.getLong(ID_COLUMN); // 获取笔记ID
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); // 获取提醒日期
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); // 获取背景颜色ID
mCreatedDate = c.getLong(CREATED_DATE_COLUMN); // 获取创建日期
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); // 获取是否有附件
mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); // 获取修改日期
mParentId = c.getLong(PARENT_ID_COLUMN); // 获取父文件夹ID
mSnippet = c.getString(SNIPPET_COLUMN); // 获取笔记摘要
mType = c.getInt(TYPE_COLUMN); // 获取笔记类型
mWidgetId = c.getInt(WIDGET_ID_COLUMN); // 获取小部件ID
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); // 获取小部件类型
mVersion = c.getLong(VERSION_COLUMN); // 获取版本号
}
/**
*
*
*/
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
mDataList.clear(); // 清空数据列表
try {
// 查询笔记的内容数据
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] {
String.valueOf(mId)
String.valueOf(mId)
}, null);
if (c != null) {
if (c.getCount() == 0) {
Log.w(TAG, "it seems that the note has not data");
Log.w(TAG, "it seems that the note has not data"); // 日志记录笔记无内容数据
return;
}
while (c.moveToNext()) {
SqlData data = new SqlData(mContext, c);
mDataList.add(data);
SqlData data = new SqlData(mContext, c); // 创建SqlData对象
mDataList.add(data); // 添加到数据列表
}
} else {
Log.w(TAG, "loadDataContent: cursor = null");
Log.w(TAG, "loadDataContent: cursor = null"); // 日志记录游标为空
}
} finally {
if (c != null)
c.close();
c.close(); // 关闭游标
}
}
/**
* JSON
* JSON
* @param js JSON
* @return truefalse
*/
public boolean setContent(JSONObject js) {
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); // 获取笔记JSON对象
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
Log.w(TAG, "cannot set system folder");
Log.w(TAG, "cannot set system folder"); // 系统文件夹不能设置
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// for folder we can only update the snnipet and type
// 对于文件夹类型,只能更新摘要和类型
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
.getString(NoteColumns.SNIPPET) : ""; // 获取摘要,如果不存在则为空字符串
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); // 如果摘要发生变化,记录更新
}
mSnippet = snippet;
mSnippet = snippet; // 更新摘要字段
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
: Notes.TYPE_NOTE; // 获取类型,如果不存在则默认为笔记类型
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
mDiffNoteValues.put(NoteColumns.TYPE, type); // 如果类型发生变化,记录更新
}
mType = type;
mType = type; // 更新类型字段
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
// 对于普通笔记类型,需要设置所有字段
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); // 获取笔记内容数据数组
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; // 获取笔记ID
if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id);
mDiffNoteValues.put(NoteColumns.ID, id); // 如果ID发生变化记录更新
}
mId = id;
mId = id; // 更新ID字段
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
.getLong(NoteColumns.ALERTED_DATE) : 0;
.getLong(NoteColumns.ALERTED_DATE) : 0; // 获取提醒日期
if (mIsCreate || mAlertDate != alertDate) {
mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); // 如果提醒日期变化,记录更新
}
mAlertDate = alertDate;
mAlertDate = alertDate; // 更新提醒日期字段
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); // 获取背景颜色ID
if (mIsCreate || mBgColorId != bgColorId) {
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); // 如果背景颜色变化,记录更新
}
mBgColorId = bgColorId;
mBgColorId = bgColorId; // 更新背景颜色ID字段
long createDate = note.has(NoteColumns.CREATED_DATE) ? note
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); // 获取创建日期
if (mIsCreate || mCreatedDate != createDate) {
mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); // 如果创建日期变化,记录更新
}
mCreatedDate = createDate;
mCreatedDate = createDate; // 更新创建日期字段
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
.getInt(NoteColumns.HAS_ATTACHMENT) : 0;
.getInt(NoteColumns.HAS_ATTACHMENT) : 0; // 获取是否有附件
if (mIsCreate || mHasAttachment != hasAttachment) {
mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); // 如果附件状态变化,记录更新
}
mHasAttachment = hasAttachment;
mHasAttachment = hasAttachment; // 更新附件字段
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); // 获取修改日期
if (mIsCreate || mModifiedDate != modifiedDate) {
mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); // 如果修改日期变化,记录更新
}
mModifiedDate = modifiedDate;
mModifiedDate = modifiedDate; // 更新修改日期字段
long parentId = note.has(NoteColumns.PARENT_ID) ? note
.getLong(NoteColumns.PARENT_ID) : 0;
.getLong(NoteColumns.PARENT_ID) : 0; // 获取父文件夹ID
if (mIsCreate || mParentId != parentId) {
mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); // 如果父ID变化记录更新
}
mParentId = parentId;
mParentId = parentId; // 更新父ID字段
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
.getString(NoteColumns.SNIPPET) : ""; // 获取摘要
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); // 如果摘要变化,记录更新
}
mSnippet = snippet;
mSnippet = snippet; // 更新摘要字段
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
: Notes.TYPE_NOTE; // 获取笔记类型
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
mDiffNoteValues.put(NoteColumns.TYPE, type); // 如果类型变化,记录更新
}
mType = type;
mType = type; // 更新类型字段
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
: AppWidgetManager.INVALID_APPWIDGET_ID;
: AppWidgetManager.INVALID_APPWIDGET_ID; // 获取小部件ID
if (mIsCreate || mWidgetId != widgetId) {
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); // 如果小部件ID变化记录更新
}
mWidgetId = widgetId;
mWidgetId = widgetId; // 更新小部件ID字段
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; // 获取小部件类型
if (mIsCreate || mWidgetType != widgetType) {
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); // 如果小部件类型变化,记录更新
}
mWidgetType = widgetType;
mWidgetType = widgetType; // 更新小部件类型字段
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; // 获取原始父文件夹ID
if (mIsCreate || mOriginParent != originParent) {
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); // 如果原始父ID变化记录更新
}
mOriginParent = originParent;
mOriginParent = originParent; // 更新原始父ID字段
// 处理笔记内容数据
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
JSONObject data = dataArray.getJSONObject(i); // 获取每条内容数据
SqlData sqlData = null;
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
long dataId = data.getLong(DataColumns.ID); // 获取内容数据ID
// 在现有数据列表中查找匹配的内容数据
for (SqlData temp : mDataList) {
if (dataId == temp.getId()) {
sqlData = temp;
sqlData = temp; // 找到已存在的数据
}
}
}
if (sqlData == null) {
sqlData = new SqlData(mContext);
mDataList.add(sqlData);
sqlData = new SqlData(mContext); // 创建新的内容数据对象
mDataList.add(sqlData); // 添加到数据列表
}
sqlData.setContent(data);
sqlData.setContent(data); // 设置内容数据
}
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // 记录JSON解析异常
e.printStackTrace();
return false;
return false; // 返回失败
}
return true;
return true; // 返回成功
}
/**
* JSON
* JSON
* @return JSONnull
*/
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
JSONObject js = new JSONObject(); // 创建JSON对象
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
Log.e(TAG, "it seems that we haven't created this in database yet"); // 日志记录笔记尚未创建
return null; // 返回null
}
JSONObject note = new JSONObject();
JSONObject note = new JSONObject(); // 创建笔记JSON对象
if (mType == Notes.TYPE_NOTE) {
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate);
note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
note.put(NoteColumns.CREATED_DATE, mCreatedDate);
note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment);
note.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
note.put(NoteColumns.PARENT_ID, mParentId);
note.put(NoteColumns.SNIPPET, mSnippet);
note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.WIDGET_ID, mWidgetId);
note.put(NoteColumns.WIDGET_TYPE, mWidgetType);
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
JSONArray dataArray = new JSONArray();
// 普通笔记类型,包含所有字段
note.put(NoteColumns.ID, mId); // 添加ID
note.put(NoteColumns.ALERTED_DATE, mAlertDate); // 添加提醒日期
note.put(NoteColumns.BG_COLOR_ID, mBgColorId); // 添加背景颜色ID
note.put(NoteColumns.CREATED_DATE, mCreatedDate); // 添加创建日期
note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); // 添加附件状态
note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); // 添加修改日期
note.put(NoteColumns.PARENT_ID, mParentId); // 添加父文件夹ID
note.put(NoteColumns.SNIPPET, mSnippet); // 添加摘要
note.put(NoteColumns.TYPE, mType); // 添加类型
note.put(NoteColumns.WIDGET_ID, mWidgetId); // 添加小部件ID
note.put(NoteColumns.WIDGET_TYPE, mWidgetType); // 添加小部件类型
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); // 添加原始父文件夹ID
js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 将笔记对象添加到JSON
// 添加笔记内容数据
JSONArray dataArray = new JSONArray(); // 创建内容数据数组
for (SqlData sqlData : mDataList) {
JSONObject data = sqlData.getContent();
JSONObject data = sqlData.getContent(); // 获取内容数据的JSON
if (data != null) {
dataArray.put(data);
dataArray.put(data); // 添加到数组
}
}
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); // 将内容数据数组添加到JSON
} 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);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
// 文件夹或系统文件夹类型,只包含必要字段
note.put(NoteColumns.ID, mId); // 添加ID
note.put(NoteColumns.TYPE, mType); // 添加类型
note.put(NoteColumns.SNIPPET, mSnippet); // 添加摘要
js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 将笔记对象添加到JSON
}
return js;
return js; // 返回JSON对象
} catch (JSONException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // 记录JSON异常
e.printStackTrace();
}
return null;
return null; // 返回null
}
/**
* ID
* ID
* @param id ID
*/
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
mParentId = id; // 更新父文件夹ID字段
mDiffNoteValues.put(NoteColumns.PARENT_ID, id); // 记录需要更新的字段
}
/**
* Google Task ID
* Google Task ID
* @param gid Google Task ID
*/
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); // 记录需要更新的字段
}
/**
* ID
* ID
* @param syncId ID
*/
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); // 记录需要更新的字段
}
/**
*
* 0
*/
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); // 记录需要更新的字段
}
/**
* ID
* @return ID
*/
public long getId() {
return mId;
}
/**
* ID
* @return ID
*/
public long getParentId() {
return mParentId;
}
/**
*
* @return
*/
public String getSnippet() {
return mSnippet;
}
/**
*
* @return truefalse
*/
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)) {
mDiffNoteValues.remove(NoteColumns.ID);
mDiffNoteValues.remove(NoteColumns.ID); // 如果ID为无效值且存在于更新字段中移除它
}
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); // 插入新笔记到数据库
try {
mId = Long.valueOf(uri.getPathSegments().get(1));
mId = Long.valueOf(uri.getPathSegments().get(1)); // 从返回的URI中获取新笔记的ID
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
Log.e(TAG, "Get note id error :" + e.toString()); // 记录获取ID异常
throw new ActionFailureException("create note failed"); // 抛出创建失败异常
}
if (mId == 0) {
throw new IllegalStateException("Create thread id failed");
throw new IllegalStateException("Create thread id failed"); // 如果ID为0抛出异常
}
// 如果是普通笔记类型,提交笔记内容数据
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1);
sqlData.commit(mId, false, -1); // 提交内容数据,不验证版本
}
}
} else {
// 更新笔记操作
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");
Log.e(TAG, "No such note"); // 日志记录无效ID
throw new IllegalStateException("Try to update note with invalid id"); // 抛出无效ID异常
}
if (mDiffNoteValues.size() > 0) {
mVersion ++;
mVersion ++; // 版本号递增
int result = 0;
if (!validateVersion) {
// 不验证版本号,直接更新
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId)
String.valueOf(mId)
});
} else {
// 验证版本号,使用乐观锁控制
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] {
String.valueOf(mId), String.valueOf(mVersion)
});
}
if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing");
Log.w(TAG, "there is no update. maybe user updates note when syncing"); // 日志记录无更新
}
}
// 如果是普通笔记类型,提交笔记内容数据的更改
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion);
sqlData.commit(mId, validateVersion, mVersion); // 提交内容数据,可能验证版本
}
}
}
// refresh local info
// 重新从数据库加载笔记数据,确保对象状态与数据库一致
loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE)
loadDataContent();
loadDataContent(); // 重新加载笔记内容数据
mDiffNoteValues.clear();
mIsCreate = false;
mDiffNoteValues.clear(); // 清空更新字段容器
mIsCreate = false; // 标记为非新建状态
}
}
}

@ -31,65 +31,77 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Task -
*
* 便Node
* 便Google Tasks
* Google Tasks
*/
public class Task extends Node {
private static final String TAG = Task.class.getSimpleName();
private boolean mCompleted;
private String mNotes;
private JSONObject mMetaInfo;
private Task mPriorSibling;
private TaskList mParent;
private static final String TAG = Task.class.getSimpleName(); // 日志标签
// 任务特有属性
private boolean mCompleted; // 完成状态标记
private String mNotes; // 任务备注/描述
private JSONObject mMetaInfo; // 元信息(存储本地便签的详细信息)
private Task mPriorSibling; // 前一个兄弟任务(用于排序)
private TaskList mParent; // 父任务列表TaskList
/**
*
*/
public Task() {
super();
mCompleted = false;
mNotes = null;
mPriorSibling = null;
mParent = null;
mMetaInfo = null;
mCompleted = false; // 默认未完成
mNotes = null; // 默认无备注
mPriorSibling = null; // 默认无前兄弟任务
mParent = null; // 默认无父列表
mMetaInfo = null; // 默认无元信息
}
/**
* JSONGoogle Tasks
* @param actionId ID
* @return JSONObject
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
try {
// action_type
// 操作类型:创建
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id
// 操作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// index
// 索引位置(在父列表中的位置)
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
// entity_delta
// 实体数据变化
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务名称
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 创建者ID
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_TASK);
GTaskStringUtils.GTASK_JSON_TYPE_TASK); // 实体类型为任务
if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 任务备注
}
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
// parent_id
// 父列表ID
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
// dest_parent_type
// 目标父类型
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
// list_id
// 列表ID与父列表ID相同
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
// prior_sibling_id
// 前兄弟任务ID用于排序
if (mPriorSibling != null) {
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
}
@ -103,27 +115,33 @@ public class Task extends Node {
return js;
}
/**
* JSONGoogle Tasks
* @param actionId ID
* @return JSONObject
* @throws ActionFailureException 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
// 操作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id
// 任务ID
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta
// 实体数据变化
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
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());
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 删除状态
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) {
@ -135,35 +153,40 @@ public class Task extends Node {
return js;
}
/**
* JSONGoogle Tasks
* @param js JSONObject
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
// id
// 任务ID
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
}
// last_modified
// 最后修改时间
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
}
// name
// 任务名称
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
}
// notes
// 任务备注
if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
}
// deleted
// 删除状态
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
}
// completed
// 完成状态
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
}
@ -175,6 +198,10 @@ public class Task extends Node {
}
}
/**
* JSON
* @param js 便JSONObject
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
@ -182,18 +209,21 @@ public class Task extends Node {
}
try {
// 获取便签信息和数据数组
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 验证便签类型
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type");
return;
}
// 遍历数据数组,查找便签内容
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT));
setName(data.getString(DataColumns.CONTENT)); // 设置任务名称为便签内容
break;
}
}
@ -204,31 +234,37 @@ public class Task extends Node {
}
}
/**
* JSON
* @return 便JSONObjectnull
*/
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
if (mMetaInfo == null) {
// new task created from web
// 从Web新创建的任务没有元信息
if (name == null) {
Log.w(TAG, "the note seems to be an empty one");
return null;
}
// 构建新的JSON结构
JSONObject js = new JSONObject();
JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject();
data.put(DataColumns.CONTENT, name);
data.put(DataColumns.CONTENT, name); // 便签内容
dataArray.put(data);
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 类型为普通便签
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
return js;
} else {
// synced task
// 已同步的任务(有元信息)
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 更新便签内容
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
@ -238,7 +274,7 @@ public class Task extends Node {
}
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
return mMetaInfo;
return mMetaInfo; // 返回更新后的元信息
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
@ -247,6 +283,10 @@ public class Task extends Node {
}
}
/**
* MetaData
* @param metaData
*/
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
@ -258,48 +298,57 @@ public class Task extends Node {
}
}
/**
*
* @param c Cursor
* @return SYNC_ACTION_*
*/
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
// 从元信息中获取便签信息
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
}
if (noteInfo == null) {
Log.w(TAG, "it seems that note meta has been deleted");
return SYNC_ACTION_UPDATE_REMOTE;
return SYNC_ACTION_UPDATE_REMOTE; // 远程更新本地
}
if (!noteInfo.has(NoteColumns.ID)) {
Log.w(TAG, "remote note id seems to be deleted");
return SYNC_ACTION_UPDATE_LOCAL;
return SYNC_ACTION_UPDATE_LOCAL; // 本地更新远程
}
// validate the note id now
// 验证便签ID是否匹配
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
Log.w(TAG, "note id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL;
return SYNC_ACTION_UPDATE_LOCAL; // ID不匹配用本地更新远程
}
// 检查本地修改标记
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update
// 本地无修改
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side
// 两边都无更新
return SYNC_ACTION_NONE;
} else {
// apply remote to local
// 远程有更新,应用到本地
return SYNC_ACTION_UPDATE_LOCAL;
}
} else {
// validate gtask id
// 本地有修改
// 验证Google Task ID是否匹配
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
return SYNC_ACTION_ERROR; // ID不匹配错误
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
// 仅本地有修改
return SYNC_ACTION_UPDATE_REMOTE;
} else {
// 两边都有修改,冲突
return SYNC_ACTION_UPDATE_CONFLICT;
}
}
@ -308,44 +357,79 @@ public class Task extends Node {
e.printStackTrace();
}
return SYNC_ACTION_ERROR;
return SYNC_ACTION_ERROR; // 发生异常,返回错误
}
/**
*
* @return truefalse
*/
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);
}
/**
*
* @param completed true-false-
*/
public void setCompleted(boolean completed) {
this.mCompleted = completed;
}
/**
*
* @param notes
*/
public void setNotes(String notes) {
this.mNotes = notes;
}
/**
*
* @param priorSibling
*/
public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling;
}
/**
*
* @param parent
*/
public void setParent(TaskList parent) {
this.mParent = parent;
}
/**
*
* @return true-false-
*/
public boolean getCompleted() {
return this.mCompleted;
}
/**
*
* @return
*/
public String getNotes() {
return this.mNotes;
}
/**
*
* @return
*/
public Task getPriorSibling() {
return this.mPriorSibling;
}
/**
*
* @return
*/
public TaskList getParent() {
return this.mParent;
}
}
}

@ -29,40 +29,54 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* TaskList -
*
* Google Tasks便
* NodeTask
* Google Tasks
*/
public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();
private static final String TAG = TaskList.class.getSimpleName(); // 日志标签
private int mIndex;
private ArrayList<Task> mChildren;
private int mIndex; // 任务列表在父容器中的索引位置
private ArrayList<Task> mChildren; // 子任务列表
/**
*
*/
public TaskList() {
super();
mChildren = new ArrayList<Task>();
mIndex = 1;
mChildren = new ArrayList<Task>(); // 初始化子任务列表
mIndex = 1; // 默认索引为1Google Tasks的索引从1开始
}
/**
* JSONGoogle Tasks
* @param actionId ID
* @return JSONObject
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
try {
// action_type
// 操作类型:创建
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id
// 操作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// index
// 索引位置
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
// entity_delta
// 实体数据变化
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 列表名称
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 创建者ID
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); // 实体类型为组(列表)
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) {
@ -74,24 +88,30 @@ public class TaskList extends Node {
return js;
}
/**
* JSONGoogle Tasks
* @param actionId ID
* @return JSONObject
* @throws ActionFailureException 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
// 操作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id
// 列表ID
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta
// 实体数据变化
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 列表名称
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 删除状态
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) {
@ -103,20 +123,25 @@ public class TaskList extends Node {
return js;
}
/**
* JSONGoogle Tasks
* @param js JSONObject
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
// id
// 列表ID
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
}
// last_modified
// 最后修改时间
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
}
// name
// 列表名称
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
}
@ -129,6 +154,10 @@ public class TaskList extends Node {
}
}
/**
* JSON
* @param js JSONObject
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
@ -137,10 +166,13 @@ public class TaskList extends Node {
try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
// 根据文件夹类型设置名称
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// 普通文件夹使用片段作为名称并添加MIUI前缀
String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
// 系统文件夹根据ID设置特定的名称
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
@ -157,21 +189,28 @@ public class TaskList extends Node {
}
}
/**
* JSON
* @return JSONObject
*/
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();
JSONObject folder = new JSONObject();
// 处理文件夹名称移除MIUI前缀
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);
// 根据文件夹名称判断类型
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); // 默认文件夹和通话记录文件夹为系统类型
else
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); // 其他为普通文件夹
js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
@ -183,28 +222,34 @@ public class TaskList extends Node {
}
}
/**
*
* @param c Cursor
* @return SYNC_ACTION_*
*/
public int getSyncAction(Cursor c) {
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update
// 本地无修改
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side
// 两边都无更新
return SYNC_ACTION_NONE;
} else {
// apply remote to local
// 远程有更新,应用到本地
return SYNC_ACTION_UPDATE_LOCAL;
}
} else {
// validate gtask id
// 本地有修改
// 验证Google Task ID是否匹配
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
// 仅本地有修改
return SYNC_ACTION_UPDATE_REMOTE;
} else {
// for folder conflicts, just apply local modification
// 文件夹冲突时,优先应用本地修改(不同于任务的处理方式)
return SYNC_ACTION_UPDATE_REMOTE;
}
}
@ -216,16 +261,25 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR;
}
/**
*
* @return
*/
public int getChildTaskCount() {
return mChildren.size();
}
/**
*
* @param task
* @return truefalse
*/
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task);
if (ret) {
// need to set prior sibling and parent
// 设置前兄弟任务和父列表
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1));
task.setParent(this);
@ -234,6 +288,12 @@ public class TaskList extends Node {
return ret;
}
/**
*
* @param task
* @param index
* @return truefalse
*/
public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index");
@ -244,7 +304,7 @@ public class TaskList extends Node {
if (task != null && pos == -1) {
mChildren.add(index, task);
// update the task list
// 更新任务列表的前后兄弟关系
Task preTask = null;
Task afterTask = null;
if (index != 0)
@ -260,6 +320,11 @@ public class TaskList extends Node {
return true;
}
/**
*
* @param task
* @return truefalse
*/
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
@ -267,11 +332,11 @@ public class TaskList extends Node {
ret = mChildren.remove(task);
if (ret) {
// reset prior sibling and parent
// 重置任务的前兄弟任务和父列表
task.setPriorSibling(null);
task.setParent(null);
// update the task list
// 更新任务列表的前兄弟关系
if (index != mChildren.size()) {
mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1));
@ -281,6 +346,12 @@ public class TaskList extends Node {
return ret;
}
/**
*
* @param task
* @param index
* @return truefalse
*/
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
@ -299,6 +370,11 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index));
}
/**
* Google Task ID
* @param gid Google Task
* @return null
*/
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@ -309,10 +385,20 @@ public class TaskList extends Node {
return null;
}
/**
*
* @param task
* @return -1
*/
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
/**
*
* @param index
* @return null
*/
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
@ -321,6 +407,11 @@ public class TaskList extends Node {
return mChildren.get(index);
}
/**
* Google Task ID
* @param gid Google Task
* @return null
*/
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
@ -329,15 +420,27 @@ public class TaskList extends Node {
return null;
}
/**
*
* @return ArrayList
*/
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}
/**
*
* @param index
*/
public void setIndex(int index) {
this.mIndex = index;
}
/**
*
* @return
*/
public int getIndex() {
return this.mIndex;
}
}
}

@ -16,18 +16,38 @@
package net.micode.notes.gtask.exception;
/**
* ActionFailureException -
*
* Google Tasks
* RuntimeException
* JSON
*/
public class ActionFailureException extends RuntimeException {
// 序列化版本UID用于对象序列化/反序列化的版本控制
private static final long serialVersionUID = 4425249765923293627L;
/**
*
*/
public ActionFailureException() {
super();
}
/**
*
* @param paramString
*/
public ActionFailureException(String paramString) {
super(paramString);
}
/**
*
* @param paramString
* @param paramThrowable
*/
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
}
}

@ -16,18 +16,38 @@
package net.micode.notes.gtask.exception;
/**
* NetworkFailureException -
*
* Google Tasks
* Exception
*
*/
public class NetworkFailureException extends Exception {
// 序列化版本UID用于对象序列化/反序列化的版本控制
private static final long serialVersionUID = 2107610287180234136L;
/**
*
*/
public NetworkFailureException() {
super();
}
/**
*
* @param paramString
*/
public NetworkFailureException(String paramString) {
super(paramString);
}
/**
*
* @param paramString
* @param paramThrowable
*/
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
}
}

@ -1,4 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
@ -28,23 +27,39 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
* GTaskASyncTask - Google Tasks
*
* Google TasksAsyncTask
* AsyncTask
* GTaskManager
*/
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;
private Context mContext; // Android上下文
private NotificationManager mNotifiManager; // 通知管理器,用于显示同步通知
private GTaskManager mTaskManager; // Google Tasks管理器执行具体同步操作
private OnCompleteListener mOnCompleteListener; // 同步完成监听器
/**
*
* @param context Android
* @param listener
*/
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
@ -53,71 +68,112 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager = GTaskManager.getInstance();
}
/**
*
*/
public void cancelSync() {
mTaskManager.cancelSync();
}
/**
*
* @param message
*/
public void publishProgess(String message) {
publishProgress(new String[] {
message
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.defaults = Notification.DEFAULT_LIGHTS;
notification.flags = Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent;
// 根据同步状态设置不同的点击意图
if (tickerId != R.string.ticker_success) {
// 同步失败或进行中,点击跳转到设置页面
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);
NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE);
} else {
// 同步成功,点击跳转到便签列表页面
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE);
}
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);
// 构建通知(使用兼容性方式)
Notification.Builder builder = new Notification.Builder(mContext)
.setAutoCancel(true)
.setContentTitle(mContext.getString(R.string.app_name))
.setContentText(content)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setOngoing(true);
Notification notification=builder.getNotification();
// 显示通知
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
/**
*
* @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);
}
/**
* 线
* @param progress
*/
@Override
protected void onProgressUpdate(String... progress) {
// 显示同步中的通知
showNotification(R.string.ticker_syncing, progress[0]);
// 如果是通过服务调用的,发送广播通知进度
if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]);
}
}
/**
* 线
* @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()));
// 记录最后同步时间
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));
}
// 执行完成回调(在新线程中执行,避免阻塞主线程)
if (mOnCompleteListener != null) {
new Thread(new Runnable() {
public void run() {
mOnCompleteListener.onComplete();
}
}).start();
}
}
}
}

@ -60,36 +60,33 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
* GTaskGoogle Tasks API
*
*/
public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName();
private static final String TAG = GTaskClient.class.getSimpleName(); // 日志标签
// Google Tasks API的URL地址
private static final String GTASK_URL = "https://mail.google.com/tasks/";
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 String mGetUrl;
private String mPostUrl;
private long mClientVersion;
private boolean mLoggedin;
private long mLastLoginTime;
private int mActionId;
private Account mAccount;
private JSONArray mUpdateArray;
private static GTaskClient mInstance = null; // 单例实例
private DefaultHttpClient mHttpClient; // HTTP客户端
private String mGetUrl; // GET请求URL
private String mPostUrl; // POST请求URL
private long mClientVersion; // 客户端版本
private boolean mLoggedin; // 登录状态
private long mLastLoginTime; // 最后登录时间
private int mActionId; // 动作ID计数器
private Account mAccount; // Google账户
private JSONArray mUpdateArray; // 待提交的更新操作数组
/**
*
*/
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
@ -102,6 +99,10 @@ public class GTaskClient {
mUpdateArray = null;
}
/**
* GTaskClient
* @return GTaskClient
*/
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -109,18 +110,22 @@ public class GTaskClient {
return mInstance;
}
/**
* Google Tasks
* @param activity Activity
* @return
*/
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))) {
.getSyncAccountName(activity))) {
mLoggedin = false;
}
@ -136,7 +141,7 @@ public class GTaskClient {
return false;
}
// login with custom domain if necessary
// 如果是自定义域名尝试使用自定义URL登录
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
@ -151,7 +156,7 @@ public class GTaskClient {
}
}
// try to login with google official url
// 如果自定义域名登录失败尝试使用Google官方URL登录
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
@ -164,6 +169,12 @@ public class GTaskClient {
return true;
}
/**
* Google
* @param activity Activity
* @param invalidateToken 使
* @return null
*/
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
@ -189,7 +200,7 @@ public class GTaskClient {
return null;
}
// get the token now
// 获取授权令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
@ -207,10 +218,15 @@ public class GTaskClient {
return authToken;
}
/**
* Google Tasks
* @param activity Activity
* @param authToken
* @return
*/
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the
// token and try again
// 令牌可能过期,尝试刷新令牌后重新登录
authToken = loginGoogleAccount(activity, true);
if (authToken == null) {
Log.e(TAG, "login google account failed");
@ -225,6 +241,11 @@ public class GTaskClient {
return true;
}
/**
* 使Google Tasks
* @param authToken
* @return
*/
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000;
@ -236,14 +257,14 @@ public class GTaskClient {
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
// 登录Google Tasks
try {
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the cookie now
// 获取Cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
@ -255,7 +276,7 @@ public class GTaskClient {
Log.w(TAG, "it seems that there is no auth cookie");
}
// get the client version
// 获取客户端版本
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -272,7 +293,6 @@ public class GTaskClient {
e.printStackTrace();
return false;
} catch (Exception e) {
// simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed");
return false;
}
@ -280,10 +300,18 @@ public class GTaskClient {
return true;
}
/**
* ID
* @return ID
*/
private int getActionId() {
return mActionId++;
}
/**
* HTTP POST
* @return HttpPost
*/
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -291,6 +319,12 @@ public class GTaskClient {
return httpPost;
}
/**
* HTTP
* @param entity HTTP
* @return
* @throws IOException
*/
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
@ -323,6 +357,12 @@ public class GTaskClient {
}
}
/**
* POSTGoogle Tasks API
* @param js JSON
* @return JSON
* @throws NetworkFailureException
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -336,7 +376,7 @@ public class GTaskClient {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
// execute the post
// 执行POST请求
HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
@ -360,20 +400,25 @@ public class GTaskClient {
}
}
/**
*
* @param task
* @throws NetworkFailureException
*/
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);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -386,20 +431,25 @@ public class GTaskClient {
}
}
/**
*
* @param tasklist
* @throws NetworkFailureException
*/
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);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -412,15 +462,19 @@ public class GTaskClient {
}
}
/**
*
* @throws NetworkFailureException
*/
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);
@ -433,10 +487,14 @@ public class GTaskClient {
}
}
/**
*
* @param node
* @throws NetworkFailureException
*/
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 +505,13 @@ public class GTaskClient {
}
}
/**
*
* @param task
* @param preParent
* @param curParent
* @throws NetworkFailureException
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
commitUpdate();
@ -455,26 +520,25 @@ public class GTaskClient {
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
// 构建移动动作
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and
// it is not the first one
// 只有同一任务列表内移动且不是第一个时才需要前驱兄弟ID
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
// 只有在不同任务列表间移动时才需要目标列表ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
@ -486,18 +550,23 @@ public class GTaskClient {
}
}
/**
*
* @param node
* @throws NetworkFailureException
*/
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
// 添加删除动作
node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
@ -509,6 +578,11 @@ public class GTaskClient {
}
}
/**
*
* @return JSON
* @throws NetworkFailureException
*/
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -520,7 +594,7 @@ public class GTaskClient {
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the task list
// 解析响应,提取任务列表数据
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -547,6 +621,12 @@ public class GTaskClient {
}
}
/**
*
* @param listGid ID
* @return JSON
* @throws NetworkFailureException
*/
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
try {
@ -554,7 +634,7 @@ public class GTaskClient {
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
// 构建获取所有任务的动作
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
@ -563,7 +643,7 @@ public class GTaskClient {
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);
@ -575,11 +655,18 @@ public class GTaskClient {
}
}
/**
*
* @return Google
*/
public Account getSyncAccount() {
return mAccount;
}
/**
*
*/
public void resetUpdateArray() {
mUpdateArray = null;
}
}
}

@ -47,46 +47,43 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
/**
* Google Tasks
* Google Tasks
*
*/
public class GTaskManager {
private static final String TAG = GTaskManager.class.getSimpleName();
public static final int STATE_SUCCESS = 0;
public static final int STATE_NETWORK_ERROR = 1;
public static final int STATE_INTERNAL_ERROR = 2;
public static final int STATE_SYNC_IN_PROGRESS = 3;
public static final int STATE_SYNC_CANCELLED = 4;
private static GTaskManager mInstance = null;
private static final String TAG = GTaskManager.class.getSimpleName(); // 日志标签
private Activity mActivity;
// 同步状态常量
public static final int STATE_SUCCESS = 0; // 同步成功
public static final int STATE_NETWORK_ERROR = 1; // 网络错误
public static final int STATE_INTERNAL_ERROR = 2; // 内部错误
public static final int STATE_SYNC_IN_PROGRESS = 3; // 同步正在进行中
public static final int STATE_SYNC_CANCELLED = 4; // 同步已取消
private Context mContext;
private static GTaskManager mInstance = null; // 单例实例
private ContentResolver mContentResolver;
private Activity mActivity; // 当前Activity
private Context mContext; // 应用上下文
private ContentResolver mContentResolver; // 内容解析器
private boolean mSyncing;
private boolean mSyncing; // 同步进行标志
private boolean mCancelled; // 同步取消标志
private boolean mCancelled;
// 数据映射存储
private HashMap<String, TaskList> mGTaskListHashMap; // Google任务列表映射GID -> TaskList
private HashMap<String, Node> mGTaskHashMap; // Google任务节点映射GID -> Node
private HashMap<String, MetaData> mMetaHashMap; // 元数据映射相关GID -> MetaData
private TaskList mMetaList; // 元数据任务列表
private HashMap<String, TaskList> mGTaskListHashMap;
private HashMap<String, Node> mGTaskHashMap;
private HashMap<String, MetaData> mMetaHashMap;
private TaskList mMetaList;
private HashSet<Long> mLocalDeleteIdMap;
private HashMap<String, Long> mGidToNid;
private HashMap<Long, String> mNidToGid;
private HashSet<Long> mLocalDeleteIdMap; // 本地待删除ID集合
private HashMap<String, Long> mGidToNid; // GID到本地ID的映射
private HashMap<Long, String> mNidToGid; // 本地ID到GID的映射
/**
*
*/
private GTaskManager() {
mSyncing = false;
mCancelled = false;
@ -99,6 +96,10 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>();
}
/**
* GTaskManager
* @return GTaskManager
*/
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@ -106,11 +107,20 @@ public class GTaskManager {
return mInstance;
}
/**
* Activity
* @param activity Activity
*/
public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
mActivity = activity;
}
/**
* Google Tasks
* @param context
* @param asyncTask
* @return
*/
public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
@ -120,6 +130,8 @@ public class GTaskManager {
mContentResolver = mContext.getContentResolver();
mSyncing = true;
mCancelled = false;
// 清理旧数据
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
@ -131,18 +143,18 @@ public class GTaskManager {
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
// login google task
// 登录Google Tasks
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed");
}
}
// get the task list from google
// 从Google获取任务列表
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList();
// do content sync work
// 执行内容同步
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent();
} catch (NetworkFailureException e) {
@ -156,6 +168,7 @@ public class GTaskManager {
e.printStackTrace();
return STATE_INTERNAL_ERROR;
} finally {
// 清理数据,无论成功与否
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
@ -168,6 +181,11 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
/**
* Google
* Google Tasks
* @throws NetworkFailureException
*/
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
@ -175,19 +193,19 @@ public class GTaskManager {
try {
JSONArray jsTaskLists = client.getTaskLists();
// init meta list first
// 首先初始化元数据列表
mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
// 查找元数据文件夹
if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object);
// load meta data
// 加载元数据任务
JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j);
@ -203,7 +221,7 @@ public class GTaskManager {
}
}
// create meta list if not existed
// 如果元数据列表不存在,则创建
if (mMetaList == null) {
mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
@ -211,21 +229,22 @@ public class GTaskManager {
GTaskClient.getInstance().createTaskList(mMetaList);
}
// init task list
// 初始化任务列表
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
// 只处理MIUI前缀的文件夹排除元数据文件夹
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) {
+ GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist);
// load tasks
// 加载该任务列表下的任务
JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j);
@ -247,6 +266,11 @@ public class GTaskManager {
}
}
/**
*
* Google Tasks
* @throws NetworkFailureException
*/
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;
@ -259,7 +283,7 @@ public class GTaskManager {
return;
}
// for local deleted note
// 处理本地已删除的笔记(在回收站中的笔记)
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] {
@ -286,10 +310,10 @@ public class GTaskManager {
}
}
// sync folder first
// 首先同步文件夹
syncFolder();
// for note existing in database
// 处理数据库中已存在的笔记
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
@ -306,10 +330,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
// 本地新增的笔记
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
// Google Tasks中已删除的笔记
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
@ -326,7 +350,7 @@ public class GTaskManager {
}
}
// go through remaining items
// 处理剩余的Google Tasks项本地不存在但Google Tasks中存在的项
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
@ -334,16 +358,15 @@ public class GTaskManager {
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
// mCancelled can be set by another thread, so we neet to check one by
// one
// clear local delete table
// 检查是否被取消,逐项检查
// 清理本地删除表
if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes");
}
}
// refresh local sync id
// 刷新本地同步ID
if (!mCancelled) {
GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId();
@ -351,6 +374,10 @@ public class GTaskManager {
}
/**
*
* @throws NetworkFailureException
*/
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
@ -361,7 +388,7 @@ public class GTaskManager {
return;
}
// for root folder
// 同步根文件夹
try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
@ -373,7 +400,7 @@ public class GTaskManager {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
// for system folder, only update remote name if necessary
// 对于系统文件夹,只有在必要时才更新远程名称
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
@ -390,11 +417,11 @@ public class GTaskManager {
}
}
// for call-note folder
// 同步通话记录文件夹
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
}, null);
if (c != null) {
if (c.moveToNext()) {
@ -404,8 +431,7 @@ public class GTaskManager {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if
// necessary
// 对于系统文件夹,只有在必要时才更新远程名称
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE))
@ -424,7 +450,7 @@ public class GTaskManager {
}
}
// for local existing folders
// 处理本地已存在的文件夹
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
@ -441,10 +467,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
// 本地新增的文件夹
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
// Google Tasks中已删除的文件夹
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
@ -460,7 +486,7 @@ public class GTaskManager {
}
}
// for remote add folders
// 处理Google Tasks中新增的文件夹
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
@ -476,6 +502,13 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate();
}
/**
*
* @param syncType
* @param node Google Tasks
* @param c
* @throws NetworkFailureException
*/
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -484,12 +517,15 @@ public class GTaskManager {
MetaData meta;
switch (syncType) {
case Node.SYNC_ACTION_ADD_LOCAL:
// 在本地添加节点
addLocalNode(node);
break;
case Node.SYNC_ACTION_ADD_REMOTE:
// 在Google Tasks添加节点
addRemoteNode(node, c);
break;
case Node.SYNC_ACTION_DEL_LOCAL:
// 删除本地节点
meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN));
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta);
@ -497,6 +533,7 @@ public class GTaskManager {
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
break;
case Node.SYNC_ACTION_DEL_REMOTE:
// 删除Google Tasks节点
meta = mMetaHashMap.get(node.getGid());
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta);
@ -504,17 +541,19 @@ public class GTaskManager {
GTaskClient.getInstance().deleteNode(node);
break;
case Node.SYNC_ACTION_UPDATE_LOCAL:
// 更新本地节点
updateLocalNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_REMOTE:
// 更新Google Tasks节点
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea
// right now just use local update simply
// 冲突处理:目前简单使用本地更新
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_NONE:
// 无需同步
break;
case Node.SYNC_ACTION_ERROR:
default:
@ -522,6 +561,11 @@ public class GTaskManager {
}
}
/**
* Google Tasks
* @param node Google Tasks
* @throws NetworkFailureException
*/
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
@ -529,6 +573,7 @@ public class GTaskManager {
SqlNote sqlNote;
if (node instanceof TaskList) {
// 处理文件夹节点
if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
@ -541,20 +586,23 @@ public class GTaskManager {
sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
}
} else {
// 处理笔记节点
sqlNote = new SqlNote(mContext);
JSONObject js = node.getLocalJSONFromContent();
try {
// 检查笔记ID是否可用
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// the id is not available, have to create a new one
// ID不可用需要创建新ID
note.remove(NoteColumns.ID);
}
}
}
// 检查数据ID是否可用
if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
for (int i = 0; i < dataArray.length(); i++) {
@ -562,8 +610,7 @@ public class GTaskManager {
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// the data id is not available, have to create
// a new one
// 数据ID不可用需要创建新ID
data.remove(DataColumns.ID);
}
}
@ -584,25 +631,31 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue());
}
// create the local node
// 创建本地节点
sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false);
// update gid-nid mapping
// 更新GID-NID映射
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta
// 更新元数据
updateRemoteMeta(node.getGid(), sqlNote);
}
/**
* 使Google Tasks
* @param node Google Tasks
* @param c
* @throws NetworkFailureException
*/
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote;
// update the note locally
// 更新本地笔记
sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent());
@ -615,10 +668,16 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true);
// update meta info
// 更新元数据信息
updateRemoteMeta(node.getGid(), sqlNote);
}
/**
* Google Tasks
* @param node Google Tasksnull
* @param c
* @throws NetworkFailureException
*/
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -627,8 +686,9 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c);
Node n;
// update remotely
// 在Google Tasks中创建
if (sqlNote.isNoteType()) {
// 创建任务
Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent());
@ -642,12 +702,13 @@ public class GTaskManager {
GTaskClient.getInstance().createTask(task);
n = (Node) task;
// add meta
// 添加元数据
updateRemoteMeta(task.getGid(), sqlNote);
} else {
// 创建任务列表(文件夹)
TaskList tasklist = null;
// we need to skip folder if it has already existed
// 如果文件夹已存在,则跳过
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT;
@ -671,7 +732,7 @@ public class GTaskManager {
}
}
// no match we can add now
// 没有匹配项,现在创建
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
@ -681,17 +742,23 @@ public class GTaskManager {
n = (Node) tasklist;
}
// update local note
// 更新本地笔记
sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false);
sqlNote.resetLocalModified();
sqlNote.commit(true);
// gid-id mapping
// 更新GID-ID映射
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
/**
* 使Google Tasks
* @param node Google Tasks
* @param c
* @throws NetworkFailureException
*/
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -699,14 +766,14 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely
// 更新Google Tasks
node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node);
// update meta
// 更新元数据
updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary
// 如果需要,移动任务
if (sqlNote.isNoteType()) {
Task task = (Task) node;
TaskList preParentList = task.getParent();
@ -725,11 +792,17 @@ public class GTaskManager {
}
}
// clear local modified flag
// 清除本地修改标志
sqlNote.resetLocalModified();
sqlNote.commit(true);
}
/**
*
* @param gid Google Tasks ID
* @param sqlNote
* @throws NetworkFailureException
*/
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
@ -746,12 +819,17 @@ public class GTaskManager {
}
}
/**
* ID
* Google Tasks
* @throws NetworkFailureException
*/
private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) {
return;
}
// get the latest gtask list
// 获取最新的Google Tasks列表
mGTaskHashMap.clear();
mGTaskListHashMap.clear();
mMetaHashMap.clear();
@ -790,11 +868,18 @@ public class GTaskManager {
}
}
/**
*
* @return
*/
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}
/**
*
*/
public void cancelSync() {
mCancelled = true;
}
}
}

@ -23,25 +23,25 @@ import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
/**
* GTaskSyncService - Google Tasks
*/
public class GTaskSyncService extends Service {
public final static String ACTION_STRING_NAME = "sync_action_type";
public final static int ACTION_START_SYNC = 0;
public final static int ACTION_CANCEL_SYNC = 1;
public final static int ACTION_INVALID = 2;
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
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 String mSyncProgress = "";
/**
*
*/
private void startSync() {
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -56,6 +56,9 @@ public class GTaskSyncService extends Service {
}
}
/**
*
*/
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
@ -97,6 +100,9 @@ public class GTaskSyncService extends Service {
return null;
}
/**
* 广
*/
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -105,6 +111,9 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent);
}
/**
*
*/
public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
@ -112,6 +121,9 @@ public class GTaskSyncService extends Service {
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);
@ -125,4 +137,4 @@ public class GTaskSyncService extends Service {
public static String getProgressString() {
return mSyncProgress;
}
}
}

@ -13,8 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.model;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
@ -33,16 +33,19 @@ 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
*/
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);
@ -50,6 +53,7 @@ public class Note {
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
long noteId = 0;
@ -59,6 +63,7 @@ public class Note {
Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0;
}
if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId);
}
@ -70,11 +75,36 @@ public class Note {
mNoteData = new NoteData();
}
/**
* 便
*/
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
public void setNoteValue(String key, int value) {
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
* 便
* @param isPinned truefalse
*/
public void setPinned(boolean isPinned) {
setNoteValue(NoteColumns.PINNED, isPinned ? 1 : 0);
}
/**
* 便
* @return 10
*/
public Integer getPinned() {
return mNoteDiffValues.getAsInteger(NoteColumns.PINNED);
}
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
@ -96,10 +126,16 @@ public class Note {
mNoteData.setCallData(key, value);
}
/**
* 便
*/
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
/**
* 便
*/
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -109,16 +145,10 @@ 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) {
Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through
}
mNoteDiffValues.clear();
@ -130,15 +160,15 @@ public class Note {
return true;
}
/**
* NoteData - 便
* 便
*/
private class NoteData {
private long mTextDataId;
private ContentValues mTextDataValues;
private long mCallDataId;
private ContentValues mCallDataValues;
private static final String TAG = "NoteData";
public NoteData() {
@ -178,10 +208,10 @@ public class Note {
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
* ContentResolver
*/
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety
*/
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
@ -250,4 +280,4 @@ public class Note {
return null;
}
}
}
}

@ -31,37 +31,29 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
* WorkingNote - 便
* 便Note
*/
public class WorkingNote {
// Note for the working note
private Note mNote;
// Note Id
private long mNoteId;
// Note content
private String mContent;
// Note mode
private String mTitle; // 便签标题
private int mMode;
private long mAlertDate;
private long mModifiedDate;
private int mBgColorId;
private int mWidgetId;
private int mWidgetType;
private long mFolderId;
private Context mContext;
private static final String TAG = "WorkingNote";
private boolean mIsDeleted;
private boolean mIsPinned;
private NoteSettingChangedListener mNoteSettingStatusListener;
// 数据表查询投影列
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
@ -72,36 +64,33 @@ public class WorkingNote {
DataColumns.DATA4,
};
// 便签表查询投影列
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
NoteColumns.MODIFIED_DATE
NoteColumns.MODIFIED_DATE,
NoteColumns.PINNED,
NoteColumns.TITLE
};
// 数据表投影列索引
private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3;
// 便签表投影列索引
private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
private static final int NOTE_WIDGET_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
private static final int NOTE_PINNED_COLUMN = 6;
private static final int NOTE_TITLE_COLUMN = 7;
// New note construct
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
@ -110,11 +99,12 @@ public class WorkingNote {
mNote = new Note();
mNoteId = 0;
mIsDeleted = false;
mIsPinned = false;
mMode = 0;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
mTitle = ""; // 初始化标题为空字符串
}
// Existing note construct
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
@ -124,6 +114,9 @@ public class WorkingNote {
loadNote();
}
/**
* 便
*/
private void loadNote() {
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
@ -137,6 +130,11 @@ public class WorkingNote {
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
mIsPinned = cursor.getInt(NOTE_PINNED_COLUMN) == 1;
// 读取便签标题
if (cursor.getColumnCount() > NOTE_TITLE_COLUMN) {
mTitle = cursor.getString(NOTE_TITLE_COLUMN);
}
}
cursor.close();
} else {
@ -146,10 +144,13 @@ public class WorkingNote {
loadNoteData();
}
/**
* 便
*/
private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
String.valueOf(mNoteId)
}, null);
if (cursor != null) {
@ -174,8 +175,11 @@ public class WorkingNote {
}
}
/**
* 便
*/
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId);
@ -183,10 +187,16 @@ public class WorkingNote {
return note;
}
/**
* 便
*/
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
/**
* 便
*/
public synchronized boolean saveNote() {
if (isWorthSaving()) {
if (!existInDatabase()) {
@ -198,9 +208,7 @@ public class WorkingNote {
mNote.syncNote(mContext, mNoteId);
/**
* Update widget content if there exist any widget of this note
*/
// 如果有关联的小部件,则更新小部件内容
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) {
@ -212,10 +220,16 @@ public class WorkingNote {
}
}
/**
* 便
*/
public boolean existInDatabase() {
return mNoteId > 0;
}
/**
* 便
*/
private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
@ -225,10 +239,16 @@ public class WorkingNote {
}
}
/**
* 便
*/
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}
/**
*
*/
public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) {
mAlertDate = date;
@ -239,14 +259,20 @@ public class WorkingNote {
}
}
/**
* 便
*/
public void markDeleted(boolean mark) {
mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
mNoteSettingStatusListener.onWidgetChanged();
}
}
/**
* ID
*/
public void setBgColorId(int id) {
if (id != mBgColorId) {
mBgColorId = id;
@ -257,6 +283,9 @@ public class WorkingNote {
}
}
/**
*
*/
public void setCheckListMode(int mode) {
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
@ -281,6 +310,9 @@ public class WorkingNote {
}
}
/**
* 便
*/
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
@ -288,6 +320,9 @@ public class WorkingNote {
}
}
/**
* 便便
*/
public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
@ -297,6 +332,21 @@ public class WorkingNote {
public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false);
}
/**
* 便
*/
public boolean isPinned() {
return mIsPinned;
}
/**
* 便
*/
public void setPinned(boolean isPinned) {
mIsPinned = isPinned;
mNote.setPinned(isPinned);
}
public String getContent() {
return mContent;
@ -342,27 +392,30 @@ public class WorkingNote {
return mWidgetType;
}
/**
* 便
*/
public String getTitle() {
return mTitle;
}
/**
* 便
*/
public void setTitle(String title) {
if (!TextUtils.equals(mTitle, title)) {
mTitle = title;
mNote.setNoteValue(NoteColumns.TITLE, title);
}
}
/**
* 便
*/
public interface NoteSettingChangedListener {
/**
* Called when the background color of current note has just changed
*/
void onBackgroundColorChanged();
/**
* Called when user set clock
*/
void onClockAlertChanged(long date, boolean set);
/**
* Call when user create note from widget
*/
void onWidgetChanged();
/**
* Call when switch between check list mode and normal mode
* @param oldMode is previous mode before change
* @param newMode is new mode
*/
void onCheckListModeChanged(int oldMode, int newMode);
}
}
}

@ -35,12 +35,32 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/**
*
*
* 便
* 1. 便SD
* 2.
* 3. 便便
* 4.
*
*
* - 使
* - TextExport
* - 便UI
*/
public class BackupUtils {
private static final String TAG = "BackupUtils";
private static final String TAG = "BackupUtils"; // 日志标签
// Singleton stuff
private static BackupUtils sInstance;
private static BackupUtils sInstance; // 单例实例
/**
* BackupUtils
* 使线
*
* @param context
* @return BackupUtils
*/
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
@ -49,82 +69,117 @@ public class BackupUtils {
}
/**
* Following states are signs to represents backup or restore
* status
*
*/
// Currently, the sdcard is not mounted
// 当前SD卡未挂载
public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist
// 备份文件不存在
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs
// 数据格式被破坏,可能被其他程序修改
public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails
// 运行时异常导致备份或恢复失败
public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success
// 备份或恢复成功
public static final int STATE_SUCCESS = 4;
private TextExport mTextExport;
private TextExport mTextExport; // 文本导出器实例
/**
*
*
* @param context
*/
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}
/**
*
*
* @return trueSDfalse
*/
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
/**
* 便
*
* @return
*/
public int exportToText() {
return mTextExport.exportToText();
}
/**
*
*
* @return
*/
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
/**
*
*
* @return
*/
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
/**
*
*
*
* 1. 便
* 2.
* 3.
*/
private static class TextExport {
// 便签表的查询投影列
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,
NoteColumns.TYPE
NoteColumns.ID, // 0: 便签ID
NoteColumns.MODIFIED_DATE, // 1: 修改日期
NoteColumns.SNIPPET, // 2: 便签片段(用于文件夹名)
NoteColumns.TYPE // 3: 便签类型
};
private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2;
private static final int NOTE_COLUMN_ID = 0; // 便签ID列索引
private static final int NOTE_COLUMN_MODIFIED_DATE = 1; // 修改日期列索引
private static final int NOTE_COLUMN_SNIPPET = 2; // 便签片段列索引
// 数据表的查询投影列
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
DataColumns.CONTENT, // 0: 数据内容
DataColumns.MIME_TYPE, // 1: MIME类型
DataColumns.DATA1, // 2: 数据1通话记录的通话日期
DataColumns.DATA2, // 3: 数据2
DataColumns.DATA3, // 4: 数据3
DataColumns.DATA4, // 5: 数据4通话记录的电话号码
};
private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
private static final int DATA_COLUMN_CONTENT = 0; // 内容列索引
private static final int DATA_COLUMN_MIME_TYPE = 1; // MIME类型列索引
private static final int DATA_COLUMN_CALL_DATE = 2; // 通话日期列索引
private static final int DATA_COLUMN_PHONE_NUMBER = 4; // 电话号码列索引
// 文本格式化字符串数组,从资源文件中加载
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 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; // 导出的文件目录
/**
*
*
* @param context
*/
public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
@ -132,28 +187,37 @@ public class BackupUtils {
mFileDirectory = "";
}
/**
*
*
* @param id IDFORMAT_FOLDER_NAME, FORMAT_NOTE_DATE, FORMAT_NOTE_CONTENT
* @return
*/
private String getFormat(int id) {
return TEXT_FORMAT[id];
}
/**
* Export the folder identified by folder id to text
* 便
*
* @param folderId ID
* @param ps
*/
private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder
// 查询属于此文件夹的所有便签
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
folderId
}, null);
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
do {
// Print note's last modified date
// 打印便签的最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
// 查询属于此便签的数据
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext());
@ -163,12 +227,15 @@ public class BackupUtils {
}
/**
* Export note identified by id to a print stream
* 便
*
* @param noteId 便ID
* @param ps
*/
private void exportNoteToText(String noteId, PrintStream ps) {
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
noteId
}, null);
if (dataCursor != null) {
@ -176,25 +243,27 @@ public class BackupUtils {
do {
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);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
// 打印电话号码(如果存在)
if (!TextUtils.isEmpty(phoneNumber)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber));
}
// Print call date
// 打印通话日期
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm),
callDate)));
// Print call attachment location
// 打印通话附件位置(如果存在)
if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
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),
@ -205,7 +274,7 @@ public class BackupUtils {
}
dataCursor.close();
}
// print a line separator between note
// 在便签之间打印一个行分隔符
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -216,20 +285,26 @@ public class BackupUtils {
}
/**
* Note will be exported as text which is user readable
* 便
*
* @return
*/
public int exportToText() {
// 检查SD卡是否可用
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
}
// 获取输出打印流
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
}
// First export folder and its notes
// 首先导出文件夹及其下的便签
// 查询所有文件夹(不包括回收站)和通话记录文件夹
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -240,7 +315,7 @@ public class BackupUtils {
if (folderCursor != null) {
if (folderCursor.moveToFirst()) {
do {
// Print folder's name
// 打印文件夹名称
String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
@ -257,7 +332,7 @@ public class BackupUtils {
folderCursor.close();
}
// Export notes in root's folder
// 导出根文件夹下的便签(不属于任何自定义文件夹的便签)
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -270,30 +345,33 @@ public class BackupUtils {
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
// 查询属于此便签的数据
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext());
}
noteCursor.close();
}
ps.close();
ps.close(); // 关闭输出流
return STATE_SUCCESS;
return STATE_SUCCESS; // 导出成功
}
/**
* Get a print stream pointed to the file {@generateExportedTextFile}
*
*
* @return null
*/
private PrintStream getExportToTextPrintStream() {
// 生成SD卡上的输出文件
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);
mFileName = file.getName(); // 保存文件名
mFileDirectory = mContext.getString(R.string.file_path); // 保存文件目录
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(file);
@ -310,23 +388,33 @@ public class BackupUtils {
}
/**
* Generate the text file to store imported data
* SD
*
* @param context
* @param filePathResId ID
* @param fileNameFormatResId ID
* @return Filenull
*/
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(Environment.getExternalStorageDirectory()); // SD卡根目录
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),
System.currentTimeMillis())));
File file = new File(sb.toString());
File file = new File(sb.toString()); // 完整文件对象
try {
// 创建目录(如果不存在)
if (!filedir.exists()) {
filedir.mkdir();
}
// 创建文件(如果不存在)
if (!file.exists()) {
file.createNewFile();
}
@ -337,8 +425,6 @@ public class BackupUtils {
e.printStackTrace();
}
return null;
return null; // 创建失败
}
}
}

@ -24,6 +24,7 @@ import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.data.Notes;
@ -33,25 +34,53 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*
* 便
* 1. 便
* 2. 便
* 3. 便
* 4.
*
*
* -
* - 使
* -
*/
public class DataUtils {
public static final String TAG = "DataUtils";
public static final String TAG = "DataUtils"; // 日志标签
/**
* 便
*
* 使applyBatch便
* 1.
* 2.
* 3. 使
*
* @param resolver 访ContentProvider
* @param ids 便IDnull
* @return truefalse
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
return true; // 空参数视为成功,无需操作
}
if (ids.size() == 0) {
Log.d(TAG, "no id is in the hashset");
return true;
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;
continue; // 跳过系统根文件夹,防止误删系统数据
}
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
@ -61,38 +90,164 @@ public class DataUtils {
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;
return false; // 批量操作返回结果异常
}
return true;
return true; // 删除成功
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false;
return false; // 异常情况
}
/**
*
*
*
* 1. 1
* 2. 1
* 3. 1
* 4.
*/
// 中文字符正则表达式
private static final Pattern CHINESE_CHAR_PATTERN = Pattern.compile("[\\u4e00-\\u9fa5]");
// 数字正则表达式
private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]");
// 英文字符正则表达式
private static final Pattern ENGLISH_CHAR_PATTERN = Pattern.compile("[a-zA-Z]");
/**
*
* @param text
* @return
*/
public static int getTotalWordCount(String text) {
if (TextUtils.isEmpty(text)) {
return 0;
}
int chineseCount = countChineseCharacters(text);
int numberCount = countNumbers(text);
int englishCount = countEnglishCharacters(text);
return chineseCount + numberCount + englishCount;
}
/**
*
* @param text
* @return
*/
private static int countChineseCharacters(String text) {
Matcher matcher = CHINESE_CHAR_PATTERN.matcher(text);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
/**
*
* @param text
* @return
*/
private static int countNumbers(String text) {
Matcher matcher = NUMBER_PATTERN.matcher(text);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
/**
*
* @param text
* @return
*/
private static int countEnglishCharacters(String text) {
Matcher matcher = ENGLISH_CHAR_PATTERN.matcher(text);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
/**
* 便
*
* 便IDID便
*
* @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
// 从回收站恢复时保留原始的ORIGIN_PARENT_ID以便递归恢复子项
if (desFolderId == Notes.ID_TRASH_FOLER) {
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 记录原始父文件夹,用于撤销
}
values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改,需要同步
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
}
/**
* 便
*
* 使便
* 1.
* 2. 使
* 3.
* 4. ID
*
* @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;
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);
// 如果是移动到回收站记录原始父文件夹ID
if (folderId == Notes.ID_TRASH_FOLER) {
// 首先查询当前父文件夹ID
Cursor cursor = resolver.query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id),
new String[]{NoteColumns.PARENT_ID},
null,
null,
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
long currentParentId = cursor.getLong(0);
// 保存原始父文件夹ID
builder.withValue(NoteColumns.ORIGIN_PARENT_ID, currentParentId);
}
cursor.close();
}
}
builder.withValue(NoteColumns.PARENT_ID, folderId); // 设置新父文件夹
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地修改
operationList.add(builder.build());
}
@ -110,9 +265,42 @@ public class DataUtils {
}
return false;
}
/**
* 便
*
* @param resolver
* @param folderId ID
* @return ID
*/
public static HashSet<Long> getFolderItems(ContentResolver resolver, long folderId) {
HashSet<Long> items = new HashSet<Long>();
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String[]{NoteColumns.ID},
NoteColumns.PARENT_ID + "=?",
new String[]{String.valueOf(folderId)},
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
long id = cursor.getLong(0);
items.add(id);
} while (cursor.moveToNext());
}
cursor.close();
}
return items;
}
/**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*
*
*
*
* @param resolver
* @return 0
*/
public static int getUserFolderCount(ContentResolver resolver) {
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
@ -136,7 +324,22 @@ public class DataUtils {
return count;
}
/**
* 便
*
* 便
*
* @param resolver
* @param noteId 便ID
* @param type 便Notes.TYPE_NOTENotes.TYPE_FOLDER
* @return true便false
*/
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
// 根文件夹永远可见
if (noteId == Notes.ID_ROOT_FOLDER) {
return true;
}
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
@ -153,6 +356,15 @@ public class DataUtils {
return exist;
}
/**
* 便
*
* 便ID
*
* @param resolver
* @param noteId 便ID
* @return true便IDfalse
*/
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 +379,15 @@ public class DataUtils {
return exist;
}
/**
*
*
* IDID
*
* @param resolver
* @param dataId ID
* @return trueIDfalse
*/
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 +402,20 @@ 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,6 +427,15 @@ 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 },
@ -224,6 +463,15 @@ 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 },
@ -240,14 +488,25 @@ public class DataUtils {
cursor.close();
}
}
return "";
return ""; // 未找到通话记录或查询失败
}
/**
* 便ID
*
*
* 使SQLPHONE_NUMBERS_EQUAL
*
* @param resolver
* @param phoneNumber
* @param callDate
* @return 便ID0
*/
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
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);
@ -261,9 +520,19 @@ public class DataUtils {
}
cursor.close();
}
return 0;
return 0; // 未找到匹配的通话记录
}
/**
* 便ID便snippet
*
* 便便
*
* @param resolver
* @param noteId 便ID
* @return 便
* @throws IllegalArgumentException 便ID
*/
public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
@ -282,14 +551,24 @@ public class DataUtils {
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
/**
* 便
*
* 便使UI
* 1.
* 2.
*
* @param snippet 便
* @return 便
*/
public static String getFormattedSnippet(String snippet) {
if (snippet != null) {
snippet = snippet.trim();
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,106 @@
package net.micode.notes.tool;
/**
* Google Tasks API
*
* Google Tasks API使JSON
*
* 1. Google Tasks API
* 2. MIUI便
* 3. API
*/
public class GTaskStringUtils {
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";
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";
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_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";
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";
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 GTASK_JSON_ACTION_ID = "action_id"; // 操作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"; // 更新操作类型
public final static String GTASK_JSON_CREATOR_ID = "creator_id"; // 创建者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"; // 完成状态标识
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"; // 默认列表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"; // 获取已删除项标识
public final static String GTASK_JSON_ID = "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"; // 最新同步点标识
public final static String GTASK_JSON_LIST_ID = "list_id"; // 列表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"; // 新ID标识
public final static String GTASK_JSON_NOTES = "notes"; // 备注标识
public final static String GTASK_JSON_PARENT_ID = "parent_id"; // 父级ID标识
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; // 前一个兄弟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便Google Tasks
*/
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
/**
*
* Google Tasks
*/
public final static String FOLDER_DEFAULT = "Default";
/**
*
* 便Google Tasks
*/
public final static String FOLDER_CALL_NOTE = "Call_Note";
/**
*
* 便
*/
public final static String FOLDER_META = "METADATA";
/**
* Google Tasks ID
* 便Google Tasks 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,38 +22,47 @@ import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
* ResourceParser -
* 便UI
*/
public class ResourceParser {
// 背景颜色ID常量
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;
// 字体大小ID常量
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;
/**
* NoteBgResources - 便
*/
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
};
public static int getNoteBgResource(int id) {
@ -65,6 +74,10 @@ public class ResourceParser {
}
}
/**
* ID
*
*/
public static int getDefaultBgId(Context context) {
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
@ -74,37 +87,40 @@ public class ResourceParser {
}
}
/**
* NoteItemBgResources - 便
*/
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
};
public static int getNoteBgFirstRes(int id) {
@ -128,13 +144,16 @@ public class ResourceParser {
}
}
/**
* WidgetBgResources -
*/
public static class WidgetBgResources {
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,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
};
public static int getWidget2xBgResource(int id) {
@ -142,11 +161,11 @@ public class ResourceParser {
}
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,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
};
public static int getWidget4xBgResource(int id) {
@ -154,20 +173,22 @@ public class ResourceParser {
}
}
/**
* TextAppearanceResources -
*/
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
* 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}
*/
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE;
}
@ -178,4 +199,4 @@ public class ResourceParser {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}
}

@ -39,120 +39,178 @@ import net.micode.notes.tool.DataUtils;
import java.io.IOException;
/**
* 便
*
* 便
* 1. 使
* 2.
* 3. 便
*
*
* - 使
* -
* - 便便
*/
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; // 媒体播放器,用于播放闹钟音
/**
* Activity
*
*
* @param savedInstanceState
*/
@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);
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // 在锁屏状态下显示
// 如果屏幕未亮起,则添加更多窗口标志以唤醒屏幕
if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON // 保持屏幕常亮
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON // 点亮屏幕
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON // 允许屏幕点亮时锁定
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); // 允许装饰嵌入布局
}
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;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
return; // 如果便签ID无效直接返回
}
mPlayer = new MediaPlayer();
mPlayer = new MediaPlayer(); // 初始化媒体播放器
// 检查便签是否在数据库中且可见(不在回收站中)
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog();
playAlarmSound();
showActionDialog(); // 显示操作对话框
playAlarmSound(); // 播放闹钟音
} else {
finish();
finish(); // 便签不存在或不可见直接结束Activity
}
}
/**
*
*
* @return truefalse
*/
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
}
/**
*
* 使
*/
private void playAlarmSound() {
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
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.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.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); // 显示对话框并设置关闭监听器
}
/**
*
*
* @param dialog
* @param which
*/
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
// 用户点击"进入编辑"按钮,启动便签编辑界面
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId);
intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递便签ID
startActivity(intent);
break;
default:
// 其他按钮(如确定按钮)无额外操作
break;
}
}
/**
*
* Activity
*
* @param dialog
*/
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
finish();
stopAlarmSound(); // 停止播放闹钟音
finish(); // 结束Activity
}
/**
*
*
*/
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
mPlayer.stop(); // 停止播放
mPlayer.release(); // 释放资源
mPlayer = null; // 清空引用
}
}
}
}

@ -27,20 +27,29 @@ import android.database.Cursor;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
/**
*
*
*/
public class AlarmInitReceiver extends BroadcastReceiver {
// 数据库查询需要的列
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; // 提醒时间列索引
@Override
public void onReceive(Context context, Intent intent) {
// 获取当前系统时间
long currentDate = System.currentTimeMillis();
// 查询所有需要设置闹钟的笔记
// 条件:提醒时间大于当前时间,且笔记类型为普通笔记(非文件夹等)
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
@ -48,18 +57,33 @@ public class AlarmInitReceiver extends BroadcastReceiver {
null);
if (c != null) {
// 遍历查询结果
if (c.moveToFirst()) {
do {
// 获取该笔记的提醒时间
long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建触发闹钟的Intent目标为AlarmReceiver
Intent sender = new Intent(context, AlarmReceiver.class);
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
// 将笔记ID附加到URI中以便AlarmReceiver知道是哪个笔记的提醒
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);
// 设置闹钟
// 使用RTC_WAKEUP模式在指定时间唤醒设备并触发PendingIntent
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext());
} while (c.moveToNext()); // 继续处理下一条记录
}
c.close();
c.close(); // 关闭游标,释放资源
}
// 注意如果c为null说明查询失败这里没有错误处理
}
}
}

@ -20,11 +20,38 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
*
* AlarmManager广
*
* AlarmInitReceiver
* - AlarmInitReceiver:
* - AlarmReceiver:
*/
public class AlarmReceiver extends BroadcastReceiver {
/**
* 广
* AlarmManager
*
* @param context Activity
* @param intent Intent
* AlarmInitReceiverURI
*/
@Override
public void onReceive(Context context, Intent intent) {
// 将Intent的目标类设置为AlarmAlertActivity这是显示提醒的界面
intent.setClass(context, AlarmAlertActivity.class);
// 添加FLAG_ACTIVITY_NEW_TASK标志因为从BroadcastReceiver启动Activity
// 必须在一个新的任务栈中,不能直接在当前任务栈启动
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动闹钟提醒Activity
// AlarmAlertActivity将显示具体的笔记内容提醒用户
context.startActivity(intent);
// 注意:此处没有取消或清除闹钟,如果需要一次性闹钟,
// 应在AlarmAlertActivity中处理闹钟的清除
}
}
}

@ -21,92 +21,124 @@ 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;
/**
*
* 1224
* 使NumberPicker
*/
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; // 半天的小时数
private static final int HOURS_IN_ALL_DAY = 24; // 全天的小时数
private static final int DAYS_IN_ALL_WEEK = 7; // 一周的天数(用于显示最近一周的日期)
// NumberPicker范围常量
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; // 上午/下午选择器
// 数据模型
private Calendar mDate; // 当前选择的日期时间
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; // 日期显示值(一周)
private boolean mIsAm; // 是否为上午
private boolean mIs24HourView; // 是否使用24小时制
private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 控件是否启用
private boolean mInitialising; // 是否正在初始化标志,防止初始化期间触发事件
// 日期时间变化监听器
private OnDateTimeChangedListener mOnDateTimeChangedListener;
/**
*
* Calendar
*/
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;
Calendar cal = Calendar.getInstance();
// 12小时制下的特殊处理
if (!mIs24HourView) {
// 处理PM到AM的跨天转换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) {
}
// 处理AM到PM的跨天转换12小时制
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;
}
// 处理12点切换时AM/PM状态变化
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();
}
} else {
}
// 24小时制下的跨天处理
else {
// 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;
}
}
// 设置新的小时值
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,21 +147,33 @@ 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;
// 检测分钟是否从最大值滚动到最小值59->0增加1小时
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
} else if (oldVal == minValue && newVal == maxValue) {
}
// 检测分钟是否从最小值滚动到最大值0->59减少1小时
else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
}
// 如果有小时偏移,调整时间
if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();
updateDateControl(); // 更新日期显示
// 更新AM/PM状态
int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
@ -139,87 +183,117 @@ public class DateTimePicker extends FrameLayout {
updateAmPmControl();
}
}
// 设置新的分钟值
mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged();
onDateTimeChanged(); // 通知监听器
}
};
/**
* AM/PM
* /12
*/
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
// AM/PM切换时调整12小时
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else {
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
}
updateAmPmControl();
onDateTimeChanged();
updateAmPmControl(); // 更新AM/PM显示
onDateTimeChanged(); // 通知监听器
}
};
/**
*
*/
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
int dayOfMonth, int hourOfDay, int minute);
}
/**
* - 使
*/
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
/**
* - 使
*/
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;
mInitialising = true; // 设置初始化标志
// 根据当前小时判断是上午还是下午
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.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state
// 更新控件初始状态
updateDateControl();
updateHourControl();
updateAmPmControl();
set24HourView(is24HourView);
// set to current time
setCurrentDate(date);
setEnabled(isEnabled());
set24HourView(is24HourView); // 设置12/24小时制显示
setCurrentDate(date); // 设置当前时间
setEnabled(isEnabled()); // 设置启用状态
// set the content descriptions
mInitialising = false;
mInitialising = false; // 初始化完成
}
/**
*
*/
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
return;
}
super.setEnabled(enabled);
// 设置所有子控件的启用状态
mDateSpinner.setEnabled(enabled);
mMinuteSpinner.setEnabled(enabled);
mHourSpinner.setEnabled(enabled);
@ -227,24 +301,23 @@ public class DateTimePicker extends FrameLayout {
mIsEnabled = enabled;
}
/**
*
*/
@Override
public boolean isEnabled() {
return mIsEnabled;
}
/**
* Get the current date in millis
*
* @return the current date in millis
*
*/
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
/**
* Set the current date
*
* @param date The current date in millis
*
*/
public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance();
@ -254,16 +327,10 @@ public class DateTimePicker extends FrameLayout {
}
/**
* 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
*
*/
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,20 +339,17 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current year
*
* @return The current year
*
*/
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}
/**
* Set current year
*
* @param year The current year
*
*/
public void setCurrentYear(int year) {
// 防止初始化期间重复触发事件
if (!mInitialising && year == getCurrentYear()) {
return;
}
@ -295,18 +359,14 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current month in the year
*
* @return The current month in the year
* 0-11
*/
public int getCurrentMonth() {
return mDate.get(Calendar.MONTH);
}
/**
* Set current month in the year
*
* @param month The month in the year
*
*/
public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) {
@ -318,18 +378,14 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current day of the month
*
* @return The day of the month
*
*/
public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH);
}
/**
* Set current day of the month
*
* @param dayOfMonth The day of the month
*
*/
public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) {
@ -341,19 +397,22 @@ 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
* 240-23
*/
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}
/**
* 12/24
*/
private int getCurrentHour() {
if (mIs24HourView){
return getCurrentHourOfDay();
return getCurrentHourOfDay(); // 24小时制直接返回
} else {
// 12小时制转换0点显示为1213点显示为1
int hour = getCurrentHourOfDay();
if (hour > HOURS_IN_HALF_DAY) {
if (hour >= HOURS_IN_HALF_DAY) {
return hour - HOURS_IN_HALF_DAY;
} else {
return hour == 0 ? HOURS_IN_HALF_DAY : hour;
@ -362,15 +421,15 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Set current hour in 24 hour mode, in the range (0~23)
*
* @param hourOfDay
* 24
*/
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;
@ -390,16 +449,14 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get currentMinute
*
* @return The Current Minute
*
*/
public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE);
}
/**
* Set current minute
*
*/
public void setCurrentMinute(int minute) {
if (!mInitialising && minute == getCurrentMinute()) {
@ -411,53 +468,78 @@ public class DateTimePicker extends FrameLayout {
}
/**
* @return true if this is in 24 hour view else false.
* 使24
*/
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.
* 12/24
*/
public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) {
return;
}
mIs24HourView = is24HourView;
// 根据12/24小时制显示或隐藏AM/PM选择器
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay();
// 更新小时选择器范围
updateHourControl();
// 保持当前小时,但根据新的显示模式调整
int hour = getCurrentHourOfDay();
setCurrentHour(hour);
updateAmPmControl();
}
/**
*
*
*/
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);
// 生成一周的日期显示字符串
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1);
// 格式:月份.日期 星期几01.15 星期一)
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
}
mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate();
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); // 当前日期在中间位置
mDateSpinner.invalidate(); // 刷新显示
}
/**
* AM/PM
*/
private void updateAmPmControl() {
if (mIs24HourView) {
// 24小时制隐藏AM/PM选择器
mAmPmSpinner.setVisibility(View.GONE);
} else {
// 12小时制显示AM/PM选择器
int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE);
}
}
/**
*
* 12/24
*/
private void updateHourControl() {
if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
@ -469,17 +551,20 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Set the callback that indicates the 'Set' button has been pressed.
* @param callback the callback, if null will do nothing
*
*/
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback;
}
/**
*
*
*/
private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}
}
}
}

@ -29,62 +29,114 @@ 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();
private boolean mIs24HourView;
private OnDateTimeSetListener mOnDateTimeSetListener;
private DateTimePicker mDateTimePicker;
private Calendar mDate = Calendar.getInstance(); // 当前选择的日期时间
private boolean mIs24HourView; // 是否使用24小时制
private OnDateTimeSetListener mOnDateTimeSetListener; // 日期时间设置完成监听器
private DateTimePicker mDateTimePicker; // 日期时间选择器控件
/**
*
* "确定"
*/
public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date);
}
/**
*
* @param context
* @param date
*/
public DateTimePickerDialog(Context context, long date) {
super(context);
// 创建DateTimePicker控件
mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker);
setView(mDateTimePicker); // 将DateTimePicker设置为对话框的内容视图
// 设置DateTimePicker的日期时间变化监听器
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) {
// 当DateTimePicker中的时间变化时更新内部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);
// 根据系统设置决定是否使用24小时制
set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 初始化对话框标题
updateTitle(mDate.getTimeInMillis());
}
/**
* 使24
* @param is24HourView true24false12
*/
public void set24HourView(boolean is24HourView) {
mIs24HourView = 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;
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
DateUtils.FORMAT_SHOW_YEAR | // 显示年份
DateUtils.FORMAT_SHOW_DATE | // 显示日期
DateUtils.FORMAT_SHOW_TIME; // 显示时间
// 根据24小时制设置选择时间格式
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : 0;
// 格式化日期时间并设置为对话框标题
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,35 +27,66 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
/**
*
* ButtonPopupMenu便
*
*/
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);
// 创建PopupMenu绑定到指定按钮
mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu();
// 从菜单资源文件加载菜单项
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 设置按钮点击事件:显示下拉菜单
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
mPopupMenu.show(); // 显示下拉菜单
}
});
}
/**
*
* @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,111 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
/**
*
*
* CursorAdapter
*/
public class FoldersListAdapter extends CursorAdapter {
// 数据库查询的列投影,只查询需要的字段
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;
// 列索引常量便于访问Cursor中的数据
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) {
// 创建FolderListItem作为列表项视图
return new FolderListItem(context);
}
/**
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
// 确保视图是FolderListItem类型
if (view instanceof FolderListItem) {
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
// 获取文件夹名称
String folderName;
// 如果是根文件夹ID为Notes.ID_ROOT_FOLDER显示特殊名称
if (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) {
folderName = context.getString(R.string.menu_move_parent_folder);
} else {
folderName = cursor.getString(NAME_COLUMN);
}
// 绑定文件夹名称到视图
((FolderListItem) view).bind(folderName);
}
}
/**
*
* @param context
* @param position
* @return
*/
public String getFolderName(Context context, int position) {
// 获取指定位置的Cursor
Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
// 根据是否为根文件夹返回相应的名称
if (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) {
return context.getString(R.string.menu_move_parent_folder);
} else {
return cursor.getString(NAME_COLUMN);
}
}
/**
*
*
*/
private class FolderListItem extends LinearLayout {
private TextView mName;
private TextView mName; // 显示文件夹名称的TextView
/**
*
* @param context
*/
public FolderListItem(Context context) {
super(context);
// 从布局文件加载视图
inflate(context, R.layout.folder_list_item, this);
// 初始化TextView
mName = (TextView) findViewById(R.id.tv_folder_name);
}
/**
*
* @param name
*/
public void bind(String name) {
mName.setText(name);
mName.setText(name); // 设置文件夹名称
}
}
}
}

File diff suppressed because it is too large Load Diff

@ -37,99 +37,144 @@ import net.micode.notes.R;
import java.util.HashMap;
import java.util.Map;
/**
*
* EditTextNoteEditActivity
*
*/
public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText";
private int mIndex;
private int mSelectionStartBeforeDelete;
private static final String TAG = "NoteEditText"; // 日志标签
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:" ;
// URL协议常量
private static final String SCHEME_TEL = "tel:" ; // 电话协议
private static final String SCHEME_HTTP = "http:" ; // HTTP协议
private static final String SCHEME_EMAIL = "mailto:"; // 邮件协议
// URL协议与对应菜单资源ID的映射
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
* @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;
private OnTextViewChangeListener mOnTextViewChangeListener; // 文本变化监听器
/**
*
* @param context
*/
public NoteEditText(Context context) {
super(context, null);
mIndex = 0;
}
/**
*
* @param index
*/
public void setIndex(int index) {
mIndex = index;
}
/**
*
* @param listener
*/
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
/**
*
* @param context
* @param attrs
*/
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
/**
*
* @param context
* @param attrs
* @param defStyle
*/
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:
// 计算触摸位置对应的字符偏移量
int x = (int) event.getX();
int y = (int) event.getY();
x -= getTotalPaddingLeft();
x -= getTotalPaddingLeft(); // 减去内边距
y -= getTotalPaddingTop();
x += getScrollX();
x += getScrollX(); // 加上滚动偏移
y += getScrollY();
Layout layout = getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
Selection.setSelection(getText(), off);
int line = layout.getLineForVertical(y); // 获取垂直方向行号
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: // 删除键
// 记录删除前的光标位置
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
@ -138,11 +183,16 @@ public class NoteEditText extends EditText {
return super.onKeyDown(keyCode, event);
}
/**
*
*
*/
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_DEL:
case KeyEvent.KEYCODE_DEL: // 删除键
if (mOnTextViewChangeListener != null) {
// 如果光标在开头且不是第一个编辑框,则触发删除事件
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true;
@ -151,11 +201,12 @@ public class NoteEditText extends EditText {
Log.d(TAG, "OnTextViewChangeListener was not seted");
}
break;
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_ENTER: // 回车键
if (mOnTextViewChangeListener != null) {
// 将当前光标后的文本移到新编辑框
int selectionStart = getSelectionStart();
String text = getText().subSequence(selectionStart, length()).toString();
setText(getText().subSequence(0, selectionStart));
setText(getText().subSequence(0, selectionStart)); // 保留光标前的文本
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
@ -167,9 +218,14 @@ 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 {
@ -179,18 +235,27 @@ public class NoteEditText extends EditText {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
/**
*
*
*/
@Override
protected void onCreateContextMenu(ContextMenu menu) {
// 检查文本是否包含Span如链接
if (getText() instanceof Spanned) {
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
// 获取选中区域的最小和最大位置
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
// 获取选中区域内的URLSpan
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
// 如果只有一个链接,则添加上下文菜单
if (urls.length == 1) {
int defaultResId = 0;
// 根据URL协议确定菜单文本资源
for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema);
@ -198,14 +263,16 @@ public class NoteEditText extends EditText {
}
}
// 如果未匹配到已知协议,使用"其他链接"
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;
}
@ -214,4 +281,4 @@ public class NoteEditText extends EditText {
}
super.onCreateContextMenu(menu);
}
}
}

@ -18,6 +18,7 @@ package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.text.Html;
import android.text.TextUtils;
import net.micode.notes.data.Contact;
@ -25,23 +26,34 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
/**
*
* 便访
* 使
*/
public class NoteItemData {
// 数据库查询列投影
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, // 0: 笔记ID
NoteColumns.ALERTED_DATE, // 1: 提醒时间
NoteColumns.BG_COLOR_ID, // 2: 背景颜色ID
NoteColumns.CREATED_DATE, // 3: 创建时间
NoteColumns.HAS_ATTACHMENT, // 4: 是否有附件
NoteColumns.MODIFIED_DATE, // 5: 修改时间
NoteColumns.NOTES_COUNT, // 6: 笔记数量(针对文件夹)
NoteColumns.PARENT_ID, // 7: 父文件夹ID
NoteColumns.SNIPPET, // 8: 内容摘要
NoteColumns.TITLE, // 9: 笔记标题
NoteColumns.TYPE, // 10: 类型(笔记/文件夹/系统文件夹)
NoteColumns.WIDGET_ID, // 11: 小部件ID
NoteColumns.WIDGET_TYPE, // 12: 小部件类型
NoteColumns.PINNED, // 13: 是否置顶
NoteColumns.PRIVATE, // 14: 是否为隐私文件夹
NoteColumns.IS_STUDY, // 15: 是否为学习文件夹
NoteColumns.FOCUS_DURATION, // 16: 专注时长(毫秒)
};
// 列索引常量
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
@ -51,51 +63,111 @@ public class NoteItemData {
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;
private static final int TITLE_COLUMN = 9;
private static final int TYPE_COLUMN = 10;
private static final int WIDGET_ID_COLUMN = 11;
private static final int WIDGET_TYPE_COLUMN = 12;
private static final int PINNED_COLUMN = 13;
private static final int PRIVATE_COLUMN = 14;
private static final int IS_STUDY_COLUMN = 15;
private static final int FOCUS_DURATION_COLUMN = 16;
// 笔记数据字段
private long mId; // 笔记ID
private long mAlertDate; // 提醒时间
private int mBgColorId; // 背景颜色ID
private long mCreatedDate; // 创建时间
private boolean mHasAttachment; // 是否有附件
private long mModifiedDate; // 修改时间
private int mNotesCount; // 笔记数量(针对文件夹)
private long mParentId; // 父文件夹ID
private String mSnippet; // 内容摘要
private String mTitle; // 笔记标题
private int mType; // 类型
private int mWidgetId; // 小部件ID
private int mWidgetType; // 小部件类型
private boolean mIsPinned; // 是否置顶
private boolean mIsPrivate; // 是否为隐私文件夹
private boolean mIsStudy; // 是否为学习文件夹
private long mFocusDuration; // 专注时长(毫秒)
private String mName; // 联系人姓名(针对通话记录)
private String mPhoneNumber; // 电话号码(针对通话记录)
// 位置信息字段
private boolean mIsLastItem; // 是否是最后一项
private boolean mIsFirstItem; // 是否是第一项
private boolean mIsOnlyOneItem; // 是否是唯一一项
private boolean mIsOneNoteFollowingFolder; // 是否是紧跟在文件夹后的单个笔记
private boolean mIsMultiNotesFollowingFolder;// 是否是紧跟在文件夹后的多个笔记
/**
*
* @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);
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);
// 获取并处理snippet移除HTML标签和清单标记
mSnippet = cursor.getString(SNIPPET_COLUMN);
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, "");
if (mSnippet != null) {
// 直接保存原始内容不进行HTML转换
// 因为我们需要保留内容的第一行作为标题而HTML转换可能会丢失结构信息
// 只移除清单标记
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, "");
// 移除多余的空白字符
mSnippet = mSnippet.trim();
}
mTitle = cursor.getString(TITLE_COLUMN); // 读取标题字段,修复索引偏移问题
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mIsPinned = (cursor.getInt(PINNED_COLUMN) > 0) ? true : false;
mIsPrivate = (cursor.getInt(PRIVATE_COLUMN) > 0) ? true : false;
mIsStudy = (cursor.getInt(IS_STUDY_COLUMN) > 0) ? true : false;
mFocusDuration = cursor.getLong(FOCUS_DURATION_COLUMN);
// 动态计算文件夹的便签数量
if (mType == Notes.TYPE_FOLDER && mParentId == Notes.ID_TRASH_FOLER) {
// 只对回收站中的文件夹进行动态计算
// 查询ORIGIN_PARENT_ID等于当前文件夹ID的便签数量
// 这样可以在回收站中显示文件夹内的便签数量
Cursor countCursor = context.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
new String[]{"COUNT(*)"},
Notes.NoteColumns.ORIGIN_PARENT_ID + "=?",
new String[]{String.valueOf(mId)},
null);
if (countCursor != null) {
if (countCursor.moveToFirst()) {
mNotesCount = countCursor.getInt(0);
}
countCursor.close();
} else {
mNotesCount = 0;
}
} else {
// 对于其他文件夹使用原来的NOTES_COUNT字段
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
}
// 初始化通话记录相关字段
mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
// 获取通话记录的电话号码
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
// 根据电话号码获取联系人姓名
mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) {
mName = mPhoneNumber;
@ -106,9 +178,14 @@ public class NoteItemData {
if (mName == null) {
mName = "";
}
// 检查位置信息
checkPostion(cursor);
}
/**
*
* @param cursor
*/
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
@ -116,17 +193,20 @@ public class NoteItemData {
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");
}
@ -134,91 +214,264 @@ public class NoteItemData {
}
}
/**
*
*/
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
/**
*
*/
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
}
/**
*
*/
public boolean isLast() {
return mIsLastItem;
}
/**
*
*/
public String getCallName() {
return mName;
}
/**
*
*/
public boolean isFirst() {
return mIsFirstItem;
}
/**
*
*/
public boolean isSingle() {
return mIsOnlyOneItem;
}
/**
* ID
*/
public long getId() {
return mId;
}
/**
*
*/
public long getAlertDate() {
return mAlertDate;
}
/**
*
*/
public long getCreatedDate() {
return mCreatedDate;
}
/**
*
*/
public boolean hasAttachment() {
return mHasAttachment;
}
/**
*
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* ID
*/
public long getParentId() {
return mParentId;
}
/**
*
*/
public int getNotesCount() {
return mNotesCount;
}
/**
* IDgetParentId
*/
public long getFolderId () {
return mParentId;
}
/**
*
*/
public int getType() {
return mType;
}
/**
*
*/
public int getWidgetType() {
return mWidgetType;
}
/**
* ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
*
*/
public String getSnippet() {
return mSnippet;
}
/**
*
*/
public String getTitle() {
return mTitle;
}
/**
* 使使
*/
public String getDisplayTitle() {
if (!TextUtils.isEmpty(mTitle)) {
return mTitle;
}
// 没有标题时,返回内容摘要的第一行
if (!TextUtils.isEmpty(mSnippet)) {
// 临时存储原始snippet
String originalSnippet = mSnippet;
// 第一步移除HTML标签提取纯文本
String plainText = originalSnippet.replaceAll("<[^>]*>", "");
// 第二步移除HTML实体
plainText = plainText.replaceAll("&[^;]+;", "");
// 第三步:移除多余的空白字符
plainText = plainText.trim();
// 第四步如果处理后仍然为空尝试从原始HTML中提取有意义的内容
if (TextUtils.isEmpty(plainText)) {
// 尝试直接提取文本,不使用正则表达式
try {
// 使用Android内置的Html.fromHtml方法转换为纯文本
CharSequence fromHtmlText = Html.fromHtml(originalSnippet);
plainText = fromHtmlText.toString().trim();
} catch (Exception e) {
// 如果转换失败,使用原始文本
plainText = originalSnippet.replaceAll("<[^>]*>", "").trim();
}
}
// 第五步:如果仍然为空,返回默认标题
if (TextUtils.isEmpty(plainText)) {
return "新便签";
}
// 第六步:获取第一行作为标题
int newlineIndex = plainText.indexOf('\n');
if (newlineIndex > 0) {
return plainText.substring(0, newlineIndex);
} else {
// 如果没有换行返回前20个字符作为标题
if (plainText.length() > 20) {
return plainText.substring(0, 20) + "...";
} else {
return plainText;
}
}
}
return "新便签";
}
/**
*
*/
public boolean hasAlert() {
return (mAlertDate > 0);
}
/**
*
*/
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
/**
*
* @param cursor
* @return
*/
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}
/**
*
* @return
*/
public boolean isPinned() {
return mIsPinned;
}
/**
*
* @return
*/
public boolean isPrivate() {
return mIsPrivate;
}
/**
*
* @return
*/
public boolean isStudy() {
return mIsStudy;
}
/**
*
* @return
*/
public long getFocusDuration() {
return mFocusDuration;
}
/**
*
* @return "xx小时xx分钟"
*/
public String getFormattedFocusDuration() {
long totalMinutes = mFocusDuration / (1000 * 60);
long hours = totalMinutes / 60;
long minutes = totalMinutes % 60;
return hours > 0 ? hours + "小时" + minutes + "分钟" : minutes + "分钟";
}
}

File diff suppressed because it is too large Load Diff

@ -1,17 +1,15 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* (c) 2010-2011The MiCode (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* Apache 2.0 "许可证"
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* "原样"
*
*
*/
package net.micode.notes.ui;
@ -30,58 +28,104 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
/**
* CursorAdapter
* ListView
*/
public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter";
private Context mContext;
private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount;
private boolean mChoiceMode;
private static final String TAG = "NotesListAdapter"; // 日志标签
private Context mContext; // 上下文对象
private HashMap<Integer, Boolean> mSelectedIndex; // 存储选中状态的映射表key为位置value为是否选中
private int mNotesCount; // 笔记总数(只包括普通笔记类型)
private boolean mChoiceMode; // 是否处于选择模式
/**
*
* ID
*/
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
public int widgetId; // 小部件ID
public int widgetType; // 小部件类型
};
/**
*
* @param context
*/
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
super(context, null); // 初始时Cursor为null
mSelectedIndex = new HashMap<Integer, Boolean>(); // 初始化选中状态映射表
mContext = context;
mNotesCount = 0;
}
/**
*
* @param context
* @param cursor
* @param parent
* @return NotesListItem
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context);
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 对象来包装游标数据
NoteItemData itemData = new NoteItemData(context, cursor);
// 绑定数据到 NotesListItem 视图
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
}
}
/**
*
* @param position
* @param checked
*/
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked);
notifyDataSetChanged();
mSelectedIndex.put(position, checked); // 更新选中状态
notifyDataSetChanged(); // 通知数据变化,刷新视图
}
/**
*
* @return
*/
public boolean isInChoiceMode() {
return mChoiceMode;
}
/**
*
* @param mode
*/
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear();
mSelectedIndex.clear(); // 清除之前的选中状态
mChoiceMode = mode;
notifyDataSetChanged(); // 通知数据集变化,清除对勾标记
}
/**
*
* @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,22 +133,38 @@ public class NotesListAdapter extends CursorAdapter {
}
}
/**
* ID
* @return ID
*/
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position);
Long id = getItemId(position); // 获取项目ID
if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen");
Log.d(TAG, "错误的项目ID不应该发生");
} else {
itemSet.add(id);
itemSet.add(id); // 添加到集合
}
}
}
return itemSet;
}
/**
*
* @return
*/
public HashMap<Integer, Boolean> getSelectedIndex() {
return mSelectedIndex;
}
/**
*
* @return null
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) {
@ -113,14 +173,14 @@ public class NotesListAdapter extends CursorAdapter {
if (c != null) {
AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType();
widget.widgetId = item.getWidgetId(); // 获取小部件ID
widget.widgetType = item.getWidgetType();// 获取小部件类型
itemSet.add(widget);
/**
* Don't close cursor here, only the adapter could close it
*
*/
} else {
Log.e(TAG, "Invalid cursor");
Log.e(TAG, "无效的游标");
return null;
}
}
@ -128,6 +188,10 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
/**
*
* @return
*/
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
@ -137,48 +201,68 @@ public class NotesListAdapter extends CursorAdapter {
int count = 0;
while (iter.hasNext()) {
if (true == iter.next()) {
count++;
count++; // 统计选中项目
}
}
return count;
}
/**
*
* @return truefalse
*/
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount);
int checkedCount = getSelectedCount(); // 获取选中数量
return (checkedCount != 0 && checkedCount == mNotesCount); // 比较选中数量和笔记总数
}
/**
*
* @param position
* @return
*/
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false;
return false; // 如果映射表中不存在该位置返回false
}
return mSelectedIndex.get(position);
}
/**
*
*/
@Override
protected void onContentChanged() {
super.onContentChanged();
calcNotesCount();
calcNotesCount(); // 重新计算笔记数量
}
/**
*
* @param cursor
*/
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
calcNotesCount();
calcNotesCount(); // 重新计算笔记数量
}
/**
*
*/
private void calcNotesCount() {
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++;
}
} else {
Log.e(TAG, "Invalid cursor");
Log.e(TAG, "无效的游标");
return;
}
}
}
}
}

@ -1,17 +1,15 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* (c) 2010-2011The MiCode (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* Apache 2.0 "许可证"
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* "原样"
*
*
*/
package net.micode.notes.ui;
@ -29,18 +27,28 @@ 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);
// 从布局文件note_item.xml中加载视图
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);
@ -48,75 +56,137 @@ public class NotesListItem extends LinearLayout {
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
/**
*
*
* @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);
mCheckBox.setVisibility(View.VISIBLE); // 选择模式且为普通笔记时显示复选框
mCheckBox.setChecked(checked); // 设置选中状态
} else {
mCheckBox.setVisibility(View.GONE);
mCheckBox.setVisibility(View.GONE); // 其他情况隐藏复选框
}
mItemData = data;
mItemData = data; // 保存数据引用
// 根据笔记类型和父文件夹ID设置不同的显示方式
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE);
// 通话记录文件夹
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());
// 通话记录文件夹中的笔记
mCallName.setVisibility(View.VISIBLE); // 显示通话记录名称
mCallName.setText(data.getCallName()); // 设置通话记录名称
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
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);
// 普通笔记或文件夹
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);
} else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
// 文件夹类型
if (data.isPrivate()) {
// 隐私文件夹
mTitle.setText(data.getSnippet()); // 只显示文件夹名称,不显示便签数量
mAlert.setImageResource(R.drawable.lock); // 设置隐私文件夹图标
mAlert.setVisibility(View.VISIBLE);
// 隐私文件夹不显示修改时间
mTime.setVisibility(View.GONE);
} else {
mAlert.setVisibility(View.GONE);
// 普通文件夹
mTitle.setText(data.getSnippet() // 设置文件夹名称
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount())); // 添加笔记数量
// 根据是否置顶设置置顶图标
if (data.isPinned()) {
mAlert.setImageResource(R.drawable.arrow_up); // 置顶标记
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
// 普通文件夹显示修改时间
mTime.setVisibility(View.VISIBLE);
}
} else {
// 普通笔记类型
mTitle.setText(DataUtils.getFormattedSnippet(data.getDisplayTitle())); // 设置笔记标题,优先使用标题字段
// 根据是否置顶或有提醒设置图标
if (data.isPinned()) {
mAlert.setImageResource(R.drawable.arrow_up); // 置顶标记
mAlert.setVisibility(View.VISIBLE);
} else if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock); // 有时钟图标
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
}
}
// 设置相对时间(如"5分钟前"、"昨天"等格式)
// 只有非隐私文件夹和普通笔记才显示修改时间
if (!data.isPrivate() || data.getType() != Notes.TYPE_FOLDER) {
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
mTime.setVisibility(View.VISIBLE);
}
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 设置背景
setBackground(data);
}
/**
*
* ID
* @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
*/
public NoteItemData getItemData() {
return mItemData;
}
}
}

@ -1,17 +1,15 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* (c) 2010-2011The MiCode (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* Apache 2.0 "许可证"
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* "原样"
*
*
*/
package net.micode.notes.ui;
@ -47,342 +45,388 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
/**
* Activity
* PreferenceActivity
*
*/
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;
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; // 是否添加了新账户的标志
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true);
/* 使用应用图标进行导航 */
getActionBar().setDisplayHomeAsUpEnabled(true); // 显示返回主页按钮
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);
addPreferencesFromResource(R.xml.preferences); // 从XML资源加载偏好设置
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); // 查找账户设置分类
mReceiver = new GTaskReceiver(); // 创建广播接收器
IntentFilter filter = new IntentFilter(); // 创建Intent过滤器
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);
mOriAccounts = null; // 初始化原始账户列表
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); // 加载设置页面头部布局
getListView().addHeaderView(header, null, true); // 将头部添加到列表视图
}
@Override
protected void onResume() {
super.onResume();
// need to set sync account automatically if user has added a new
// account
// 如果用户添加了新账户,需要自动设置同步账户
if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts();
Account[] accounts = getGoogleAccounts(); // 获取当前所有Google账户
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
// 检查是否有新账户被添加
for (Account accountNew : accounts) {
boolean found = false;
for (Account accountOld : mOriAccounts) {
if (TextUtils.equals(accountOld.name, accountNew.name)) {
found = true;
found = true; // 账户已存在
break;
}
}
if (!found) {
setSyncAccount(accountNew.name);
setSyncAccount(accountNew.name); // 设置新账户为同步账户
break;
}
}
}
}
refreshUI();
refreshUI(); // 刷新UI
}
@Override
protected void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
unregisterReceiver(mReceiver); // 取消注册广播接收器
}
super.onDestroy();
}
/**
*
*/
private void loadAccountPreference() {
mAccountCategory.removeAll();
mAccountCategory.removeAll(); // 清除所有现有设置项
Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary));
Preference accountPref = new Preference(this); // 创建账户设置项
final String defaultAccount = getSyncAccountName(this); // 获取当前同步账户名称
accountPref.setTitle(getString(R.string.preferences_account_title)); // 设置标题
accountPref.setSummary(getString(R.string.preferences_account_summary)); // 设置摘要
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (!GTaskSyncService.isSyncing()) {
if (!GTaskSyncService.isSyncing()) { // 检查是否正在同步
if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account
showSelectAccountAlertDialog();
// 首次设置账户
showSelectAccountAlertDialog(); // 显示选择账户对话框
} else {
// if the account has already been set, we need to promp
// user about the risk
showChangeAccountConfirmAlertDialog();
// 如果账户已经设置,需要提示用户风险
showChangeAccountConfirmAlertDialog(); // 显示更改账户确认对话框
}
} else {
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show(); // 显示无法更改账户的提示
}
return true;
}
});
mAccountCategory.addPreference(accountPref);
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);
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.setText(getString(R.string.preferences_button_sync_cancel)); // 同步中显示取消
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
GTaskSyncService.cancelSync(NotesPreferenceActivity.this); // 取消同步
}
});
} else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setText(getString(R.string.preferences_button_sync_immediately)); // 未同步显示立即同步
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.startSync(NotesPreferenceActivity.this);
GTaskSyncService.startSync(NotesPreferenceActivity.this); // 开始同步
}
});
}
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); // 有同步账户时启用按钮
// set last sync time
// 设置上次同步时间
if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); // 显示同步进度
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
long lastSyncTime = getLastSyncTime(this);
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)));
lastSyncTime))); // 格式化显示上次同步时间
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
lastSyncTimeView.setVisibility(View.GONE);
lastSyncTimeView.setVisibility(View.GONE); // 从未同步过则隐藏
}
}
}
/**
* UI
*/
private void refreshUI() {
loadAccountPreference();
loadSyncButton();
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));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
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)); // 设置标题
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); // 副标题文本
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); // 设置副标题
dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null);
dialogBuilder.setCustomTitle(titleView); // 设置自定义标题
dialogBuilder.setPositiveButton(null, null); // 不设置确定按钮
Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this);
Account[] accounts = getGoogleAccounts(); // 获取所有Google账户
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;
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;
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();
setSyncAccount(itemMapping[which].toString()); // 设置选中的账户为同步账户
dialog.dismiss(); // 关闭对话框
refreshUI(); // 刷新UI
}
});
}
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView);
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); // 加载添加账户视图
dialogBuilder.setView(addAccountView); // 设置对话框视图
final AlertDialog dialog = dialogBuilder.show();
final AlertDialog dialog = dialogBuilder.show(); // 显示对话框
addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
mHasAddedAccount = true; // 标记已添加账户
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); // 跳转到添加账户设置
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls"
"gmail-ls" // 设置账户权限过滤器
});
startActivityForResult(intent, -1);
dialog.dismiss();
startActivityForResult(intent, -1); // 启动添加账户Activity
dialog.dismiss(); // 关闭对话框
}
});
}
/**
*
*/
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);
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)));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView);
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),
getString(R.string.preferences_menu_cancel)
getString(R.string.preferences_menu_change_account), // 更改账户
getString(R.string.preferences_menu_remove_account), // 移除账户
getString(R.string.preferences_menu_cancel) // 取消
};
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showSelectAccountAlertDialog();
showSelectAccountAlertDialog(); // 显示选择账户对话框
} else if (which == 1) {
removeSyncAccount();
refreshUI();
removeSyncAccount(); // 移除同步账户
refreshUI(); // 刷新UI
}
// 选项2为取消不执行任何操作
}
});
dialogBuilder.show();
dialogBuilder.show(); // 显示对话框
}
/**
* Google
* @return Google
*/
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
AccountManager accountManager = AccountManager.get(this); // 获取账户管理器
return accountManager.getAccountsByType("com.google"); // 返回Google类型账户
}
/**
*
* @param account
*/
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (!getSyncAccountName(this).equals(account)) { // 检查账户是否已更改
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); // 获取偏好设置
SharedPreferences.Editor editor = settings.edit(); // 获取编辑器
if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); // 保存账户名称
} else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); // 清空账户名称
}
editor.commit();
editor.commit(); // 提交更改
// clean up last sync time
// 清除上次同步时间
setLastSyncTime(this, 0);
// clean up local gtask related info
// 清除本地GTask相关信息
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
values.put(NoteColumns.GTASK_ID, ""); // 清空GTask ID
values.put(NoteColumns.SYNC_ID, 0); // 清空同步ID
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); // 更新数据库
}
}).start();
Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();
Toast.LENGTH_SHORT).show(); // 显示设置成功提示
}
}
/**
*
*/
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
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);
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); // 移除同步账户名称
}
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME);
editor.remove(PREFERENCE_LAST_SYNC_TIME); // 移除上次同步时间
}
editor.commit();
editor.commit(); // 提交更改
// clean up local gtask related info
// 清除本地GTask相关信息
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
values.put(NoteColumns.GTASK_ID, ""); // 清空GTask ID
values.put(NoteColumns.SYNC_ID, 0); // 清空同步ID
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); // 更新数据库
}
}).start();
}
/**
*
* @param context
* @return
*/
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
Context.MODE_PRIVATE); // 获取偏好设置
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); // 返回账户名称
}
/**
*
* @param context
* @param time
*/
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit();
Context.MODE_PRIVATE); // 获取偏好设置
SharedPreferences.Editor editor = settings.edit(); // 获取编辑器
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); // 保存同步时间
editor.commit(); // 提交更改
}
/**
*
* @param context
* @return 0
*/
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
Context.MODE_PRIVATE); // 获取偏好设置
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); // 返回同步时间
}
/**
* GTask广
* UI
*/
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshUI();
refreshUI(); // 刷新UI
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); // 同步状态文本
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); // 更新进度消息
}
}
}
/**
*
* @param item
* @return
*/
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);
case android.R.id.home: // 返回主页按钮
Intent intent = new Intent(this, NotesListActivity.class); // 跳转到笔记列表Activity
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 清除Activity栈
startActivity(intent);
return true;
default:
return false;
}
}
}
}

@ -1,20 +1,19 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* (c) 2010-2011The MiCode (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* Apache 2.0 "许可证"
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* "原样"
*
*
*/
package net.micode.notes.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
@ -32,101 +31,166 @@ import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;
/**
*
* AppWidgetProvider
*
*/
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";
private static final String TAG = "NoteWidgetProvider"; // 日志标签
/**
*
* ID
* @param context
* @param appWidgetIds ID
*/
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues();
// 将小部件ID设置为无效值
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 + "=?",
new String[] { String.valueOf(appWidgetIds[i])});
NoteColumns.WIDGET_ID + "=?", // 条件小部件ID等于被删除的小部件ID
new String[] { String.valueOf(appWidgetIds[i])}); // 参数值
}
}
/**
* ID
* @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 + "<>?",
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
null);
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", // 条件
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, // 参数值
null); // 排序方式
}
/**
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetManager, appWidgetIds, false);
update(context, appWidgetManager, appWidgetIds, false); // 默认非隐私模式
}
/**
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
* @param privacyMode
*/
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 = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
int bgId = ResourceParser.getDefaultBgId(context); // 默认背景颜色ID
String snippet = ""; // 笔记内容片段
Intent intent = new Intent(context, NoteEditActivity.class); // 创建编辑笔记的Intent
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // 设置为单例模式
// 传递小部件ID和类型信息
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()) {
// 检查是否有多条笔记对应同一个widgetId不应该发生
if (c.getCount() > 1) {
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);
// 传递笔记ID用于查看已有笔记
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
intent.setAction(Intent.ACTION_VIEW);
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); // 设置动作为插入或编辑
}
if (c != null) {
c.close();
c.close(); // 关闭Cursor
}
// 创建RemoteViews对象
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
// 设置背景图片
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
* 宿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();
}
}

@ -1,17 +1,15 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* (c) 2010-2011The MiCode (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* Apache 2.0 "许可证"
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* "原样"
*
*
*/
package net.micode.notes.widget;
@ -23,25 +21,51 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
/**
* 2x
* NoteWidgetProvider2x
* 2x
*/
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
/**
*
* update
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds);
super.update(context, appWidgetManager, appWidgetIds); // 调用父类更新方法
}
/**
* 2xID
* @return 2xID
*/
@Override
protected int getLayoutId() {
return R.layout.widget_2x;
return R.layout.widget_2x; // 返回2x小部件的布局文件
}
/**
* IDID
* 2x
* @param bgId ID
* @return 2xID
*/
@Override
protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); // 获取2x小部件的背景资源
}
/**
*
* @return 2x
*/
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X;
return Notes.TYPE_WIDGET_2X; // 返回2x小部件的类型标识
}
}
}

@ -1,17 +1,15 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* (c) 2010-2011The MiCode (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* Apache 2.0 "许可证"
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* "原样"
*
*
*/
package net.micode.notes.widget;
@ -23,24 +21,52 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
/**
* 4x
* NoteWidgetProvider4x
* 4x
* NoteWidgetProvider_2x4x
*/
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
/**
*
* update
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds);
super.update(context, appWidgetManager, appWidgetIds); // 调用父类更新方法
}
/**
* 4xID
* 4xID
* @return 4xID
*/
protected int getLayoutId() {
return R.layout.widget_4x;
return R.layout.widget_4x; // 返回4x小部件的布局文件
}
/**
* IDID
* 4x
* @param bgId ID
* @return 4xID
*/
@Override
protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); // 获取4x小部件的背景资源
}
/**
*
* @return 4x
*/
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X;
return Notes.TYPE_WIDGET_4X; // 返回4x小部件的类型标识
}
}
}
Loading…
Cancel
Save