初始化工程

main
sweet 2 years ago
parent 2e7963f92f
commit d13de7bc61

@ -26,46 +26,53 @@ import android.util.Log;
import java.util.HashMap;
public class Contact {
// 用于缓存联系人信息的静态HashMap
private static HashMap<String, String> sContactCache;
// 日志标签
private static final String TAG = "Contact";
// 查询联系人的SQL语句使用Android的ContentProvider机制
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
// 获取联系人信息的静态方法传入Context和电话号码
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);
}
// 构建查询条件替换SQL语句中的占位符"+"
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 使用ContentResolver进行查询
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_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.close();
}
} else {
// 如果未查询到结果打印调试信息并返回null
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}

@ -28,10 +28,11 @@ import net.micode.notes.data.Notes.NoteColumns;
public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 数据库名称和版本号
private static final String DB_NAME = "note.db";
// 数据表的接口定义
private static final int DB_VERSION = 4;
// 单例模式的实例
public interface TABLE {
public static final String NOTE = "note";
@ -41,7 +42,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "NotesDatabaseHelper";
private static NotesDatabaseHelper mInstance;
// 创建笔记表的SQL语句
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
@ -62,7 +63,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")";
// 创建数据表的SQL语句
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
@ -77,7 +78,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";
// 创建数据表的索引的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 + ");";
@ -205,19 +206,23 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
// 构造方法接收Context参数
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
// 创建笔记表的方法
public void createNoteTable(SQLiteDatabase db) {
// 执行创建笔记表的SQL语句
db.execSQL(CREATE_NOTE_TABLE_SQL);
// 重新创建笔记表的触发器
reCreateNoteTableTriggers(db);
// 创建系统文件夹
createSystemFolder(db);
Log.d(TAG, "note table has been created");
}
// 重新创建笔记表的触发器
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
// 删除旧的触发器 ... (删除其他触发器)
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -226,6 +231,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
// 创建新的触发器 ... (创建其他触发器)
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
@ -234,13 +240,14 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
// 创建系统文件夹的方法
private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues();
/**
* call record foler for call notes
*/
// 创建不同的系统文件夹例如call record folder、root folder、temporary folder、trash folder
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
@ -269,38 +276,44 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
// 创建数据表的方法
public void createDataTable(SQLiteDatabase db) {
// 执行创建数据表的SQL语句
db.execSQL(CREATE_DATA_TABLE_SQL);
// 重新创建数据表的触发器
reCreateDataTableTriggers(db);
// 创建数据表的索引
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
Log.d(TAG, "data table has been created");
}
// 重新创建数据表的触发器
private void reCreateDataTableTriggers(SQLiteDatabase db) {
// 删除旧的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
// 创建新的触发器
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
// 获取数据库帮助类的实例,采用单例模式
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
}
return mInstance;
}
// 创建数据库时的回调方法
@Override
public void onCreate(SQLiteDatabase db) {
// 创建笔记表和数据表
createNoteTable(db);
createDataTable(db);
}
// 数据库升级时的回调方法
@Override
// ... (数据库升级的相关逻辑)
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
boolean skipV2 = false;
@ -332,14 +345,14 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
+ "fails");
}
}
// 数据库升级到版本2的方法
private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
createNoteTable(db);
createDataTable(db);
}
// 数据库升级到版本3的方法
private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
@ -354,7 +367,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
// 数据库升级到版本4的方法
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");

@ -34,14 +34,15 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
//用于提供备忘录Notes应用数据的 Content Provider 类,用于与应用的数据进行交互
public class NotesProvider extends ContentProvider {
//一些静态变量的定义
private static final UriMatcher mMatcher;
private NotesDatabaseHelper mHelper;
private static final String TAG = "NotesProvider";
// 定义 URI 匹配器,用于匹配不同的 URI 请求
private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
@ -65,6 +66,7 @@ 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.
*/
// 定义用于搜索的投影,以及搜索的 SQL 查询语句
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 + ","
@ -80,38 +82,47 @@ public class NotesProvider extends ContentProvider {
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override
//数据库初始化
public boolean onCreate() {
// 初始化 NotesProvider在这里创建了一个 NotesDatabaseHelper 实例
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
@Override
//查询处理
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
switch (mMatcher.match(uri)) {
// 处理不同的 URI 请求
case URI_NOTE:
// 处理备忘录列表的查询
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
// 处理单个备忘录的查询
id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
// 处理备忘录数据的查询
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM:
// 处理单个备忘录数据的查询
id = uri.getPathSegments().get(1);
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_SEARCH:
case URI_SEARCH_SUGGEST:
// 处理搜索结果的查询
if (sortOrder != null || projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
@ -148,14 +159,17 @@ public class NotesProvider extends ContentProvider {
}
@Override
//数值插入
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 插入备忘录
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
case URI_DATA:
// 插入备忘录数据
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
@ -166,7 +180,7 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
// 通知数据变更
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
@ -182,6 +196,7 @@ public class NotesProvider extends ContentProvider {
}
@Override
//数据删除
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
@ -189,10 +204,12 @@ public class NotesProvider extends ContentProvider {
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 删除备忘录
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
// 删除单个备忘录
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
@ -206,10 +223,12 @@ public class NotesProvider extends ContentProvider {
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
// 删除备忘录数据
count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true;
break;
case URI_DATA_ITEM:
// 删除单个备忘录数据
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
@ -218,6 +237,7 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 通知数据变更
if (count > 0) {
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
@ -228,6 +248,7 @@ public class NotesProvider extends ContentProvider {
}
@Override
//数据更新
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
@ -235,20 +256,24 @@ public class NotesProvider extends ContentProvider {
boolean updateData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 更新备忘录
increaseNoteVersion(-1, selection, selectionArgs);
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
// 更新单个备忘录
id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
break;
case URI_DATA:
// 更新备忘录数据
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
break;
case URI_DATA_ITEM:
// 更新单个备忘录数据
id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
@ -257,7 +282,7 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 通知数据变更
if (count > 0) {
if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
@ -266,11 +291,12 @@ public class NotesProvider extends ContentProvider {
}
return count;
}
//根据传入的查询条件 selection构造并返回一个 SQL 语句的 WHERE 子句。如果传入的查询条件非空,则在前面添加 " AND "。
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
//用于更新备忘录版本号。它构建一个 SQL UPDATE 语句将备忘录版本号NoteColumns.VERSION加一。
//如果传入了备忘录的 ID 或其他查询条件,则会附加到 WHERE 子句中,以确定更新的是哪个备忘录。
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
@ -297,6 +323,7 @@ public class NotesProvider extends ContentProvider {
}
@Override
//这个方法返回给定 URI 的 MIME 类型。在这里,方法未实现,返回了 null
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;

@ -24,12 +24,13 @@ import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
//定义了一个名为 MetaData 的类,它继承自 Task 类
public class MetaData extends Task {
//声明了一个私有静态常量字符串 TAG用于记录日志。
private final static String TAG = MetaData.class.getSimpleName();
//声明了一个私有字符串变量 mRelatedGid初始值为 null。
private String mRelatedGid = null;
//定义了一个公有方法 setMeta用于设置元数据信息。
public void setMeta(String gid, JSONObject metaInfo) {
try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
@ -39,19 +40,23 @@ public class MetaData extends Task {
setNotes(metaInfo.toString());
setName(GTaskStringUtils.META_NOTE_NAME);
}
//定义了一个公有方法 getRelatedGid用于获取相关联的任务 ID。
public String getRelatedGid() {
return mRelatedGid;
}
@Override
//重写了父类的方法 isWorthSaving。
public boolean isWorthSaving() {
return getNotes() != null;
}
@Override
//重写了父类的方法 setContentByRemoteJSON。
public void setContentByRemoteJSON(JSONObject js) {
//调用父类相同方法,然后解析任务的笔记内容中的 JSON 对象。
super.setContentByRemoteJSON(js);
//提取其中的任务 ID 并存储在 mRelatedGid 中,若解析失败则记录日志。
if (getNotes() != null) {
try {
JSONObject metaInfo = new JSONObject(getNotes().trim());
@ -64,18 +69,23 @@ public class MetaData extends Task {
}
@Override
//重写了父类的方法 setContentByLocalJSON。
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
// 抛出异常,表示不应调用此方法。
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
@Override
//重写了父类的方法 getLocalJSONFromContent。
public JSONObject getLocalJSONFromContent() {
//抛出异常,表示不应调用此方法。
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
@Override
//重写了父类的方法 getSyncAction。
public int getSyncAction(Cursor c) {
//抛出异常,表示不应调用此方法。
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
}

@ -19,7 +19,9 @@ package net.micode.notes.gtask.data;
import android.database.Cursor;
import org.json.JSONObject;
//常量定义
//定义了一系列抽象方法,子类需要实现这些方法以满足具体的节点类型的需求,
//如创建操作、更新操作、设置远程 JSON 内容、设置本地 JSON 内容、获取本地 JSON 内容、获取同步操作等。
public abstract class Node {
public static final int SYNC_ACTION_NONE = 0;
@ -65,7 +67,9 @@ public abstract class Node {
public abstract JSONObject getLocalJSONFromContent();
public abstract int getSyncAction(Cursor c);
//成员变量的 Getter 和 Setter 方法
//提供了一系列公有的 Getter 和 Setter 方法,
//用于获取和设置节点的属性,包括全局唯一标识 (Gid)、名称 (Name)、最后修改时间 (LastModified) 和删除状态 (Deleted)。
public void setGid(String gid) {
this.mGid = gid;
}

@ -34,10 +34,11 @@ import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException;
import org.json.JSONObject;
//声明了 SqlData 类,用于处理数据表的操作。
public class SqlData {
//常量定义和类成员
private static final String TAG = SqlData.class.getSimpleName();
//定义了常量 INVALID_ID 和 PROJECTION_DATA以及数据表列的索引常量。
private static final int INVALID_ID = -99999;
public static final String[] PROJECTION_DATA = new String[] {
@ -54,7 +55,8 @@ public class SqlData {
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
// ... 其他 PROJECTION_DATA 列索引的常量定义
//声明了类成员,包括 ContentResolver 对象,标志是否创建数据 (mIsCreate),数据表的各个字段值,以及用于存储差异的 ContentValues 对象。
private ContentResolver mContentResolver;
private boolean mIsCreate;
@ -70,8 +72,9 @@ public class SqlData {
private String mDataContentData3;
private ContentValues mDiffDataValues;
//构造函数接受一个 Context 参数,用于获取 ContentResolver。
public SqlData(Context context) {
// 初始化类成员,包括标志是否创建数据 (mIsCreate)、数据表的字段值、ContentValues 对象等。
mContentResolver = context.getContentResolver();
mIsCreate = true;
mDataId = INVALID_ID;
@ -81,14 +84,16 @@ public class SqlData {
mDataContentData3 = "";
mDiffDataValues = new ContentValues();
}
//构造函数接受一个 Context 和一个 Cursor 参数,用于从数据库中加载数据。
public SqlData(Context context, Cursor c) {
//初始化类成员,包括标志是否创建数据 (mIsCreate)、通过 loadFromCursor 方法加载数据,以及 ContentValues 对象。
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDiffDataValues = new ContentValues();
}
//私有方法 loadFromCursor 用于从 Cursor 对象加载数据,将各个字段值赋给相应的成员变量。
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -96,9 +101,11 @@ public class SqlData {
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
//私有方法 loadFromCursor 用于从 Cursor 对象加载数据,将各个字段值赋给相应的成员变量。
//setContent 方法接受一个 JSONObject 参数,用于将其内容设置到类的成员变量中。
public void setContent(JSONObject js) throws JSONException {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
//根据 JSON 对象中的数据,更新相应的成员变量,并将差异存储在 mDiffDataValues 中。
if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId);
}
@ -129,8 +136,9 @@ public class SqlData {
}
mDataContentData3 = dataContentData3;
}
//getContent 方法用于获取成员变量的数据,并返回一个 JSON 对象表示该数据。
public JSONObject getContent() throws JSONException {
//若对象处于创建状态 (mIsCreate),则返回 null
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
@ -143,9 +151,9 @@ public class SqlData {
js.put(DataColumns.DATA3, mDataContentData3);
return js;
}
//commit 方法用于提交数据到数据库,包括插入新数据和更新已有数据。
public void commit(long noteId, boolean validateVersion, long version) {
//插入新数据时,将 mDiffDataValues 中的差异值插入数据库,更新 mDataId。
if (mIsCreate) {
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID);
@ -160,6 +168,7 @@ public class SqlData {
throw new ActionFailureException("create note failed");
}
} else {
//更新已有数据时,根据是否需要验证版本,执行不同的数据库更新操作。
if (mDiffDataValues.size() > 0) {
int result = 0;
if (!validateVersion) {
@ -182,7 +191,7 @@ public class SqlData {
mDiffDataValues.clear();
mIsCreate = false;
}
//getId 方法用于获取数据的 ID。
public long getId() {
return mDataId;
}

@ -37,8 +37,9 @@ import org.json.JSONObject;
import java.util.ArrayList;
//SqlNote 类用于处理笔记的数据库操作。
public class SqlNote {
//包含常量定义和列索引的声明,以及类成员的定义。
private static final String TAG = SqlNote.class.getSimpleName();
private static final int INVALID_ID = -99999;
@ -86,6 +87,7 @@ public class SqlNote {
public static final int VERSION_COLUMN = 16;
private Context mContext;
private ContentResolver mContentResolver;
@ -121,8 +123,9 @@ public class SqlNote {
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
//构构造函数接受一个 Context 参数,用于获取 ContentResolver。
public SqlNote(Context context) {
//初始化各个类成员,包括标志是否创建数据 (mIsCreate)、笔记的各种属性、ContentValues 对象以及数据列表。
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = true;
@ -142,31 +145,36 @@ public class SqlNote {
mDiffNoteValues = new ContentValues();
mDataList = new ArrayList<SqlData>();
}
//构造函数接受一个 Context 和一个 Cursor 参数,用于从数据库中加载笔记数据。
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
//调用 loadFromCursor 方法加载数据,根据笔记类型加载数据内容。
loadFromCursor(c);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
//初始化 ContentValues 对象。
mDiffNoteValues = new ContentValues();
}
// 构造函数接受一个 Context 和一个 long 类型的 ID 参数,用于从数据库中加载笔记数据。
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
//调用 loadFromCursor 方法加载数据,根据笔记类型加载数据内容。
loadFromCursor(id);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
//初始化 ContentValues 对象。
mDiffNoteValues = new ContentValues();
}
//loadFromCursor 方法用于从数据库或 Cursor 对象加载笔记数据。
private void loadFromCursor(long id) {
//根据 ID 或 Cursor 对象加载相应的数据,更新类成员。
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
@ -184,7 +192,7 @@ public class SqlNote {
c.close();
}
}
//// 从 Cursor 对象加载数据
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
@ -199,8 +207,9 @@ public class SqlNote {
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
mVersion = c.getLong(VERSION_COLUMN);
}
//loadDataContent 方法用于加载笔记的数据内容。
private void loadDataContent() {
//查询数据库,根据笔记 ID 获取相关的数据,构建 SqlData 对象,并添加到 mDataList 中。
Cursor c = null;
mDataList.clear();
try {
@ -225,8 +234,9 @@ public class SqlNote {
c.close();
}
}
//setContent 方法用于从 JSON 对象设置笔记的内容。
public boolean setContent(JSONObject js) {
//解析 JSON 对象,根据笔记类型设置不同的属性值,包括笔记的基本属性和数据内容。
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
@ -236,6 +246,7 @@ public class SqlNote {
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
//将差异存储在 mDiffNoteValues 中。
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
mSnippet = snippet;
@ -358,7 +369,7 @@ public class SqlNote {
}
return true;
}
// getContent 方法用于获取笔记的内容,并返回一个 JSON 对象表示该内容。
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
@ -406,42 +417,45 @@ public class SqlNote {
}
return null;
}
//Setter 方法
//setParentId 方法用于设置笔记的父 ID同时将差异存储在 mDiffNoteValues 中。
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
}
//setGtaskId 方法用于设置 GTask ID同样将差异存储在 mDiffNoteValues 中。
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
//setSyncId 方法用于设置同步 ID同样将差异存储在 mDiffNoteValues 中。
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
//resetLocalModified 方法用于重置本地修改标志,将其设置为 0。
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}
//getId 方法用于获取笔记的 ID。
public long getId() {
return mId;
}
//getParentId 方法用于获取笔记的父 ID。
public long getParentId() {
return mParentId;
}
//getSnippet 方法用于获取笔记的摘要。
public String getSnippet() {
return mSnippet;
}
//isNoteType 方法用于判断笔记是否为类型为 Notes.TYPE_NOTE。
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}
//commit 方法用于提交对笔记的更改到数据库。
public void commit(boolean validateVersion) {
//如果是新建笔记mIsCreate 为 true首先判断是否需要移除 ID然后插入数据获取新的 ID。
if (mIsCreate) {
//// 新建笔记的情况
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID);
}
@ -456,18 +470,20 @@ public class SqlNote {
if (mId == 0) {
throw new IllegalStateException("Create thread id failed");
}
// 提交新建笔记的数据内容
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1);
}
}
} else {
// 更新已存在的笔记的情况
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id");
}
if (mDiffNoteValues.size() > 0) {
// 更新笔记信息
mVersion ++;
int result = 0;
if (!validateVersion) {
@ -486,7 +502,7 @@ public class SqlNote {
Log.w(TAG, "there is no update. maybe user updates note when syncing");
}
}
// 提交笔记数据内容的更新
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion);
@ -494,7 +510,7 @@ public class SqlNote {
}
}
// refresh local info
// // 刷新本地信息
loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE)
loadDataContent();

@ -31,20 +31,26 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
// Task 类,继承自 Node 类
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;
// Task 类的构造函数
public Task() {
super();
mCompleted = false;
@ -54,6 +60,7 @@ public class Task extends Node {
mMetaInfo = null;
}
// 获取用于创建任务的 JSON 对象的方法
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -103,6 +110,7 @@ public class Task extends Node {
return js;
}
// 获取用于更新任务的 JSON 对象的方法
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -135,6 +143,7 @@ public class Task extends Node {
return js;
}
// 通过远程 JSON 设置任务内容的方法
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -175,10 +184,11 @@ public class Task extends Node {
}
}
// 通过本地 JSON 设置任务内容的方法
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
Log.w(TAG, "setContentByLocalJSON: nothing is available");
}
try {
@ -204,6 +214,7 @@ public class Task extends Node {
}
}
// 从任务内容获取本地 JSON 的方法
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
@ -247,6 +258,7 @@ public class Task extends Node {
}
}
// 设置元信息的方法
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
@ -258,6 +270,7 @@ public class Task extends Node {
}
}
// 获取同步操作类型的方法
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
@ -284,7 +297,7 @@ public class Task extends Node {
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
// no update both sides
return SYNC_ACTION_NONE;
} else {
// apply remote to local
@ -311,41 +324,49 @@ public class Task extends Node {
return SYNC_ACTION_ERROR;
}
// 判断任务是否值得保存的方法
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);
}
// 设置任务完成状态的方法
public void setCompleted(boolean completed) {
this.mCompleted = completed;
}
// 设置任务附注的方法
public void setNotes(String notes) {
this.mNotes = notes;
}
// 设置前一个同级任务的方法
public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling;
}
// 设置任务父任务列表的方法
public void setParent(TaskList parent) {
this.mParent = parent;
}
// 获取任务完成状态的方法
public boolean getCompleted() {
return this.mCompleted;
}
// 获取任务附注的方法
public String getNotes() {
return this.mNotes;
}
// 获取前一个同级任务的方法
public Task getPriorSibling() {
return this.mPriorSibling;
}
// 获取任务父任务列表的方法
public TaskList getParent() {
return this.mParent;
}
}

@ -29,20 +29,24 @@ import org.json.JSONObject;
import java.util.ArrayList;
// TaskList 类,继承自 Node 类
public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();
// 任务列表的索引
private int mIndex;
// 子任务列表
private ArrayList<Task> mChildren;
// TaskList 类的构造函数
public TaskList() {
super();
mChildren = new ArrayList<Task>();
mIndex = 1;
}
// 获取用于创建任务列表的 JSON 对象的方法
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -68,12 +72,13 @@ public class TaskList extends Node {
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-create jsonobject");
throw new ActionFailureException("生成任务列表创建 JSON 对象失败");
}
return js;
}
// 获取用于更新任务列表的 JSON 对象的方法
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -97,12 +102,13 @@ public class TaskList extends Node {
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-update jsonobject");
throw new ActionFailureException("生成任务列表更新 JSON 对象失败");
}
return js;
}
// 通过远程 JSON 设置任务列表内容的方法
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -124,14 +130,15 @@ public class TaskList extends Node {
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to get tasklist content from jsonobject");
throw new ActionFailureException("从 JSON 对象中获取任务列表内容失败");
}
}
}
// 通过本地 JSON 设置任务列表内容的方法
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
Log.w(TAG, "setContentByLocalJSON: 没有可用的内容");
}
try {
@ -147,9 +154,9 @@ public class TaskList extends Node {
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE);
else
Log.e(TAG, "invalid system folder");
Log.e(TAG, "无效的系统文件夹");
} else {
Log.e(TAG, "error type");
Log.e(TAG, "错误的类型");
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
@ -157,6 +164,7 @@ public class TaskList extends Node {
}
}
// 获取本地 JSON 对象从任务列表内容的方法
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();
@ -183,28 +191,29 @@ public class TaskList extends Node {
}
}
// 获取同步操作类型的方法
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
// 验证 GTask ID
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
Log.e(TAG, "GTask ID 不匹配");
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 +225,18 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR;
}
// 获取子任务数量的方法
public int getChildTaskCount() {
return mChildren.size();
}
// 添加子任务的方法
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,9 +245,10 @@ public class TaskList extends Node {
return ret;
}
// 添加子任务到指定位置的方法
public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index");
Log.e(TAG, "添加子任务:无效的索引");
return false;
}
@ -244,7 +256,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 +272,7 @@ public class TaskList extends Node {
return true;
}
// 移除子任务的方法
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
@ -267,11 +280,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,16 +294,17 @@ public class TaskList extends Node {
return ret;
}
// 移动子任务到指定位置的方法
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "move child task: invalid index");
Log.e(TAG, "移动子任务:无效的索引");
return false;
}
int pos = mChildren.indexOf(task);
if (pos == -1) {
Log.e(TAG, "move child task: the task should in the list");
Log.e(TAG, "移动子任务:任务应该在列表中");
return false;
}
@ -299,6 +313,7 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index));
}
// 通过 GTask ID 查找子任务的方法
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@ -309,18 +324,21 @@ public class TaskList extends Node {
return null;
}
// 获取子任务索引的方法
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
// 通过索引获取子任务的方法
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
Log.e(TAG, "getTaskByIndex: 无效的索引");
return null;
}
return mChildren.get(index);
}
// 通过 GTask ID 获取子任务的方法
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
@ -329,14 +347,17 @@ public class TaskList extends Node {
return null;
}
// 获取子任务列表的方法
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}
// 设置索引的方法
public void setIndex(int index) {
this.mIndex = index;
}
// 获取索引的方法
public int getIndex() {
return this.mIndex;
}

@ -16,18 +16,27 @@
package net.micode.notes.gtask.exception;
// ActionFailureException 类,继承自 RuntimeException 类
public class ActionFailureException extends RuntimeException {
private static final long serialVersionUID = 4425249765923293627L;
// 默认构造函数
public ActionFailureException() {
super();
}
// 带参数的构造函数,接受一个字符串参数
public ActionFailureException(String paramString) {
super(paramString);
}
// 带参数的构造函数,接受一个字符串参数和一个 Throwable 参数
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
}

@ -16,17 +16,21 @@
package net.micode.notes.gtask.exception;
// NetworkFailureException 类,继承自 Exception 类
public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L;
// 默认构造函数
public NetworkFailureException() {
super();
}
// 带参数的构造函数,接受一个字符串参数
public NetworkFailureException(String paramString) {
super(paramString);
}
// 带参数的构造函数,接受一个字符串参数和一个 Throwable 参数
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}

@ -29,40 +29,48 @@ import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
// GTaskASyncTask 类,继承自 AsyncTask用于执行后台同步任务
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// GTASK_SYNC_NOTIFICATION_ID同步通知的通知 ID
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
// OnCompleteListener 接口,用于监听同步任务完成事件
public interface OnCompleteListener {
void onComplete();
}
// 上下文对象
private Context mContext;
// 通知管理器
private NotificationManager mNotifiManager;
// GTaskManager 实例,用于执行同步操作
private GTaskManager mTaskManager;
// 同步任务完成监听器
private OnCompleteListener mOnCompleteListener;
// 构造函数,接受上下文和监听器作为参数
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotifiManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mTaskManager = GTaskManager.getInstance();
}
// 取消同步任务
public void cancelSync() {
mTaskManager.cancelSync();
}
// 更新同步进度信息
public void publishProgess(String message) {
publishProgress(new String[] {
message
});
publishProgress(new String[] { message });
}
// 显示通知
private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis());
@ -72,7 +80,6 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);
} else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
@ -82,23 +89,30 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
// 后台任务的具体执行逻辑
@Override
protected Integer doInBackground(Void... unused) {
// 发布同步登录的进度信息
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
// 执行同步任务并返回结果
return mTaskManager.sync(mContext, this);
}
// 更新同步进度
@Override
protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]);
// 如果上下文是 GTaskSyncService 的实例,则发送广播通知
if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]);
}
}
// 后台任务执行完毕的回调
@Override
protected void onPostExecute(Integer result) {
// 根据同步结果显示相应通知
if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount()));
@ -111,9 +125,9 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled));
}
// 如果存在同步完成监听器,则在新线程中执行 onComplete 方法
if (mOnCompleteListener != null) {
new Thread(new Runnable() {
public void run() {
mOnCompleteListener.onComplete();
}
@ -121,3 +135,4 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
}
}
}

@ -61,6 +61,7 @@ import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
// GTaskClient 类,用于处理与 Google 任务相关的网络请求和同步操作
public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName();
@ -90,6 +91,7 @@ public class GTaskClient {
private JSONArray mUpdateArray;
// 私有构造函数,确保单例模式
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
@ -102,6 +104,7 @@ public class GTaskClient {
mUpdateArray = null;
}
// 获取单例实例
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -109,15 +112,15 @@ public class GTaskClient {
return mInstance;
}
// 登录 Google 帐号
public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
// 假设 cookie 在 5 分钟后过期,需要重新登录
final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
// need to re-login after account switch
// 在帐户切换后需要重新登录
if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
@ -125,18 +128,18 @@ public class GTaskClient {
}
if (mLoggedin) {
Log.d(TAG, "already logged in");
Log.d(TAG, "已经登录");
return true;
}
mLastLoginTime = System.currentTimeMillis();
String authToken = loginGoogleAccount(activity, false);
if (authToken == null) {
Log.e(TAG, "login google account failed");
Log.e(TAG, "登录 Google 帐号失败");
return false;
}
// login with custom domain if necessary
// 如果不是 gmail.com 或 googlemail.com 结尾,则尝试使用自定义域登录
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
@ -151,7 +154,7 @@ public class GTaskClient {
}
}
// try to login with google official url
// 尝试使用 Google 官方 URL 登录
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
@ -164,13 +167,14 @@ public class GTaskClient {
return true;
}
// 登录 Google 帐号获取授权令牌
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
Account[] accounts = accountManager.getAccountsByType("com.google");
if (accounts.length == 0) {
Log.e(TAG, "there is no available google account");
Log.e(TAG, "没有可用的 Google 帐号");
return null;
}
@ -185,11 +189,11 @@ public class GTaskClient {
if (account != null) {
mAccount = account;
} else {
Log.e(TAG, "unable to get an account with the same name in the settings");
Log.e(TAG, "无法获取与设置中相同名称的帐号");
return null;
}
// get the token now
// 获取令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
@ -200,31 +204,32 @@ public class GTaskClient {
loginGoogleAccount(activity, false);
}
} catch (Exception e) {
Log.e(TAG, "get auth token failed");
Log.e(TAG, "获取授权令牌失败");
authToken = null;
}
return authToken;
}
// 尝试登录 Google 任务
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");
Log.e(TAG, "登录 Google 帐号失败");
return false;
}
if (!loginGtask(authToken)) {
Log.e(TAG, "login gtask failed");
Log.e(TAG, "登录 GTask 失败");
return false;
}
}
return true;
}
// 登录 GTask
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000;
@ -236,14 +241,14 @@ public class GTaskClient {
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
// 登录 GTask
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) {
@ -252,10 +257,10 @@ public class GTaskClient {
}
}
if (!hasAuthCookie) {
Log.w(TAG, "it seems that there is no auth cookie");
Log.w(TAG, "似乎没有授权 cookie");
}
// get the client version
// 获取客户端版本
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -272,18 +277,19 @@ public class GTaskClient {
e.printStackTrace();
return false;
} catch (Exception e) {
// simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed");
Log.e(TAG, "HttpGet GTask URL 失败");
return false;
}
return true;
}
// 获取动作 ID
private int getActionId() {
return mActionId++;
}
// 创建 HTTP POST 请求
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -291,11 +297,12 @@ public class GTaskClient {
return httpPost;
}
// 获取 HTTP 响应内容
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding);
Log.d(TAG, "编码: " + contentEncoding);
}
InputStream input = entity.getContent();
@ -323,10 +330,11 @@ public class GTaskClient {
}
}
// 发送 POST 请求
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
Log.e(TAG, "请先登录");
throw new ActionFailureException("未登录");
}
HttpPost httpPost = createHttpPost();
@ -336,7 +344,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);
@ -344,36 +352,37 @@ public class GTaskClient {
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
throw new NetworkFailureException("postRequest 失败");
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
throw new NetworkFailureException("postRequest 失败");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("unable to convert response content to jsonobject");
throw new ActionFailureException("无法将响应内容转换为 JSONObject");
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("error occurs when posting request");
throw new ActionFailureException("提交请求时发生错误");
}
}
// 创建任务
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
// 发送 POST 请求
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -382,24 +391,25 @@ public class GTaskClient {
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("create task: handing jsonobject failed");
throw new ActionFailureException("创建任务:处理 JSONObject 失败");
}
}
// 创建任务列表
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
// 发送 POST 请求
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -408,41 +418,45 @@ public class GTaskClient {
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("create tasklist: handing jsonobject failed");
throw new ActionFailureException("创建任务列表:处理 JSONObject 失败");
}
}
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
// 创建 JSON 对象
JSONObject jsPost = new JSONObject();
// action_list
// 添加动作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version
// 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送网络请求
postRequest(jsPost);
mUpdateArray = null;
} catch (JSONException e) {
// 处理 JSON 对象异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("commit update: handing jsonobject failed");
throw new ActionFailureException("commit update: 处理 JSONObject 失败");
}
}
}
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// too many update items may result in an error
// set max to 10 items
// 更新项过多可能导致错误最大限制为10项
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
if (mUpdateArray == null)
mUpdateArray = new JSONArray();
// 将节点的更新动作添加到更新数组中
mUpdateArray.put(node.getUpdateAction(getActionId()));
}
}
@ -451,76 +465,87 @@ public class GTaskClient {
throws NetworkFailureException {
commitUpdate();
try {
// 创建 JSON 对象
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
// 添加动作列表
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and
// it is not the first one
// 仅在任务列表内移动且不是第一个时,添加 prior_sibling_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
// 在任务列表间移动时,添加 dest_list
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);
} catch (JSONException e) {
// 处理 JSON 对象异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("move task: handing jsonobject failed");
throw new ActionFailureException("move task: 处理 JSONObject 失败");
}
}
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
try {
// 创建 JSON 对象
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
// 设置节点为已删除状态
node.setDeleted(true);
// 添加节点的更新动作到动作列表
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送网络请求
postRequest(jsPost);
mUpdateArray = null;
} catch (JSONException e) {
// 处理 JSON 对象异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("delete node: handing jsonobject failed");
throw new ActionFailureException("delete node: 处理 JSONObject 失败");
}
}
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
// 未登录时抛出异常
Log.e(TAG, "请先登录");
throw new ActionFailureException("未登录");
}
try {
// 创建 HTTP GET 请求
HttpGet httpGet = new HttpGet(mGetUrl);
HttpResponse response = null;
// 执行 HTTP GET 请求
response = mHttpClient.execute(httpGet);
// get the task list
// 获取任务列表
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -530,31 +555,37 @@ public class GTaskClient {
if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end);
}
// 解析 JSON 字符串
JSONObject js = new JSONObject(jsString);
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
} catch (ClientProtocolException e) {
// 处理 HTTP 请求异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
throw new NetworkFailureException("gettasklists: HTTP GET 请求失败");
} catch (IOException e) {
// 处理 IO 异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
throw new NetworkFailureException("gettasklists: HTTP GET 请求失败");
} catch (JSONException e) {
// 处理 JSON 对象异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task lists: handing jasonobject failed");
throw new ActionFailureException("get task lists: 处理 JSONObject 失败");
}
}
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
try {
// 创建 JSON 对象
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
// 添加动作列表
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
@ -563,15 +594,17 @@ 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);
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
} catch (JSONException e) {
// 处理 JSON 对象异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task list: handing jsonobject failed");
throw new ActionFailureException("get task list: 处理 JSONObject 失败");
}
}
@ -582,4 +615,4 @@ public class GTaskClient {
public void resetUpdateArray() {
mUpdateArray = null;
}
}

@ -51,41 +51,38 @@ import java.util.Map;
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;
// 同步状态常量
public static final int STATE_SUCCESS = 0; // 同步成功
public static final int STATE_NETWORK_ERROR = 1; // 网络错误
public static final int STATE_INTERNAL_ERROR = 2; // 内部错误
public static final int STATE_SYNC_IN_PROGRESS = 3; // 同步进行中
public static final int STATE_SYNC_CANCELLED = 4; // 同步被取消
private static GTaskManager mInstance = null;
private Activity mActivity;
private Activity mActivity; // 活动实例,用于获取认证令牌
private Context mContext;
private Context mContext; // 上下文
private ContentResolver mContentResolver;
private ContentResolver mContentResolver; // 内容解析器
private boolean mSyncing;
private boolean mSyncing; // 同步标志
private boolean mCancelled;
private boolean mCancelled; // 取消同步标志
private HashMap<String, TaskList> mGTaskListHashMap;
private HashMap<String, TaskList> mGTaskListHashMap; // 任务列表哈希映射
private HashMap<String, Node> mGTaskHashMap;
private HashMap<String, Node> mGTaskHashMap; // 任务哈希映射
private HashMap<String, MetaData> mMetaHashMap;
private HashMap<String, MetaData> mMetaHashMap; // 元数据哈希映射
private TaskList mMetaList;
private TaskList mMetaList; // 元数据列表
private HashSet<Long> mLocalDeleteIdMap;
private HashSet<Long> mLocalDeleteIdMap; // 本地删除 ID 集合
private HashMap<String, Long> mGidToNid;
private HashMap<String, Long> mGidToNid; // GID 到 NID 的映射
private HashMap<Long, String> mNidToGid;
private HashMap<Long, String> mNidToGid; // NID 到 GID 的映射
private GTaskManager() {
mSyncing = false;
@ -99,6 +96,7 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>();
}
// 获取 GTaskManager 单例实例
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@ -106,14 +104,15 @@ public class GTaskManager {
return mInstance;
}
// 设置活动实例,用于获取认证令牌
public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
mActivity = activity;
}
// 执行同步操作
public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
Log.d(TAG, "同步正在进行中");
return STATE_SYNC_IN_PROGRESS;
}
mContext = context;
@ -131,18 +130,18 @@ public class GTaskManager {
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
// login google task
// 登录 Google 任务
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed");
throw new NetworkFailureException("登录 Google 任务失败");
}
}
// 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) {
@ -167,27 +166,27 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
// 初始化GTask列表
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
GTaskClient client = GTaskClient.getInstance();
try {
// 获取所有任务列表
JSONArray jsTaskLists = client.getTaskLists();
// init meta list first
// 先初始化元信息列表
mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object);
// load meta data
// 加载元数据
JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j);
@ -203,29 +202,27 @@ public class GTaskManager {
}
}
// create meta list if not existed
// 如果元信息列表不存在,则创建
if (mMetaList == null) {
mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META);
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META);
GTaskClient.getInstance().createTaskList(mMetaList);
}
// init task list
// 初始化任务列表
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) {
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist);
// load tasks
// 加载任务
JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j);
@ -243,10 +240,11 @@ public class GTaskManager {
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("initGTaskList: handing JSONObject failed");
throw new ActionFailureException("initGTaskList: handling JSONObject failed");
}
}
// 执行内容同步
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;
@ -259,7 +257,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 +284,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 +304,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
// 本地新增
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
// 远程删除
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
@ -326,7 +324,7 @@ public class GTaskManager {
}
}
// go through remaining items
// 处理剩余的项目
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
@ -334,23 +332,22 @@ 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
// 逐个检查是否已被另一个线程设置了mCancelled标志
// 清除本地删除表
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();
}
}
// 同步文件夹
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
@ -361,7 +358,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 +370,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,7 +387,7 @@ public class GTaskManager {
}
}
// for call-note folder
// 处理通话笔记文件夹
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] {
@ -404,11 +401,9 @@ public class GTaskManager {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if
// necessary
// 对于系统文件夹,仅在必要时更新远程名称
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE))
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
@ -424,7 +419,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 +436,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
// 本地新增
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
// 远程删除
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
@ -460,7 +455,7 @@ public class GTaskManager {
}
}
// for remote add folders
// 处理远程新增的文件夹
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
@ -476,6 +471,7 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate();
}
// 执行内容同步
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -510,18 +506,19 @@ public class GTaskManager {
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea
// right now just use local update simply
// 合并两者的修改可能是个好主意
// 现在只是简单地使用本地更新
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_NONE:
break;
case Node.SYNC_ACTION_ERROR:
default:
throw new ActionFailureException("unkown sync action type");
throw new ActionFailureException("unknown sync action type");
}
}
// 添加本地节点
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
@ -596,58 +593,62 @@ public class GTaskManager {
updateRemoteMeta(node.getGid(), sqlNote);
}
// 更新本地节点
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
return; // 如果同步被取消,立即返回
}
SqlNote sqlNote;
// update the note locally
// 本地更新笔记内容
sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent());
// 获取父节点ID如果是任务则使用任务映射表查找否则使用根文件夹ID
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
: new Long(Notes.ID_ROOT_FOLDER);
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot update local node");
Log.e(TAG, "无法在本地找到任务的父节点ID");
throw new ActionFailureException("无法更新本地节点");
}
sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true);
// update meta info
// 更新远程元信息
updateRemoteMeta(node.getGid(), sqlNote);
}
// 添加远程节点
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
return; // 如果同步被取消,立即返回
}
SqlNote sqlNote = new SqlNote(mContext, c);
Node n;
// update remotely
// 远程更新
if (sqlNote.isNoteType()) {
Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent());
// 获取父任务列表的GID如果找不到则抛出异常
String parentGid = mNidToGid.get(sqlNote.getParentId());
if (parentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot add remote task");
Log.e(TAG, "无法在本地找到任务的父任务列表");
throw new ActionFailureException("无法添加远程任务");
}
mGTaskListHashMap.get(parentGid).addChildTask(task);
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 +672,7 @@ public class GTaskManager {
}
}
// no match we can add now
// 如果没有匹配,则现在可以添加
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
@ -681,43 +682,46 @@ 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());
}
// 更新远程节点
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
return; // 如果同步被取消,立即返回
}
SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely
// 远程更新节点内容
node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node);
// update meta
// 更新元信息
updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary
// 如果是任务,则移动任务
if (sqlNote.isNoteType()) {
Task task = (Task) node;
TaskList preParentList = task.getParent();
// 获取当前父任务列表的GID如果找不到则抛出异常
String curParentGid = mNidToGid.get(sqlNote.getParentId());
if (curParentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot update remote task");
Log.e(TAG, "无法在本地找到任务的父任务列表");
throw new ActionFailureException("无法更新远程任务");
}
TaskList curParentList = mGTaskListHashMap.get(curParentGid);
// 如果前一个父任务列表与当前不同,则移动任务
if (preParentList != curParentList) {
preParentList.removeChildTask(task);
curParentList.addChildTask(task);
@ -725,11 +729,12 @@ public class GTaskManager {
}
}
// clear local modified flag
// 清除本地修改标志
sqlNote.resetLocalModified();
sqlNote.commit(true);
}
// 更新远程元信息
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
@ -746,12 +751,13 @@ public class GTaskManager {
}
}
// 刷新本地同步ID
private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) {
return;
return; // 如果同步被取消,立即返回
}
// get the latest gtask list
// 获取最新的GTask列表
mGTaskHashMap.clear();
mGTaskListHashMap.clear();
mMetaHashMap.clear();
@ -759,6 +765,7 @@ public class GTaskManager {
Cursor c = null;
try {
// 查询本地笔记,排除系统类型和垃圾箱
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
@ -774,13 +781,13 @@ public class GTaskManager {
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
c.getLong(SqlNote.ID_COLUMN)), values, null, null);
} else {
Log.e(TAG, "something is missed");
Log.e(TAG, "有一些遗漏了");
throw new ActionFailureException(
"some local items don't have gid after sync");
"同步后某些本地项没有GID");
}
}
} else {
Log.w(TAG, "failed to query local note to refresh sync id");
Log.w(TAG, "查询本地笔记以刷新同步ID失败");
}
} finally {
if (c != null) {
@ -790,11 +797,12 @@ public class GTaskManager {
}
}
// 获取同步账户名
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}
// 取消同步
public void cancelSync() {
mCancelled = true;
}
}

@ -24,28 +24,40 @@ import android.os.Bundle;
import android.os.IBinder;
public class GTaskSyncService extends Service {
// 同步操作类型的字符串名称
public final static String ACTION_STRING_NAME = "sync_action_type";
// 启动同步的操作类型
public final static int ACTION_START_SYNC = 0;
// 取消同步的操作类型
public final static int ACTION_CANCEL_SYNC = 1;
// 无效的操作类型
public final static int ACTION_INVALID = 2;
// 广播的名称
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
// 广播中表示是否正在同步的标志
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() {
public void onComplete() {
// 同步完成后的回调,清空任务实例,发送广播通知
mSyncTask = null;
sendBroadcast("");
stopSelf();
@ -56,6 +68,7 @@ public class GTaskSyncService extends Service {
}
}
// 取消当前同步任务
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
@ -64,18 +77,22 @@ public class GTaskSyncService extends Service {
@Override
public void onCreate() {
// 服务创建时初始化同步任务实例
mSyncTask = null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 处理服务启动命令
Bundle bundle = intent.getExtras();
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
case ACTION_START_SYNC:
// 启动同步
startSync();
break;
case ACTION_CANCEL_SYNC:
// 取消同步
cancelSync();
break;
default:
@ -88,15 +105,18 @@ public class GTaskSyncService extends Service {
@Override
public void onLowMemory() {
// 在低内存时取消同步任务
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
// 绑定服务时的回调
public IBinder onBind(Intent intent) {
return null;
}
// 发送同步进度广播
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -105,24 +125,32 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent);
}
// 静态方法:启动同步
public static void startSync(Activity activity) {
// 设置 GTaskManager 的活动上下文
GTaskManager.getInstance().setActivityContext(activity);
// 创建并启动服务
Intent intent = new Intent(activity, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
activity.startService(intent);
}
// 静态方法:取消同步
public static void cancelSync(Context context) {
// 创建并启动服务,执行取消同步操作
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
}
// 静态方法:检查是否正在同步
public static boolean isSyncing() {
return mSyncTask != null;
}
// 静态方法:获取同步进度消息
public static String getProgressString() {
return mSyncProgress;
}
}

@ -33,16 +33,22 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
//这个类用于表示笔记的实体,包含对笔记的各种操作和属性。注释提供了对各个部分功能的解释。
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);
@ -56,69 +62,74 @@ public class Note {
try {
noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
Log.e(TAG, "获取笔记 id 出错:" + e.toString());
noteId = 0;
}
if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId);
throw new IllegalStateException("错误的笔记 id" + noteId);
}
return noteId;
}
// 构造函数,初始化笔记差异和笔记数据
public Note() {
mNoteDiffValues = new ContentValues();
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 setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
// 设置文本数据的 id
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
// 获取文本数据的 id
public long getTextDataId() {
return mNoteData.mTextDataId;
}
// 设置通话数据的 id
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}
// 设置通话数据的方法
public void setCallData(String key, String value) {
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);
throw new IllegalArgumentException("错误的笔记 id" + noteId);
}
if (!isLocalModified()) {
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
*/
// 理论上,一旦数据发生变化,就应该更新笔记的 LOCAL_MODIFIED 和 MODIFIED_DATE
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
Log.e(TAG, "更新笔记出错,不应该发生");
// 不要返回,继续执行
}
mNoteDiffValues.clear();
@ -130,6 +141,7 @@ public class Note {
return true;
}
// 内部类 NoteData 用于管理笔记的文本和通话数据
private class NoteData {
private long mTextDataId;
@ -141,6 +153,7 @@ public class Note {
private static final String TAG = "NoteData";
// 构造函数,初始化文本和通话数据
public NoteData() {
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
@ -148,48 +161,52 @@ public class Note {
mCallDataId = 0;
}
// 检查是否本地修改的方法
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
// 设置文本数据的 id
void setTextDataId(long id) {
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
if (id <= 0) {
throw new IllegalArgumentException("文本数据 id 应大于 0");
}
mTextDataId = id;
}
// 设置通话数据的 id
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
throw new IllegalArgumentException("通话数据 id 应大于 0");
}
mCallDataId = id;
}
// 设置通话数据的方法
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
// 设置文本数据的方法
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
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);
throw new IllegalArgumentException("错误的笔记 id" + noteId);
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) {
if (mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
@ -198,7 +215,7 @@ public class Note {
try {
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
Log.e(TAG, "插入新文本数据失败,笔记 id" + noteId);
mTextDataValues.clear();
return null;
}
@ -211,7 +228,7 @@ public class Note {
mTextDataValues.clear();
}
if(mCallDataValues.size() > 0) {
if (mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
@ -220,7 +237,7 @@ public class Note {
try {
setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new call data fail with noteId" + noteId);
Log.e(TAG, "插入新通话数据失败,笔记 id" + noteId);
mCallDataValues.clear();
return null;
}
@ -251,3 +268,4 @@ public class Note {
}
}
}

@ -32,36 +32,51 @@ import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
//这个类用于表示工作笔记的实体,包含对工作笔记的各种操作和属性。注释提供了对各个部分功能的解释。
public class WorkingNote {
// Note for the working note
// 工作笔记的实体 Note
private Note mNote;
// Note Id
// 笔记 Id
private long mNoteId;
// Note content
// 笔记内容
private String mContent;
// Note mode
// 笔记模式
private int mMode;
// 提醒日期
private long mAlertDate;
// 修改日期
private long mModifiedDate;
// 背景颜色 Id
private int mBgColorId;
// Widget Id
private int mWidgetId;
// Widget 类型
private int mWidgetType;
// 文件夹 Id
private long mFolderId;
// 上下文对象
private Context mContext;
// 日志标签
private static final String TAG = "WorkingNote";
// 标记笔记是否已删除
private boolean mIsDeleted;
// 笔记设置状态变化监听器
private NoteSettingChangedListener mNoteSettingStatusListener;
// 数据查询投影
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
@ -72,6 +87,7 @@ public class WorkingNote {
DataColumns.DATA4,
};
// 笔记查询投影
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
@ -81,27 +97,21 @@ public class WorkingNote {
NoteColumns.MODIFIED_DATE
};
// 数据查询列索引
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;
// New note construct
// 创建空白笔记的构造方法
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
@ -114,7 +124,7 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
}
// Existing note construct
// 创建已存在的笔记的构造方法
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
@ -124,6 +134,7 @@ public class WorkingNote {
loadNote();
}
// 加载笔记的方法
private void loadNote() {
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
@ -140,16 +151,17 @@ public class WorkingNote {
}
cursor.close();
} else {
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
Log.e(TAG, "没有找到 id 为:" + mNoteId + " 的笔记");
throw new IllegalArgumentException("找不到 id 为 " + mNoteId + " 的笔记");
}
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) {
@ -163,17 +175,18 @@ public class WorkingNote {
} else if (DataConstants.CALL_NOTE.equals(type)) {
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else {
Log.d(TAG, "Wrong note type with type:" + type);
Log.d(TAG, "错误的笔记类型:" + type);
}
} while (cursor.moveToNext());
}
cursor.close();
} else {
Log.e(TAG, "No data with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
Log.e(TAG, "没有找到 id 为:" + mNoteId + " 的数据");
throw new IllegalArgumentException("找不到 id 为 " + mNoteId + " 的笔记数据");
}
}
// 创建一个空白的工作笔记
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
@ -183,15 +196,17 @@ 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()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId);
Log.e(TAG, "创建新的笔记失败id" + mNoteId);
return false;
}
}
@ -199,7 +214,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
@ -212,10 +227,12 @@ public class WorkingNote {
}
}
// 检查笔记是否存在于数据库中
public boolean existInDatabase() {
return mNoteId > 0;
}
// 判断是否值得保存
private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
@ -225,10 +242,12 @@ public class WorkingNote {
}
}
// 设置设置状态变化监听器
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}
// 设置提醒日期
public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) {
mAlertDate = date;
@ -239,14 +258,16 @@ 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 +278,7 @@ public class WorkingNote {
}
}
// 设置检查列表模式
public void setCheckListMode(int mode) {
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
@ -267,6 +289,7 @@ public class WorkingNote {
}
}
// 设置小部件类型
public void setWidgetType(int type) {
if (type != mWidgetType) {
mWidgetType = type;
@ -274,6 +297,7 @@ public class WorkingNote {
}
}
// 设置小部件 Id
public void setWidgetId(int id) {
if (id != mWidgetId) {
mWidgetId = id;
@ -281,6 +305,7 @@ public class WorkingNote {
}
}
// 设置工作文本
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
@ -288,81 +313,96 @@ public class WorkingNote {
}
}
// 转换为通话笔记
public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
}
// 是否有闹钟提醒
public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false);
}
// 获取笔记内容
public String getContent() {
return mContent;
}
// 获取提醒日期
public long getAlertDate() {
return mAlertDate;
}
// 获取修改日期
public long getModifiedDate() {
return mModifiedDate;
}
// 获取背景颜色资源 Id
public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId);
}
// 获取背景颜色 Id
public int getBgColorId() {
return mBgColorId;
}
// 获取标题背景资源 Id
public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId);
}
// 获取检查列表模式
public int getCheckListMode() {
return mMode;
}
// 获取笔记 Id
public long getNoteId() {
return mNoteId;
}
// 获取文件夹 Id
public long getFolderId() {
return mFolderId;
}
// 获取小部件 Id
public int getWidgetId() {
return mWidgetId;
}
// 获取小部件类型
public int getWidgetType() {
return mWidgetType;
}
// 笔记设置状态变化监听器接口
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
*
* @param oldMode
* @param newMode
*/
void onCheckListModeChanged(int oldMode, int newMode);
}
}

@ -37,6 +37,7 @@ import java.util.HashSet;
public class DataUtils {
public static final String TAG = "DataUtils";
////直接删除多个笔记
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) {
Log.d(TAG, "the ids is null");
@ -46,19 +47,19 @@ public class DataUtils {
Log.d(TAG, "no id is in the hashset");
return true;
}
// //提供一个任务列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;
}
}////如果发现是根文件夹,则不删除
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));//实现删除功能
operationList.add(builder.build());
}
try {
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);////主机名或叫Authority用于唯一标识这个ContentProvider外部调用者可以根据这个标识来找到它。
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
@ -71,8 +72,8 @@ public class DataUtils {
}
return false;
}
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
//移动notes到指定文件夹folder
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {//moveNoteToFoler 方法用于将单个note移动到目标文件夹
ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, desFolderId);
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
@ -81,23 +82,23 @@ public class DataUtils {
}
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
long folderId) {//用于批量移动多个notes到目标文件夹
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();//用于存储要执行的批量更新操作。
for (long id : ids) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
ContentProviderOperation.Builder builder = ContentProviderOperation//ContentProviderOperation.Builder 对象,并设置要更新的属性值。然后,它将操作添加到操作列表中
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));////通过withAppendedId方法为该Uri加上ID
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
operationList.add(builder.build());
}
try {
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);//使用 ContentResolver 的 applyBatch() 方法将操作列表应用到数据提供者。
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
@ -114,29 +115,31 @@ public class DataUtils {
/**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*/
//获取用户文件夹user folder的数量
public static int getUserFolderCount(ContentResolver resolver) {
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null);
null);////筛选条件源文件不为trash folder
int count = 0;
if(cursor != null) {
if(cursor.moveToFirst()) {
try {
count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) {
} catch (IndexOutOfBoundsException e) {//故障处理
Log.e(TAG, "get folder count failed:" + e.toString());
} finally {
cursor.close();
cursor.close();//关闭资源
}
}
}
return count;
return count;//返回文件数量
}
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
//检查指定的笔记在笔记数据库中是否可见
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {//使用 ContentResolver 的 query() 方法执行一个查询操作,以检查指定的笔记是否可见。
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
@ -148,11 +151,11 @@ public class DataUtils {
if (cursor.getCount() > 0) {
exist = true;
}
cursor.close();
cursor.close();//释放资源。
}
return exist;
}
//检查指定的note是否存在于数据库中
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
@ -166,7 +169,7 @@ public class DataUtils {
}
return exist;
}
//检查指定的数据项是否存在于数据数据库中
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
@ -178,15 +181,16 @@ public class DataUtils {
}
cursor.close();
}
return exist;
return exist;//方法返回一个布尔值,表示指定的数据项是否存在于数据数据库中。
}
//通过执行查询操作检查在可见的文件夹中是否存在具有指定名称的文件夹,并返回相应的布尔值结果。
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 + "=?",
new String[] { name }, null);
//通过名字查询文件是否存在
boolean exist = false;
if(cursor != null) {
if(cursor.getCount() > 0) {
@ -196,35 +200,35 @@ public class DataUtils {
}
return exist;
}
//获取指定文件夹下的所有note小部件的属性集合
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
new String[] { String.valueOf(folderId) },
null);
null);//查询条件父ID是传入的folderId;
HashSet<AppWidgetAttribute> set = null;
HashSet<AppWidgetAttribute> set = null;//存储属性集合
if (c != null) {
if (c.moveToFirst()) {
set = new HashSet<AppWidgetAttribute>();
do {
try {
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
widget.widgetId = c.getInt(0);////0对应的NoteColumns.WIDGET_ID
widget.widgetType = c.getInt(1);//1对应的NoteColumns.WIDGET_TYPE
set.add(widget);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString());
}
} while (c.moveToNext());
} while (c.moveToNext());//查询下一条
}
c.close();
}
return set;
}
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
//通过noteID获取相关的电话号码
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {//获取与指定笔记ID相关的电话号码
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
@ -234,7 +238,7 @@ public class DataUtils {
if (cursor != null && cursor.moveToFirst()) {
try {
return cursor.getString(0);
} catch (IndexOutOfBoundsException e) {
} catch (IndexOutOfBoundsException e) {//异常处理
Log.e(TAG, "Get call number fails " + e.toString());
} finally {
cursor.close();
@ -242,7 +246,7 @@ public class DataUtils {
}
return "";
}
//通过电话号码和通话日期获取相关的ID
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
@ -250,7 +254,7 @@ public class DataUtils {
+ CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
//通过数据库操作查询条件是callDate和phoneNumber匹配传入参数的值
if (cursor != null) {
if (cursor.moveToFirst()) {
try {
@ -263,13 +267,13 @@ public class DataUtils {
}
return 0;
}
//通过ID获取相应的摘要snippet
public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)},
null);
null);////查询条件noteId
if (cursor != null) {
String snippet = "";
@ -279,10 +283,10 @@ public class DataUtils {
cursor.close();
return snippet;
}
throw new IllegalArgumentException("Note is not found with id: " + noteId);
throw new IllegalArgumentException("Note is not found with id: " + noteId);//没有找到相关笔记,代码将抛出异常。
}
public static String getFormattedSnippet(String snippet) {
public static String getFormattedSnippet(String snippet) {//对字符串进行格式处理,将字符串两头的空格去掉,同时将换行符去掉
if (snippet != null) {
snippet = snippet.trim();
int index = snippet.indexOf('\n');

@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//定义了一个名为 GTaskStringUtils 的工具类,其中包含了一些字符串常量
package net.micode.notes.tool;
jsonObject"key"
public class GTaskStringUtils {
public final static String GTASK_JSON_ACTION_ID = "action_id";

@ -13,6 +13,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*使
* R.java
* R.id
* R.drawable 使
* R.layout
* R.menu
* R.String
* R.style 使
* idgetXXX
*
*
* @BG_DEFAULT_COLOR
* BG_DEFAULT_FONT_SIZE
*/
package net.micode.notes.tool;
@ -161,7 +175,7 @@ public class ResourceParser {
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
};
////这里有一个容错的函数防止输入的id大于资源总量若如此则自动返回默认的设置结果
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.

@ -41,58 +41,64 @@ import java.io.IOException;
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId;
private String mSnippet;
private long mNoteId; //文本在数据库存储中的ID号
private String mSnippet;//闹钟提示时出现的文本片段
private static final int SNIPPET_PREW_MAX_LEN = 60;
MediaPlayer mPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Bundle类型的数据与Map类型的数据相似都是以key-value的形式存储数据的
//onsaveInstanceState方法是用来保存Activity的状态的
//能从onCreate的参数savedInsanceState中获得状态数据
requestWindowFeature(Window.FEATURE_NO_TITLE);
//界面显示——无标题
final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
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 {
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);//根据ID从数据库中获取标签的内容
//判断标签片段是否达到符合长度
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) {
} catch (IllegalArgumentException e) {//抛出异常
e.printStackTrace();
return;
}
mPlayer = new MediaPlayer();
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog();
showActionDialog();//弹出对话框
playAlarmSound();
} else {
finish();
finish();//完成闹钟操作
}
}
//isScreenOn() 方法用于检查设备屏幕是否处于开启状态
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
}
//playAlarmSound() 方法用于播放警报声音
private void playAlarmSound() {
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);//获取警报铃声的 URI
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);//获取静音模式对应的音频流。
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
@ -101,10 +107,10 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
}
try {
mPlayer.setDataSource(this, url);
mPlayer.prepare();
mPlayer.setLooping(true);
mPlayer.start();
} catch (IllegalArgumentException e) {
mPlayer.prepare();//准备播放器。
mPlayer.setLooping(true);//设置循环播放
mPlayer.start();//开始播放铃声。
} catch (IllegalArgumentException e) {//抛出异常
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
@ -118,25 +124,25 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
e.printStackTrace();
}
}
//showActionDialog() 方法用于显示一个带有动作选项的对话框
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);//设置对话框的消息内容为一个成员变量 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);//显示对话框,并使用 setOnDismissListener(this) 设置对话框的消失监听器为当前类。
}
//DialogInterface.OnClickListener 接口的回调方法,用于处理对话框按钮的点击事件
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);
startActivity(intent);
startActivity(intent);//启动目标活动。
break;
default:
break;
@ -144,14 +150,14 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
}
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
stopAlarmSound( //停止闹钟声音
finish();
}
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer.stop();//停止播放
mPlayer.release();//释放MediaPlayer对象
mPlayer = null;
}
}

@ -34,18 +34,23 @@ public class AlarmInitReceiver extends BroadcastReceiver {
NoteColumns.ID,
NoteColumns.ALERTED_DATE
};
//对数据库的操作调用标签ID和闹钟时间
private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1;
@Override
public void onReceive(Context context, Intent intent) {
long currentDate = System.currentTimeMillis();
//System.currentTimeMillis()产生一个当前的毫秒
//这个毫秒其实就是自1970年1月1日0时起的毫秒数
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
new String[] { String.valueOf(currentDate) },
new String[] { String.valueOf(currentDate) },//将long变量currentDate转化为字符串
null);
//Cursor在这里的作用是通过查找数据库中的标签内容找到和当前系统时间相等的标签
//这里就是根据数据库里的闹钟时间创建一个闹钟机制
if (c != null) {
if (c.moveToFirst()) {

@ -24,7 +24,13 @@ public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
intent.setClass(context, AlarmAlertActivity.class);
//启动AlarmAlertActivit
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//activity要存在于activity的栈中而非activity的途径启动activity时必然不存在一个activity的栈
//所以要新起一个栈装入启动的activity
context.startActivity(intent);
}
}
//这是实现alarm这个功能最接近用户层的包基于上面的两个包
//作用还需要深究但是对于setClass和addFlags的

@ -45,13 +45,15 @@ public class DateTimePicker extends FrameLayout {
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;
//NumberPicker是数字选择器
//这里定义的四个变量全部是在设置闹钟时需要选择的变量(如日期、时、分、上午或者下午)
private Calendar mDate;
//定义了Calendar类型的变量mDate用于操作时间
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
private boolean mIsAm;
@ -71,13 +73,16 @@ public class DateTimePicker extends FrameLayout {
updateDateControl();
onDateTimeChanged();
}
};
};//OnValueChangeListener这是时间改变监听器这里主要是对日期的监听
//这里是对 小时Hour 的监听
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;
//声明一个Calendar的变量cal便于后续的操作
Calendar cal = Calendar.getInstance();
//这里是对于12小时制时晚上11点和12点交替时对日期的更改
if (!mIs24HourView) {
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
@ -87,25 +92,27 @@ public class DateTimePicker extends FrameLayout {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
}//这里是对于12小时制时凌晨11点和12点交替时对日期的更改
/121112AMPM
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 {
} else { //这里是对于24小时制时晚上11点和12点交替时对日期的更改
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) {
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {//这里是对于12小时制时凌晨11点和12点交替时对日期的更改
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
}
//通过数字选择器对newHour的赋值
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour);
mDate.set(Calendar.HOUR_OF_DAY, newHour);//通过set函数将新的Hour值传给mDate
onDateTimeChanged();
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
@ -114,7 +121,7 @@ public class DateTimePicker extends FrameLayout {
}
}
};
//这里是对 分钟Minute改变的监听
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
@ -143,11 +150,12 @@ public class DateTimePicker extends FrameLayout {
onDateTimeChanged();
}
};
//用于监听时间选择器中上午/下午的变化事件。
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {//获取时间选择器控件。
mIsAm = !mIsAm;
//根据当前的上午/下午状态 mIsAm切换状态取反
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else {
@ -157,27 +165,28 @@ public class DateTimePicker extends FrameLayout {
onDateTimeChanged();
}
};
//用于定义日期时间发生变化时的回调方法。
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
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));
}
//用于初始化日期时间选择器控件的各个部分,并设置初始状态。
public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context);
mDate = Calendar.getInstance();
mDate = Calendar.getInstance();//创建一个 Calendar 实例 mDate表示日期和时间
mInitialising = true;
//根据当前小时是否大于等于半天的小时数 HOURS_IN_HALF_DAY设置上午/下午的状态 mIsAm
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
inflate(context, R.layout.datetime_picker, this);
//通过 findViewById() 方法获取日期、小时、分钟和上午/下午选择器的实例,并设置相应的监听器和属性。
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
@ -198,14 +207,14 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state
// update controls to initial state更新日期、小时和上午/下午控件的显示。
updateDateControl();
updateHourControl();
updateAmPmControl();
//根据传入的参数设置是否为 24 小时制。
set24HourView(is24HourView);
// set to current time
// set to current time设置当前的日期和时间。
setCurrentDate(date);
setEnabled(isEnabled());
@ -213,7 +222,7 @@ public class DateTimePicker extends FrameLayout {
// set the content descriptions
mInitialising = false;
}
//重写了 setEnabled() 方法,用于设置日期时间选择器及其各个部分的启用状态
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
@ -246,6 +255,7 @@ public class DateTimePicker extends FrameLayout {
*
* @param date The current date in millis
*/
//定义了一个 setCurrentDate() 方法,用于设置日期时间选择器的当前日期和时间
public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date);
@ -262,6 +272,7 @@ public class DateTimePicker extends FrameLayout {
* @param hourOfDay The current hourOfDay
* @param minute The current minute
*/
//设置日期时间选择器的当前日期和时间
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
@ -433,7 +444,7 @@ public class DateTimePicker extends FrameLayout {
setCurrentHour(hour);
updateAmPmControl();
}
//// 对于星期几的算法
private void updateDateControl() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis());
@ -447,7 +458,7 @@ public class DateTimePicker extends FrameLayout {
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate();
}
/ /
private void updateAmPmControl() {
if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE);
@ -457,7 +468,7 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setVisibility(View.VISIBLE);
}
}
//// 对与小时的算法
private void updateHourControl() {
if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);

@ -28,21 +28,21 @@ import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
//该类用于创建一个日期时间选择器对话框,并处理日期时间选择的事件。
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
private Calendar mDate = Calendar.getInstance();
private boolean mIs24HourView;
private OnDateTimeSetListener mOnDateTimeSetListener;
private DateTimePicker mDateTimePicker;
private boolean mIs24HourView;//一个布尔值,表示是否使用 24 小时制
private OnDateTimeSetListener mOnDateTimeSetListener;//用于处理日期时间设置的回调。
private DateTimePicker mDateTimePicker;//用于显示日期时间选择器。
//用于在日期时间设置完成时进行回调。
public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date);
}
//DateTimePickerDialog 类的构造函数接收一个 Context 对象和一个日期的长整型参数 date
public DateTimePickerDialog(Context context, long date) {
super(context);
mDateTimePicker = new DateTimePicker(context);
mDateTimePicker = new DateTimePicker(context);//用于显示日期时间选择器,并将其设置为对话框的视图。
setView(mDateTimePicker);
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month,
@ -60,18 +60,18 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
setButton(context.getString(R.string.datetime_dialog_ok), this);
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
set24HourView(DateFormat.is24HourFormat(this.getContext()));
set24HourView(DateFormat.is24HourFormat(this.getContext()));//调用 set24HourView() 方法,根据当前系统设置决定是否使用 24 小时制。
updateTitle(mDate.getTimeInMillis());
}
//设置是否使用 24 小时制。
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
}
//用于设置日期时间设置的回调监听器
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
//用于更新对话框的标题,以显示指定日期时间的格式化字符串。
private void updateTitle(long date) {
int flag =
DateUtils.FORMAT_SHOW_YEAR |
@ -80,7 +80,7 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
//用于处理点击对话框按钮的事件
public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());

@ -26,7 +26,7 @@ import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
//定义了一个名为 DropdownMenu 的类,用于创建一个下拉菜单。
public class DropdownMenu {
private Button mButton;
private PopupMenu mPopupMenu;
@ -44,17 +44,17 @@ public class DropdownMenu {
}
});
}
//设置下拉菜单项的点击事件监听器
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
//查找具有指定 ID 的菜单项,并返回对应的 MenuItem 对象。
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
//设置下拉菜单按钮的标题文本。
public void setTitle(CharSequence title) {
mButton.setText(title);
}

@ -28,8 +28,12 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
//CursorAdapter是Cursor和ListView的接口
//FoldersListAdapter继承了CursorAdapter的类
//主要作用是便签数据库和用户的交互
//这里就是用folder文件夹的形式展现给用户
public class FoldersListAdapter extends CursorAdapter {
////调用数据库中便签的ID和片段
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
@ -37,18 +41,20 @@ public class FoldersListAdapter extends CursorAdapter {
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1;
////数据库操作
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
@Override
//创建一个文件夹,对于各文件夹中子标签的初始化
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context);
}
@Override
//将各个布局文件绑定起来
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) {
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
@ -56,7 +62,7 @@ public class FoldersListAdapter extends CursorAdapter {
((FolderListItem) view).bind(folderName);
}
}
//根据数据库中标签的ID得到标签的各项内容
public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
@ -69,6 +75,7 @@ public class FoldersListAdapter extends CursorAdapter {
public FolderListItem(Context context) {
super(context);
inflate(context, R.layout.folder_list_item, this);
//根据布局文件的名字等信息将其找出来
mName = (TextView) findViewById(R.id.tv_folder_name);
}

File diff suppressed because it is too large Load Diff

@ -37,11 +37,13 @@ import net.micode.notes.R;
import java.util.HashMap;
import java.util.Map;
//继承edittext设置便签设置文本框
public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText";
private int mIndex;
private int mSelectionStartBeforeDelete;
//建立一个字符和整数的hash表用于链接电话网站还有邮箱
private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ;
@ -56,11 +58,13 @@ public class NoteEditText extends EditText {
/**
* 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
*/
//处理删除按键时的操作
void onEditTextDelete(int index, String text);
/**
@ -76,30 +80,32 @@ public class NoteEditText extends EditText {
}
private OnTextViewChangeListener mOnTextViewChangeListener;
//根据context设置文本
public NoteEditText(Context context) {
super(context, null);
mIndex = 0;
}
//设置当前光标
public void setIndex(int index) {
mIndex = index;
}
//初始化文本修改标记
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
//AttributeSet 百度了一下是自定义空控件属性,用于维护便签动态变化的属性
//初始化便签
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
// 根据defstyle自动初始化
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
@Override
//view里的函数处理手机屏幕的所有事件
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
@ -110,10 +116,11 @@ public class NoteEditText extends EditText {
y -= getTotalPaddingTop();
x += getScrollX();
y += getScrollY();
//用布局控件layout根据x,y的新值设置新的位置
Layout layout = getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
//更新光标新的位置
Selection.setSelection(getText(), off);
break;
}
@ -122,25 +129,31 @@ public class NoteEditText extends EditText {
}
@Override
//处理用户按下一个键盘按键时会触发 的事件
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
//根据按键的 Unicode 编码值来处理
case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) {
return false;
}
break;
case KeyEvent.KEYCODE_DEL:
//“删除”按键
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
break;
}
//继续执行父类的其他点击事件
return super.onKeyDown(keyCode, event);
}
@Override
//处理用户松开一个键盘按键时会触发 的事件
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
//根据按键的 Unicode 编码值来处理有删除和进入2种操作
case KeyEvent.KEYCODE_DEL:
if (mOnTextViewChangeListener != null) {
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
@ -167,51 +180,74 @@ public class NoteEditText extends EditText {
return super.onKeyUp(keyCode, event);
}
@Override
@Override
// 函数功能:当焦点发生变化时,会自动调用该方法来处理焦点改变的事件
// 参数focused表示触发该事件的View是否获得了焦点当该控件获得焦点时Focused等于true否则等于false。
// direction表示焦点移动的方向用数值表示
// Rect表示在触发事件的View的坐标系中前一个获得焦点的矩形区域即表示焦点是从哪里来的。如果不可用则为null
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) {
if (mOnTextViewChangeListener != null) {
//若监听器已经建立
if (!focused && TextUtils.isEmpty(getText())) {
//获取到焦点并且文本不为空
mOnTextViewChangeListener.onTextChange(mIndex, false);
//mOnTextViewChangeListener子函数置false隐藏事件选项
} else {
mOnTextViewChangeListener.onTextChange(mIndex, true);
//mOnTextViewChangeListener子函数置true显示事件选项
}
}
//继续执行父类的其他焦点变化的事件
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
//生成上下文菜单
protected void onCreateContextMenu(ContextMenu menu) {
if (getText() instanceof Spanned) {
//有文本存在
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
//获取文本开始和结尾位置
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
//获取开始到结尾的最大值和最小值
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
//设置url的信息的范围值
if (urls.length == 1) {
int defaultResId = 0;
for(String schema: sSchemaActionResMap.keySet()) {
//获取计划表中所有的key值
if(urls[0].getURL().indexOf(schema) >= 0) {
//若url可以添加则在添加后将defaultResId置为key所映射的值
defaultResId = sSchemaActionResMap.get(schema);
break;
}
}
if (defaultResId == 0) {
//defaultResId == 0则说明url并没有添加任何东西所以置为连接其他SchemaActionResMap的值
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;
}
});
}
}
//继续执行父类的其他菜单创建的事件
super.onCreateContextMenu(menu);
}
}

@ -25,9 +25,10 @@ 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 [] {
static final String [] PROJECTION = new String [] {//用于指定查询笔记项数据时需要返回的列。该数组包含了一系列笔记项属性的列名。
//表示笔记项数据在查询结果中的列索引。
NoteColumns.ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
@ -54,7 +55,7 @@ public class NoteItemData {
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;
@ -75,7 +76,7 @@ public class NoteItemData {
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;
//接收一个 Context 对象和一个 Cursor 对象作为参数。构造函数根据传入的 Cursor 对象从数据库中提取数据,并将数据赋值给相应的实例变量。
public NoteItemData(Context context, Cursor cursor) {
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
@ -92,6 +93,7 @@ public class NoteItemData {
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
//初始化电话号码的信息
mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
@ -108,6 +110,7 @@ public class NoteItemData {
}
checkPostion(cursor);
}
//根据鼠标的位置设置标记,和位置
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false;
@ -217,7 +220,7 @@ public class NoteItemData {
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
//用于从给定的 Cursor 对象中获取笔记项的类型。
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}

@ -14,8 +14,9 @@
* limitations under the License.
*/
package net.micode.notes.ui;
package net.micode.notes.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
@ -59,7 +60,7 @@ import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
@ -71,103 +72,115 @@ import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import net.micode.notes.widget.NoteWidgetProvider_2x;
import net.micode.notes.widget.NoteWidgetProvider_4x;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
//主界面,一进入就是这个界面
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener {
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { //没有用特定的标签加注释。。。感觉没有什么用
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;
private static final int FOLDER_LIST_QUERY_TOKEN = 1;
private static final int MENU_FOLDER_DELETE = 0;
private static final int MENU_FOLDER_VIEW = 1;
private static final int MENU_FOLDER_CHANGE_NAME = 2;
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; //单行超过80个字符
private enum ListEditState {
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
};
private ListEditState mState;
private BackgroundQueryHandler mBackgroundQueryHandler;
private NotesListAdapter mNotesListAdapter;
private ListView mNotesListView;
private Button mAddNewNote;
private boolean mDispatch;
private int mOriginY;
private int mDispatchY;
private TextView mTitleBar;
private long mCurrentFolderId;
private ContentResolver mContentResolver;
private ModeCallback mModeCallBack;
private static final String TAG = "NotesListActivity";
public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;
private NoteItemData mFocusNoteDataItem;
private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";
private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"
+ Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
+ NoteColumns.NOTES_COUNT + ">0)";
private final static int REQUEST_CODE_OPEN_NODE = 102;
private final static int REQUEST_CODE_NEW_NODE = 103;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 创建类
protected void onCreate(final Bundle savedInstanceState) { //需要是final类型 根据程序上下文环境Java关键字final有“这是无法改变的”或者“终态的”含义它可以修饰非抽象类、非抽象类成员方法和变量。你可能出于两种理解而需要阻止改变设计或效率。
// final类不能被继承没有子类final类中的方法默认是final的。
//final方法不能被子类的方法覆盖但可以被继承。
//final成员变量表示常量只能被赋值一次赋值后值不再改变。
//final不能用于修饰构造方法。
super.onCreate(savedInstanceState); // 调用父类的onCreate函数
setContentView(R.layout.note_list);
initResources();
/**
* Insert an introduction when user firstly use this application
*/
setAppInfoFromRawRes();
}
@Override
// 返回一些子模块完成的数据交给主Activity处理
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK
// 结果值 和 要求值 符合要求
if (resultCode == RESULT_OK
&& (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
mNotesListAdapter.changeCursor(null);
} else {
super.onActivityResult(requestCode, resultCode, data);
// 调用 Activity 的onActivityResult
}
}
private void setAppInfoFromRawRes() {
// Android平台给我们提供了一个SharedPreferences类它是一个轻量级的存储类特别适合用于保存软件配置参数。
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
StringBuilder sb = new StringBuilder();
InputStream in = null;
try {
in = getResources().openRawResource(R.raw.introduction);
// 把资源文件放到应用程序的/raw/raw下那么就可以在应用中使用getResources获取资源后,
// 以openRawResource方法不带后缀的资源文件名打开这个文件。
in = getResources().openRawResource(R.raw.introduction);
if (in != null) {
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
char [] buf = new char[1024];
char [] buf = new char[1024]; // 自行定义的数值,使用者不知道有什么意义
int len = 0;
while ((len = br.read(buf)) > 0) {
sb.append(buf, 0, len);
@ -180,7 +193,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
e.printStackTrace();
return;
} finally {
if(in != null) {
if (in != null) {
try {
in.close();
} catch (IOException e) {
@ -189,12 +202,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
}
// 创建空的WorkingNote
WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,
AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
ResourceParser.RED);
note.setWorkingText(sb.toString());
if (note.saveNote()) {
// 更新保存note的信息
sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
} else {
Log.e(TAG, "Save introduction note error");
@ -202,25 +217,28 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
}
@Override
protected void onStart() {
super.onStart();
startAsyncNotesListQuery();
}
// 初始化资源
private void initResources() {
mContentResolver = this.getContentResolver();
mContentResolver = this.getContentResolver(); // 获取应用程序的数据,得到类似数据表的东西
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mNotesListView = (ListView) findViewById(R.id.notes_list);
// findViewById 是安卓编程的定位函数,主要是引用.R文件里的引用名
mNotesListView = (ListView) findViewById(R.id.notes_list); // 绑定XML中的ListView作为Item的容器
mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null),
null, false);
mNotesListView.setOnItemClickListener(new OnListItemClickListener());
mNotesListView.setOnItemLongClickListener(this);
mNotesListAdapter = new NotesListAdapter(this);
mNotesListView.setAdapter(mNotesListAdapter);
mAddNewNote = (Button) findViewById(R.id.btn_new_note);
mAddNewNote = (Button) findViewById(R.id.btn_new_note);// 在activity中要获取该按钮
mAddNewNote.setOnClickListener(this);
mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());
mDispatch = false;
@ -230,12 +248,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mState = ListEditState.NOTE_LIST;
mModeCallBack = new ModeCallback();
}
// 继承自ListView.MultiChoiceModeListener 和 OnMenuItemClickListener
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
private DropdownMenu mDropDownMenu;
private ActionMode mActionMode;
private MenuItem mMoveMenu;
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getMenuInflater().inflate(R.menu.note_list_options, menu);
menu.findItem(R.id.delete).setOnMenuItemClickListener(this);
@ -251,7 +270,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mNotesListAdapter.setChoiceMode(true);
mNotesListView.setLongClickable(false);
mAddNewNote.setVisibility(View.GONE);
View customView = LayoutInflater.from(NotesListActivity.this).inflate(
R.layout.note_list_dropdown_menu, null);
mode.setCustomView(customView);
@ -259,21 +278,22 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
(Button) customView.findViewById(R.id.selection_menu),
R.menu.note_list_dropdown);
mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(MenuItem item) {
public boolean onMenuItemClick(final MenuItem item) {
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
updateMenu();
return true;
}
});
return true;
}
// 更新菜单
private void updateMenu() {
int selectedCount = mNotesListAdapter.getSelectedCount();
// Update dropdown menu
String format = getResources().getString(R.string.menu_select_title, selectedCount);
mDropDownMenu.setTitle(format);
mDropDownMenu.setTitle(format); // 更改标题
MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);
if (item != null) {
if (mNotesListAdapter.isAllSelected()) {
@ -285,40 +305,40 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
return false;
}
public void onDestroyActionMode(ActionMode mode) {
mNotesListAdapter.setChoiceMode(false);
mNotesListView.setLongClickable(true);
mAddNewNote.setVisibility(View.VISIBLE);
}
public void finishActionMode() {
mActionMode.finish();
}
public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
boolean checked) {
mNotesListAdapter.setCheckedItem(position, checked);
updateMenu();
}
public boolean onMenuItemClick(MenuItem item) {
if (mNotesListAdapter.getSelectedCount() == 0) {
Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),
Toast.LENGTH_SHORT).show();
return true;
}
switch (item.getItemId()) {
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
@ -345,9 +365,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true;
}
}
private class NewNoteOnTouchListener implements OnTouchListener {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
@ -366,7 +386,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
/**
* HACKME:When click the transparent part of "New Note" button, dispatch
* the event to the list view behind this button. The transparent part of
* "New Note" button could be expressed by formula y=-0.12x+94Unit:pixel
* "New Note" button could be expressed by formula y=-0.12x+94nit:pixel<EFBFBD>
* and the line top of the button. The coordinate based on left of the "New
* Note" button. The 94 represents maximum height of the transparent part.
* Notice that, if the background of the button changes, the formula should
@ -405,9 +425,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
return false;
}
};
private void startAsyncNotesListQuery() {
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
: NORMAL_SELECTION;
@ -416,12 +436,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
String.valueOf(mCurrentFolderId)
}, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
}
private final class BackgroundQueryHandler extends AsyncQueryHandler {
public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch (token) {
@ -440,13 +460,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
}
private void showFolderListMenu(Cursor cursor) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(R.string.menu_title_select_folder);
final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DataUtils.batchMoveToFolder(mContentResolver,
mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which));
@ -461,14 +481,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
});
builder.show();
}
private void createNewNote() {
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);
this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
}
private void batchDelete() {
new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
@ -490,7 +510,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
return widgets;
}
@Override
protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) {
if (widgets != null) {
@ -505,13 +525,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}.execute();
}
private void deleteFolder(long folderId) {
if (folderId == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Wrong folder id, should not happen " + folderId);
return;
}
HashSet<Long> ids = new HashSet<Long>();
ids.add(folderId);
HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver,
@ -532,14 +552,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
}
private void openNode(NoteItemData data) {
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, data.getId());
this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
}
private void openFolder(NoteItemData data) {
mCurrentFolderId = data.getId();
startAsyncNotesListQuery();
@ -556,7 +576,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
mTitleBar.setVisibility(View.VISIBLE);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_new_note:
@ -566,19 +586,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
break;
}
}
private void showSoftInput() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
private void hideSoftInput(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
private void showCreateOrModifyFolderDialog(final boolean create) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
@ -596,14 +616,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
etName.setText("");
builder.setTitle(this.getString(R.string.menu_create_folder));
}
builder.setPositiveButton(android.R.string.ok, null);
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
hideSoftInput(etName);
}
});
final Dialog dialog = builder.setView(view).show();
final Button positive = (Button)dialog.findViewById(android.R.id.button1);
positive.setOnClickListener(new OnClickListener() {
@ -636,7 +656,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
dialog.dismiss();
}
});
if (TextUtils.isEmpty(etName.getText())) {
positive.setEnabled(false);
}
@ -646,9 +666,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
etName.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (TextUtils.isEmpty(etName.getText())) {
positive.setEnabled(false);
@ -656,17 +676,20 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
positive.setEnabled(true);
}
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
/* (non-Javadoc)
* @see android.app.Activity#onBackPressed()
*
*/
@Override
public void onBackPressed() {
switch (mState) {
public void onBackPressed() { switch (mState) {
case SUB_FOLDER:
mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mState = ListEditState.NOTE_LIST;
@ -687,7 +710,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
break;
}
}
/**
* @param appWidgetId
* @param appWidgetType
* widgetintent
*/
private void updateWidget(int appWidgetId, int appWidgetType) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (appWidgetType == Notes.TYPE_WIDGET_2X) {
@ -698,15 +726,18 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
Log.e(TAG, "Unspported widget type");
return;
}
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
appWidgetId
});
sendBroadcast(intent);
setResult(RESULT_OK, intent);
}
/**
*
*/
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (mFocusNoteDataItem != null) {
@ -717,7 +748,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
};
@Override
public void onContextMenuClosed(Menu menu) {
if (mNotesListView != null) {
@ -725,7 +756,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
super.onContextMenuClosed(menu);
}
/* (non-Javadoc)
* @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
* menu
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
if (mFocusNoteDataItem == null) {
@ -734,10 +769,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
switch (item.getItemId()) {
case MENU_FOLDER_VIEW:
openFolder(mFocusNoteDataItem);
openFolder(mFocusNoteDataItem);//打开对应文件
break;
case MENU_FOLDER_DELETE:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);//设置确认是否删除的对话框
builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_folder));
@ -748,7 +783,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.show();
builder.show();//显示对话框
break;
case MENU_FOLDER_CHANGE_NAME:
showCreateOrModifyFolderDialog(false);
@ -756,10 +791,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
default:
break;
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
@ -777,7 +812,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
@ -817,22 +852,29 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
return true;
}
/* (non-Javadoc)
* @see android.app.Activity#onSearchRequested()
* startSearch
*/
@Override
public boolean onSearchRequested() {
startSearch(null, false, null /* appData */, false);
return true;
}
/**
* 便
*/
private void exportNoteToText() {
final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
new AsyncTask<Void, Void, Integer>() {
@Override
protected Integer doInBackground(Void... unused) {
return backup.exportToText();
}
@Override
protected void onPostExecute(Integer result) {
if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {
@ -862,22 +904,33 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.show();
}
}
}.execute();
}
/**
* @return
*
*/
private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
}
/**
* PreferenceActivity
*/
private void startPreferenceActivity() {
Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, NotesPreferenceActivity.class);
from.startActivityIfNeeded(intent, -1);
}
/**
* @author k
* 便
*/
private class OnListItemClickListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) {
NoteItemData item = ((NotesListItem) view).getItemData();
@ -889,7 +942,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
return;
}
switch (mState) {
case NOTE_LIST:
if (item.getType() == Notes.TYPE_FOLDER
@ -914,14 +967,17 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
}
}
/**
*
*/
private void startQueryDestinationFolders() {
String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
selection = (mState == ListEditState.NOTE_LIST) ? selection:
"(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")";
mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN,
null,
Notes.CONTENT_NOTE_URI,
@ -934,7 +990,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
},
NoteColumns.MODIFIED_DATE + " DESC");
}
/* (non-Javadoc)
* @see android.widget.AdapterView.OnItemLongClickListener#onItemLongClick(android.widget.AdapterView, android.view.View, int, long)
*
* 便ActionModeContextMenu
* ActionMOdeContextMenu
*/
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) {
mFocusNoteDataItem = ((NotesListItem) view).getItemData();

@ -30,19 +30,19 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
//NotesListAdapter 类是一个自定义的适配器类,用于将数据源中的数据绑定到列表项的视图上,并提供了一些方法来操作选择项、获取选择的数据等。
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;
//桌面widget的属性包括编号和类型
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
};
//初始化便签链接器
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
@ -51,11 +51,13 @@ public class NotesListAdapter extends CursorAdapter {
}
@Override
//新建一个视图来存储光标所指向的数据
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context);
}
@Override
//将已经存在的视图和鼠标指向的数据进行捆绑
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor);
@ -63,21 +65,23 @@ public class NotesListAdapter extends CursorAdapter {
isSelectedItem(cursor.getPosition()));
}
}
//设置勾选框
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked);
notifyDataSetChanged();
}
//判断单选按钮是否勾选
public boolean isInChoiceMode() {
return mChoiceMode;
}
//设置单项选项框
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear();
mChoiceMode = mode;
}
//选择全部选项
public void selectAll(boolean checked) {
Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) {
@ -88,7 +92,7 @@ public class NotesListAdapter extends CursorAdapter {
}
}
}
//建立选择项的下标列表
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) {
@ -104,7 +108,7 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
//建立桌面Widget的选项表
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) {
@ -127,7 +131,7 @@ public class NotesListAdapter extends CursorAdapter {
}
return itemSet;
}
//获取选项个数
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
@ -142,12 +146,12 @@ public class NotesListAdapter extends CursorAdapter {
}
return count;
}
//判断是否全部选中
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount);
}
//判断是否为选项表
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false;
@ -160,13 +164,13 @@ public class NotesListAdapter extends CursorAdapter {
super.onContentChanged();
calcNotesCount();
}
//在activity光标发生局部变动的时候回调该函数计算便签的数量
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
calcNotesCount();
}
//计算便签数量
private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {

@ -29,7 +29,7 @@ import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
//NotesListItem 类是一个自定义的列表项视图类,用于显示笔记列表中的每一项。它根据传入的数据项,设置视图的显示内容和样式,同时提供了一个方法来获取列表项的数据对象。
public class NotesListItem extends LinearLayout {
private ImageView mAlert;
private TextView mTitle;

@ -15,7 +15,7 @@
*/
package net.micode.notes.ui;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActionBar;
@ -41,108 +41,151 @@ import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
/*
*NotesPreferenceActivity便
* PreferenceActivityActivity
*/
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;
//账户的hash标记
@Override
/*
*activity
*Bundle icicle activity
*
*/
protected void onCreate(Bundle icicle) {
//先执行父类的创建函数
super.onCreate(icicle);
/* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true);
//给左上角图标的左边加上一个返回的图标
addPreferencesFromResource(R.xml.preferences);
//添加xml来源并显示 xml
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
//根据同步账户关键码来初始化分组
mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter);
//初始化同步组件
mOriAccounts = null;
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
//获取listvivewListView的作用:用于列出所有选择
getListView().addHeaderView(header, null, true);
//在listview组件上方添加其他组件
}
@Override
/*
* activity
*
*/
protected void onResume() {
//先执行父类 的交互实现
super.onResume();
// need to set sync account automatically if user has added a new
// account
if (mHasAddedAccount) {
//若用户新加了账户则自动设置同步账户
Account[] accounts = getGoogleAccounts();
//获取google同步账户
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
for (Account accountNew : accounts) {
//若原账户不为空且当前账户有增加
for (Account accountNew : accounts) {
boolean found = false;
for (Account accountOld : mOriAccounts) {
if (TextUtils.equals(accountOld.name, accountNew.name)) {
//更新账户
found = true;
break;
}
}
if (!found) {
setSyncAccount(accountNew.name);
//若是没有找到旧的账户,那么同步账号中就只添加新账户
break;
}
}
}
}
refreshUI();
//刷新标签界面
}
@Override
/*
* activity
*
*/
protected void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
//注销接收器
}
super.onDestroy();
//执行父类的销毁动作
}
/*
*
*
*/
private void loadAccountPreference() {
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));
//设置首选项的大标题和小标题
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
//建立监听器
if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account
//若是第一次建立账户显示选择账户提示对话框
showSelectAccountAlertDialog();
} else {
// if the account has already been set, we need to promp
// user about the risk
//若是已经建立则显示修改对话框并进行修改操作
showChangeAccountConfirmAlertDialog();
}
} else {
//若在没有同步的情况下则在toast中显示不能修改
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
@ -150,22 +193,30 @@ public class NotesPreferenceActivity extends PreferenceActivity {
return true;
}
});
//根据新建首选项编辑新的账户分组
mAccountCategory.addPreference(accountPref);
}
/*
*
*
*/
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
//获取同步按钮控件和最终同步时间的的窗口
// set button state
//设置按钮的状态
if (GTaskSyncService.isSyncing()) {
//若是在同步状态下
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}
});
//设置按钮显示的文本为“取消同步”以及监听器
} else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() {
@ -173,50 +224,67 @@ public class NotesPreferenceActivity extends PreferenceActivity {
GTaskSyncService.startSync(NotesPreferenceActivity.this);
}
});
//若是不同步则设置按钮显示的文本为“立即同步”以及对应监听器
}
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
//设置按键可用还是不可用
// set last sync time
// 设置最终同步时间
if (GTaskSyncService.isSyncing()) {
//若是在同步的情况下
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE);
// 根据当前同步服务器设置时间显示框的文本以及可见性
} else {
//若是非同步情况
long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) {
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime)));
lastSyncTimeView.setVisibility(View.VISIBLE);
//则根据最后同步时间的信息来编辑时间显示框的文本内容和可见性
} else {
//若时间为空直接设置为不可见状态
lastSyncTimeView.setVisibility(View.GONE);
}
}
}
/*
*
*
*/
private void refreshUI() {
loadAccountPreference();
loadSyncButton();
}
/*
*
*
*/
private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
//创建一个新的对话框
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
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);
//设置对话框的自定义标题建立一个YES的按钮
Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this);
//获取同步账户信息
mOriAccounts = accounts;
mHasAddedAccount = false;
if (accounts.length > 0) {
//若账户不为空
CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items;
int checkedItem = -1;
@ -224,84 +292,120 @@ public class NotesPreferenceActivity extends PreferenceActivity {
for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index;
//在账户列表中查询到所需账户
}
items[index++] = account.name;
}
dialogBuilder.setSingleChoiceItems(items, checkedItem,
//在对话框建立一个单选的复选框
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString());
dialog.dismiss();
//取消对话框
refreshUI();
}
//设置点击后执行的事件,包括检录新同步账户和刷新标签界面
});
//建立对话框网络版的监听器
}
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView);
//给新加账户对话框设置自定义样式
final AlertDialog dialog = dialogBuilder.show();
//显示对话框
addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mHasAddedAccount = true;
//将新加账户的hash置true
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
//建立网络建立组件
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls"
});
startActivityForResult(intent, -1);
//跳回上一个选项
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);
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);
//设置对话框的自定义标题
CharSequence[] menuItemArray = new CharSequence[] {
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() {
//设置对话框要显示的一个list用于显示几个命令时,即changeremovecancel
public void onClick(DialogInterface dialog, int which) {
//按键功能由which来决定
if (which == 0) {
//进入账户选择对话框
showSelectAccountAlertDialog();
} else if (which == 1) {
//删除账户并且跟新便签界面
removeSyncAccount();
refreshUI();
}
}
});
dialogBuilder.show();
//显示对话框
}
/*
*
*
*/
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
}
/*
*
*
*/
private void setSyncAccount(String account) {
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);
} else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
//将该账号加入到首选项中
editor.commit();
// clean up last sync time
//提交修改的数据
setLastSyncTime(this, 0);
//将最后同步时间清零
// clean up local gtask related info
new Thread(new Runnable() {
public void run() {
@ -311,24 +415,34 @@ public class NotesPreferenceActivity extends PreferenceActivity {
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的文本信息置为“设置账户成功”并显示出来
}
}
/*
*
*
*/
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
//设置共享首选项
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
//假如当前首选项中有账户就删除
}
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME);
//删除当前首选项中有账户时间
}
editor.commit();
//提交更新后的数据
// clean up local gtask related info
new Thread(new Runnable() {
public void run() {
@ -338,51 +452,79 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
//重置当地同步任务的信息
}
/*
*
*
*/
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
/*
*
*
*/
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
// 从共享首选项中找到相关账户并获取其编辑器
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit();
//编辑最终同步时间并提交更新
}
/*
*
*
*/
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
/*
*
* BroadcastReceiver
*/
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
//获取随广播而来的Intent中的同步服务的数据
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
//通过获取的数据在设置系统的状态
}
}
}
/*
*
*
* :MenuItem
*/
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//根据选项的id选择这里只有一个主页
case android.R.id.home:
Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
//在主页情况下在创建连接组件intent发出清空的信号并开始一个相应的activity
default:
return false;
}
}
}

@ -31,7 +31,7 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;
//NoteWidgetProvider 类是一个抽象类用于作为自定义小部件的提供者。它定义了一些常量和方法用于更新小部件的视图并提供了抽象方法供子类实现以返回特定的背景资源ID、布局ID和小部件类型
public abstract class NoteWidgetProvider extends AppWidgetProvider {
public static final String [] PROJECTION = new String [] {
NoteColumns.ID,

@ -15,7 +15,6 @@
*/
package net.micode.notes.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
@ -23,7 +22,7 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
//NoteWidgetProvider_2x 类是一个具体的小部件提供者类,它继承自 NoteWidgetProvider。它重写了父类的一些方法并提供了特定的布局资源ID、背景资源ID和小部件类型。通过创建该类的实例并在应用程序的清单文件中声明该小部件提供者可以创建一个 2x 大小的小部件,并在更新时使用指定的布局和背景资源
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

@ -23,7 +23,7 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
// NoteWidgetProvider_4x 类是一个具体的小部件提供者类,它继承自 NoteWidgetProvider。它重写了父类的一些方法并提供了特定的布局资源ID、背景资源ID和小部件类型。
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

Loading…
Cancel
Save